org.springframework.beans.BeanWrapper

Here are the examples of the java api org.springframework.beans.BeanWrapper taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

140 Examples 7

19 View Source File : FameUtil.java
License : MIT License
Project Creator : zzzzbw

/**
 * 获取Null属性名称
 *
 * @param source 对象
 * @return Null属性名称
 */
public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    Set<String> emptyNames = new HashSet<String>();
    for (java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) {
            emptyNames.add(pd.getName());
        }
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

19 View Source File : FlywayPropertiesTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private Map<String, PropertyDescriptor> indexProperties(BeanWrapper beanWrapper) {
    Map<String, PropertyDescriptor> descriptor = new HashMap<>();
    for (PropertyDescriptor propertyDescriptor : beanWrapper.getPropertyDescriptors()) {
        descriptor.put(propertyDescriptor.getName(), propertyDescriptor);
    }
    ignoreProperties(descriptor, "clreplaced");
    return descriptor;
}

19 View Source File : BeanUtil.java
License : Apache License 2.0
Project Creator : yin5980280

public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper beanWrapper = new BeanWrapperImpl(source);
    PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();
    Set<String> emptyNames = new HashSet<>();
    for (PropertyDescriptor pd : pds) {
        Object srcValue = beanWrapper.getPropertyValue(pd.getName());
        if (srcValue == null) {
            emptyNames.add(pd.getName());
        }
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

19 View Source File : BeanUtils.java
License : Apache License 2.0
Project Creator : xjjdog

static String[] getNullPropertyNames(Object source) {
    final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
    return Stream.of(wrappedSource.getPropertyDescriptors()).map(FeatureDescriptor::getName).filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null).toArray(String[]::new);
}

19 View Source File : HttpServletBean.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Initialize the BeanWrapper for this HttpServletBean,
 * possibly with custom editors.
 * <p>This default implementation is empty.
 * @param bw the BeanWrapper to initialize
 * @throws BeansException if thrown by BeanWrapper methods
 * @see org.springframework.beans.BeanWrapper#registerCustomEditor
 */
protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
}

19 View Source File : GenericFilterBean.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Initialize the BeanWrapper for this GenericFilterBean,
 * possibly with custom editors.
 * <p>This default implementation is empty.
 * @param bw the BeanWrapper to initialize
 * @throws BeansException if thrown by BeanWrapper methods
 * @see org.springframework.beans.BeanWrapper#registerCustomEditor
 */
protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
}

19 View Source File : BeanPropertySqlParameterSource.java
License : MIT License
Project Creator : Vip-Augus

/**
 * {@link SqlParameterSource} implementation that obtains parameter values
 * from bean properties of a given JavaBean object. The names of the bean
 * properties have to match the parameter names.
 *
 * <p>Uses a Spring BeanWrapper for bean property access underneath.
 *
 * @author Thomas Risberg
 * @author Juergen Hoeller
 * @since 2.0
 * @see NamedParameterJdbcTemplate
 * @see org.springframework.beans.BeanWrapper
 */
public clreplaced BeanPropertySqlParameterSource extends AbstractSqlParameterSource {

    private final BeanWrapper beanWrapper;

    @Nullable
    private String[] propertyNames;

    /**
     * Create a new BeanPropertySqlParameterSource for the given bean.
     * @param object the bean instance to wrap
     */
    public BeanPropertySqlParameterSource(Object object) {
        this.beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
    }

    @Override
    public boolean hasValue(String paramName) {
        return this.beanWrapper.isReadableProperty(paramName);
    }

    @Override
    @Nullable
    public Object getValue(String paramName) throws IllegalArgumentException {
        try {
            return this.beanWrapper.getPropertyValue(paramName);
        } catch (NotReadablePropertyException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    }

    /**
     * Derives a default SQL type from the corresponding property type.
     * @see org.springframework.jdbc.core.StatementCreatorUtils#javaTypeToSqlParameterType
     */
    @Override
    public int getSqlType(String paramName) {
        int sqlType = super.getSqlType(paramName);
        if (sqlType != TYPE_UNKNOWN) {
            return sqlType;
        }
        Clreplaced<?> propType = this.beanWrapper.getPropertyType(paramName);
        return StatementCreatorUtils.javaTypeToSqlParameterType(propType);
    }

    @Override
    @NonNull
    public String[] getParameterNames() {
        return getReadablePropertyNames();
    }

    /**
     * Provide access to the property names of the wrapped bean.
     * Uses support provided in the {@link PropertyAccessor} interface.
     * @return an array containing all the known property names
     */
    public String[] getReadablePropertyNames() {
        if (this.propertyNames == null) {
            List<String> names = new ArrayList<>();
            PropertyDescriptor[] props = this.beanWrapper.getPropertyDescriptors();
            for (PropertyDescriptor pd : props) {
                if (this.beanWrapper.isReadableProperty(pd.getName())) {
                    names.add(pd.getName());
                }
            }
            this.propertyNames = StringUtils.toStringArray(names);
        }
        return this.propertyNames;
    }
}

19 View Source File : BeanPropertyRowMapper.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Initialize the given BeanWrapper to be used for row mapping.
 * To be called for each row.
 * <p>The default implementation applies the configured {@link ConversionService},
 * if any. Can be overridden in subclreplacedes.
 * @param bw the BeanWrapper to initialize
 * @see #getConversionService()
 * @see BeanWrapper#setConversionService
 */
protected void initBeanWrapper(BeanWrapper bw) {
    ConversionService cs = getConversionService();
    if (cs != null) {
        bw.setConversionService(cs);
    }
}

19 View Source File : BeanPropertyBindingResult.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Default implementation of the {@link Errors} and {@link BindingResult}
 * interfaces, for the registration and evaluation of binding errors on
 * JavaBean objects.
 *
 * <p>Performs standard JavaBean property access, also supporting nested
 * properties. Normally, application code will work with the
 * {@code Errors} interface or the {@code BindingResult} interface.
 * A {@link DataBinder} returns its {@code BindingResult} via
 * {@link DataBinder#getBindingResult()}.
 *
 * @author Juergen Hoeller
 * @since 2.0
 * @see DataBinder#getBindingResult()
 * @see DataBinder#initBeanPropertyAccess()
 * @see DirectFieldBindingResult
 */
@SuppressWarnings("serial")
public clreplaced BeanPropertyBindingResult extends AbstractPropertyBindingResult implements Serializable {

    @Nullable
    private final Object target;

    private final boolean autoGrowNestedPaths;

    private final int autoGrowCollectionLimit;

    @Nullable
    private transient BeanWrapper beanWrapper;

    /**
     * Creates a new instance of the {@link BeanPropertyBindingResult} clreplaced.
     * @param target the target bean to bind onto
     * @param objectName the name of the target object
     */
    public BeanPropertyBindingResult(@Nullable Object target, String objectName) {
        this(target, objectName, true, Integer.MAX_VALUE);
    }

    /**
     * Creates a new instance of the {@link BeanPropertyBindingResult} clreplaced.
     * @param target the target bean to bind onto
     * @param objectName the name of the target object
     * @param autoGrowNestedPaths whether to "auto-grow" a nested path that contains a null value
     * @param autoGrowCollectionLimit the limit for array and collection auto-growing
     */
    public BeanPropertyBindingResult(@Nullable Object target, String objectName, boolean autoGrowNestedPaths, int autoGrowCollectionLimit) {
        super(objectName);
        this.target = target;
        this.autoGrowNestedPaths = autoGrowNestedPaths;
        this.autoGrowCollectionLimit = autoGrowCollectionLimit;
    }

    @Override
    @Nullable
    public final Object getTarget() {
        return this.target;
    }

    /**
     * Returns the {@link BeanWrapper} that this instance uses.
     * Creates a new one if none existed before.
     * @see #createBeanWrapper()
     */
    @Override
    public final ConfigurablePropertyAccessor getPropertyAccessor() {
        if (this.beanWrapper == null) {
            this.beanWrapper = createBeanWrapper();
            this.beanWrapper.setExtractOldValueForEditor(true);
            this.beanWrapper.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
            this.beanWrapper.setAutoGrowCollectionLimit(this.autoGrowCollectionLimit);
        }
        return this.beanWrapper;
    }

    /**
     * Create a new {@link BeanWrapper} for the underlying target object.
     * @see #getTarget()
     */
    protected BeanWrapper createBeanWrapper() {
        if (this.target == null) {
            throw new IllegalStateException("Cannot access properties on null bean instance '" + getObjectName() + "'");
        }
        return PropertyAccessorFactory.forBeanPropertyAccess(this.target);
    }
}

19 View Source File : ConstructorResolver.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw, Executable executable, Object[] argsToResolve, boolean fallback) {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Clreplaced<?>[] paramTypes = executable.getParameterTypes();
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forExecutable(executable, argIndex);
        GenericTypeResolver.resolveParameterType(methodParam, executable.getDeclaringClreplaced());
        if (argValue instanceof AutowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter, fallback);
        } else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        } else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Clreplaced<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        } catch (TypeMismatchException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClreplacedName(argValue) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}

19 View Source File : ConstructorResolver.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Create an array of arguments to invoke a constructor or factory method,
 * given the resolved constructor argument values.
 */
private ArgumentsHolder createArgumentArray(String beanName, RootBeanDefinition mbd, @Nullable ConstructorArgumentValues resolvedValues, BeanWrapper bw, Clreplaced<?>[] paramTypes, @Nullable String[] paramNames, Executable executable, boolean autowiring, boolean fallback) throws UnsatisfiedDependencyException {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        Clreplaced<?> paramType = paramTypes[paramIndex];
        String paramName = (paramNames != null ? paramNames[paramIndex] : "");
        // Try to find matching constructor argument value, either indexed or generic.
        ConstructorArgumentValues.ValueHolder valueHolder = null;
        if (resolvedValues != null) {
            valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
            // If we couldn't find a direct match and are not supposed to autowire,
            // let's try the next generic, untyped argument value as fallback:
            // it could match after type conversion (for example, String -> int).
            if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
                valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
            }
        }
        if (valueHolder != null) {
            // We found a potential match - let's give it a try.
            // Do not consider the same value definition multiple times!
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            if (valueHolder.isConverted()) {
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            } else {
                MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
                try {
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                } catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClreplacedName(valueHolder.getValue()) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
                Object sourceHolder = valueHolder.getSource();
                if (sourceHolder instanceof ConstructorArgumentValues.ValueHolder) {
                    Object sourceValue = ((ConstructorArgumentValues.ValueHolder) sourceHolder).getValue();
                    args.resolveNecessary = true;
                    args.preparedArguments[paramIndex] = sourceValue;
                }
            }
            args.arguments[paramIndex] = convertedValue;
            args.rawArguments[paramIndex] = originalValue;
        } else {
            MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
            // No explicit match found: we're either supposed to autowire or
            // have to fail creating an argument array for the given constructor.
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Ambiguous argument values for parameter of type [" + paramType.getName() + "] - did you specify the correct bean references as arguments?");
            }
            try {
                Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter, fallback);
                args.rawArguments[paramIndex] = autowiredArgument;
                args.arguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = new AutowiredArgumentMarker();
                args.resolveNecessary = true;
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
            }
        }
    }
    for (String autowiredBeanName : autowiredBeanNames) {
        this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (logger.isDebugEnabled()) {
            logger.debug("Autowiring by type from bean name '" + beanName + "' via " + (executable instanceof Constructor ? "constructor" : "factory method") + " to bean named '" + autowiredBeanName + "'");
        }
    }
    return args;
}

19 View Source File : ObjectPdxInstanceAdapter.java
License : Apache License 2.0
Project Creator : spring-projects

/**
 * A {@link PdxInstance} implementation that adapts (wraps) a non-null {@link Object} as a {@link PdxInstance}.
 *
 * @author John Blum
 * @see java.beans.PropertyDescriptor
 * @see java.lang.reflect.Field
 * @see org.apache.geode.pdx.PdxInstance
 * @see org.apache.geode.pdx.WritablePdxInstance
 * @see org.springframework.beans.BeanWrapper
 * @see org.springframework.beans.PropertyAccessor
 * @see org.springframework.beans.PropertyAccessorFactory
 * @since 1.3.0
 */
public clreplaced ObjectPdxInstanceAdapter implements PdxInstance {

    protected static final String CLreplaced_PROPERTY_NAME = "clreplaced";

    protected static final String ID_PROPERTY_NAME = "id";

    private static void replacedertCondition(boolean condition, Supplier<RuntimeException> runtimeExceptionSupplier) {
        if (!condition) {
            throw runtimeExceptionSupplier.get();
        }
    }

    /**
     * Factory method used to construct a new instance of the {@link ObjectPdxInstanceAdapter} from
     * the given {@literal target} {@link Object}.
     *
     * @param target {@link Object} to adapt as a {@link PdxInstance}; must not be {@literal null}.
     * @return a new instance of {@link ObjectPdxInstanceAdapter}.
     * @throws IllegalArgumentException if {@link Object} is {@literal null}.
     * @see #ObjectPdxInstanceAdapter(Object)
     */
    public static ObjectPdxInstanceAdapter from(@NonNull Object target) {
        return new ObjectPdxInstanceAdapter(target);
    }

    /**
     * Null-safe factory method used to unwrap the given {@link PdxInstance}, returning the underlying, target
     * {@link PdxInstance#getObject() Object} upon which this {@link PdxInstance} is based.
     *
     * @param pdxInstance {@link PdxInstance} to unwrap.
     * @return the underlying, target {@link PdxInstance#getObject() Object} from the given {@link PdxInstance}.
     * @see org.apache.geode.pdx.PdxInstance
     */
    @Nullable
    public static Object unwrap(@Nullable PdxInstance pdxInstance) {
        return pdxInstance instanceof ObjectPdxInstanceAdapter ? pdxInstance.getObject() : pdxInstance;
    }

    private final AtomicReference<String> resolvedIdenreplacedyFieldName = new AtomicReference<>(null);

    private transient final BeanWrapper beanWrapper;

    private final Object target;

    /**
     * Constructs a new instance of {@link ObjectPdxInstanceAdapter} initialized with the given {@link Object}.
     *
     * @param target {@link Object} to adapt as a {@link PdxInstance}; must not be {@literal null}.
     * @throws IllegalArgumentException if {@link Object} is {@literal null}.
     * @see java.lang.Object
     */
    public ObjectPdxInstanceAdapter(Object target) {
        replacedert.notNull(target, "Object to adapt must not be null");
        this.target = target;
        this.beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(target);
    }

    /**
     * Returns a {@link BeanWrapper} wrapping the {@literal target} {@link Object} in order to access the {@link Object}
     * as a Java bean using JavaBeans conventions.
     *
     * @return a {@link BeanWrapper} for the {@literal target} {@link Object}; never {@literal null}.
     * @see org.springframework.beans.BeanWrapper
     */
    @NonNull
    protected BeanWrapper getBeanWrapper() {
        return this.beanWrapper;
    }

    /**
     * Returns the {@link Clreplaced#getName()} of the underlying, target {@link Object}.
     *
     * @return the {@link Clreplaced#getName()} of the underlying, target {@link Object}.
     * @see java.lang.Object#getClreplaced()
     * @see java.lang.Clreplaced#getName()
     * @see #getObject()
     */
    @Override
    public String getClreplacedName() {
        return getObject().getClreplaced().getName();
    }

    /**
     * Determines whether this {@link PdxInstance} can be deserialized back into an {@link Object}.
     *
     * This method effectively returns {@literal true} since this {@link PdxInstance} implementation is an adapter
     * for an underlying, target {@link Object} in the first place.
     *
     * @return a boolean value indicating whether this {@link PdxInstance} can be deserialized
     * back into an {@link Object}.
     * @see #getObject()
     */
    @Override
    public boolean isDeserializable() {
        return getObject() != null;
    }

    /**
     * Determines whether the underlying, target {@link Object} is an {@link Enum enumerated value} {@link Clreplaced type}.
     *
     * @return a boolean value indicating whether the underlying, target {@link Object}
     * is an {@link Enum enumerated value} {@link Clreplaced type}.
     * @see java.lang.Object#getClreplaced()
     * @see java.lang.Clreplaced#isEnum()
     * @see #getObject()
     */
    @Override
    public boolean isEnum() {
        return getObject().getClreplaced().isEnum();
    }

    /**
     * Returns the {@link Object value} for the {@link PropertyDescriptor property} identified by
     * the given {@link String field name} on the underlying, target {@link Object}.
     *
     * @param fieldName {@link String} containing the name of the field to get the {@link Object value} for.
     * @return the {@link Object value} for the {@link PropertyDescriptor property} identified by
     * the given {@link String field name} on the underlying, target {@link Object}.
     * @see org.springframework.beans.BeanWrapper#getPropertyValue(String)
     * @see #getBeanWrapper()
     */
    @Override
    public Object getField(String fieldName) {
        BeanWrapper beanWrapper = getBeanWrapper();
        return beanWrapper.isReadableProperty(fieldName) ? beanWrapper.getPropertyValue(fieldName) : null;
    }

    /**
     * Returns a {@link List} of {@link String field names} based on the {@link PropertyDescriptor propeties}
     * from the underlying, target {@link Object}.
     *
     * @return a {@link List} of {@link String field names} / {@link PropertyDescriptor properties} serialized
     * in the PDX bytes for the underlying, target {@link Object}.
     * @see org.springframework.beans.BeanWrapper#getPropertyDescriptors()
     * @see java.beans.PropertyDescriptor
     * @see #getBeanWrapper()
     */
    @Override
    public List<String> getFieldNames() {
        PropertyDescriptor[] propertyDescriptors = ArrayUtils.nullSafeArray(getBeanWrapper().getPropertyDescriptors(), PropertyDescriptor.clreplaced);
        return Arrays.stream(propertyDescriptors).map(PropertyDescriptor::getName).filter(propertyName -> !CLreplaced_PROPERTY_NAME.equals(propertyName)).collect(Collectors.toList());
    }

    /**
     * Determines whether the given {@link String field name} is an identifier for this {@link PdxInstance}.
     *
     * @param fieldName {@link String} containing the name of the field to evaluate.
     * @return a boolean value indicating whether the given {@link String field name} is an identifier for
     * this {@link PdxInstance}.
     * @see #resolveIdenreplacedyFieldNameFromProperty(BeanWrapper)
     */
    @Override
    public boolean isIdenreplacedyField(String fieldName) {
        String resolvedIdenreplacedyFieldName = this.resolvedIdenreplacedyFieldName.updateAndGet(it -> StringUtils.hasText(it) ? it : resolveIdenreplacedyFieldNameFromProperty());
        return StringUtils.hasText(resolvedIdenreplacedyFieldName) && resolvedIdenreplacedyFieldName.equals(fieldName);
    }

    // Identifier Search Algorithm: @Id Property -> @Id Field -> "id" Property
    @Nullable
    String resolveIdenreplacedyFieldNameFromProperty() {
        return resolveIdenreplacedyFieldNameFromProperty(getBeanWrapper());
    }

    @Nullable
    private String resolveIdenreplacedyFieldNameFromProperty(@NonNull BeanWrapper beanWrapper) {
        List<PropertyDescriptor> properties = Arrays.asList(ArrayUtils.nullSafeArray(beanWrapper.getPropertyDescriptors(), PropertyDescriptor.clreplaced));
        Optional<PropertyDescriptor> atIdAnnotatedProperty = properties.stream().filter(this::isAtIdAnnotatedProperty).findFirst();
        return atIdAnnotatedProperty.map(PropertyDescriptor::getName).orElseGet(() -> resolveIdenreplacedyFieldNameFromField(beanWrapper));
    }

    private boolean isAtIdAnnotatedProperty(@Nullable PropertyDescriptor propertyDescriptor) {
        return Optional.ofNullable(propertyDescriptor).map(PropertyDescriptor::getReadMethod).map(method -> AnnotationUtils.findAnnotation(method, Id.clreplaced)).isPresent();
    }

    @Nullable
    private String resolveIdenreplacedyFieldNameFromField(@NonNull BeanWrapper beanWrapper) {
        List<Field> fields = Arrays.asList(ArrayUtils.nullSafeArray(beanWrapper.getWrappedClreplaced().getDeclaredFields(), Field.clreplaced));
        Optional<PropertyDescriptor> atIdAnnotatedProperty = fields.stream().map(field -> getPropertyForAtIdAnnotatedField(beanWrapper, field)).filter(Objects::nonNull).findFirst();
        return atIdAnnotatedProperty.map(PropertyDescriptor::getName).orElseGet(() -> beanWrapper.isReadableProperty(ID_PROPERTY_NAME) ? ID_PROPERTY_NAME : null);
    }

    @Nullable
    private PropertyDescriptor getPropertyForAtIdAnnotatedField(@NonNull BeanWrapper beanWrapper, @Nullable Field field) {
        return Optional.ofNullable(field).filter(it -> beanWrapper.isReadableProperty(it.getName())).filter(it -> Objects.nonNull(AnnotationUtils.findAnnotation(it, Id.clreplaced))).map(it -> beanWrapper.getPropertyDescriptor(it.getName())).orElse(null);
    }

    /**
     * Returns the {@literal target} {@link Object} being adapted by this {@link PdxInstance}.
     *
     * @return the {@literal target} {@link Object} being adapted by this {@link PdxInstance}; never {@literal null}.
     * @see java.lang.Object
     */
    @Override
    public Object getObject() {
        return this.target;
    }

    ObjectPdxInstanceAdapter getParent() {
        return this;
    }

    /**
     * @inheritDoc
     */
    @Override
    public WritablePdxInstance createWriter() {
        return new WritablePdxInstance() {

            @Override
            public void setField(String fieldName, Object value) {
                withPropertyAccessorFor(fieldName, value).setPropertyValue(fieldName, value);
            }

            private PropertyAccessor withPropertyAccessorFor(String fieldName, Object value) {
                replacedertFieldIsPresent(fieldName);
                BeanWrapper beanWrapper = getBeanWrapper();
                replacedertFieldIsWritable(beanWrapper, fieldName);
                replacedertValueIsTypeMatch(beanWrapper, fieldName, value);
                return beanWrapper;
            }

            private void replacedertFieldIsPresent(String fieldName) {
                Supplier<String> pdxFieldNotFoundExceptionMessageSupplier = () -> String.format("Field [%1$s] does not exist on Object [%2$s]", fieldName, getClreplacedName());
                replacedertCondition(hasField(fieldName), () -> new PdxFieldDoesNotExistException(pdxFieldNotFoundExceptionMessageSupplier.get()));
            }

            private void replacedertFieldIsWritable(BeanWrapper beanWrapper, String fieldName) {
                Supplier<String> pdxFieldNotWritableExceptionMessageSupplier = () -> String.format("Field [%1$s] of Object [%2$s] is not writable", fieldName, getClreplacedName());
                replacedertCondition(beanWrapper.isWritableProperty(fieldName), () -> new PdxFieldNotWritableException(pdxFieldNotWritableExceptionMessageSupplier.get()));
            }

            private void replacedertValueIsTypeMatch(BeanWrapper beanWrapper, String fieldName, Object value) {
                PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
                Supplier<String> typeMismatchExceptionMessageSupplier = () -> String.format("Value [%1$s] of type [%2$s] does not match field [%3$s] of type [%4$s] on Object [%5$s]", value, ObjectUtils.nullSafeClreplacedName(value), fieldName, property.getPropertyType().getName(), getClreplacedName());
                replacedertCondition(isTypeMatch(property, value), () -> new PdxFieldTypeMismatchException(typeMismatchExceptionMessageSupplier.get()));
            }

            private boolean isTypeMatch(PropertyDescriptor property, Object value) {
                return value == null || property.getPropertyType().isInstance(value);
            }

            @Override
            public String getClreplacedName() {
                return getParent().getClreplacedName();
            }

            @Override
            public boolean isDeserializable() {
                return getParent().isDeserializable();
            }

            @Override
            public boolean isEnum() {
                return getParent().isEnum();
            }

            @Override
            public Object getField(String fieldName) {
                return getParent().getField(fieldName);
            }

            @Override
            public List<String> getFieldNames() {
                return getParent().getFieldNames();
            }

            @Override
            public boolean isIdenreplacedyField(String fieldName) {
                return getParent().isIdenreplacedyField(fieldName);
            }

            @Override
            public Object getObject() {
                return getParent().getObject();
            }

            @Override
            public WritablePdxInstance createWriter() {
                return this;
            }

            @Override
            public boolean hasField(String fieldName) {
                return getParent().hasField(fieldName);
            }
        };
    }

    /**
     * Determines whether the given {@link String field name} is a {@link PropertyDescriptor property}
     * on the underlying, target {@link Object}.
     *
     * @param fieldName {@link String} containing the name of the field to match against
     * a {@link PropertyDescriptor property} from the underlying, target {@link Object}.
     * @return a boolean value that determines whether the given {@link String field name}
     * is a {@link PropertyDescriptor property} on the underlying, target {@link Object}.
     * @see #getFieldNames()
     */
    @Override
    public boolean hasField(String fieldName) {
        return getFieldNames().contains(fieldName);
    }
}

19 View Source File : ObjectPdxInstanceAdapter.java
License : Apache License 2.0
Project Creator : spring-projects

/**
 * Returns the {@link Object value} for the {@link PropertyDescriptor property} identified by
 * the given {@link String field name} on the underlying, target {@link Object}.
 *
 * @param fieldName {@link String} containing the name of the field to get the {@link Object value} for.
 * @return the {@link Object value} for the {@link PropertyDescriptor property} identified by
 * the given {@link String field name} on the underlying, target {@link Object}.
 * @see org.springframework.beans.BeanWrapper#getPropertyValue(String)
 * @see #getBeanWrapper()
 */
@Override
public Object getField(String fieldName) {
    BeanWrapper beanWrapper = getBeanWrapper();
    return beanWrapper.isReadableProperty(fieldName) ? beanWrapper.getPropertyValue(fieldName) : null;
}

19 View Source File : ConstructorResolver.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw, Executable executable, Object[] argsToResolve, boolean fallback) {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    Clreplaced<?>[] paramTypes = executable.getParameterTypes();
    Object[] resolvedArgs = new Object[argsToResolve.length];
    for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
        Object argValue = argsToResolve[argIndex];
        MethodParameter methodParam = MethodParameter.forExecutable(executable, argIndex);
        if (argValue == autowiredArgumentMarker) {
            argValue = resolveAutowiredArgument(methodParam, beanName, null, converter, fallback);
        } else if (argValue instanceof BeanMetadataElement) {
            argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
        } else if (argValue instanceof String) {
            argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
        }
        Clreplaced<?> paramType = paramTypes[argIndex];
        try {
            resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
        } catch (TypeMismatchException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClreplacedName(argValue) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
        }
    }
    return resolvedArgs;
}

19 View Source File : ConstructorResolver.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Create an array of arguments to invoke a constructor or factory method,
 * given the resolved constructor argument values.
 */
private ArgumentsHolder createArgumentArray(String beanName, RootBeanDefinition mbd, @Nullable ConstructorArgumentValues resolvedValues, BeanWrapper bw, Clreplaced<?>[] paramTypes, @Nullable String[] paramNames, Executable executable, boolean autowiring, boolean fallback) throws UnsatisfiedDependencyException {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
    Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
        Clreplaced<?> paramType = paramTypes[paramIndex];
        String paramName = (paramNames != null ? paramNames[paramIndex] : "");
        // Try to find matching constructor argument value, either indexed or generic.
        ConstructorArgumentValues.ValueHolder valueHolder = null;
        if (resolvedValues != null) {
            valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
            // If we couldn't find a direct match and are not supposed to autowire,
            // let's try the next generic, untyped argument value as fallback:
            // it could match after type conversion (for example, String -> int).
            if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
                valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
            }
        }
        if (valueHolder != null) {
            // We found a potential match - let's give it a try.
            // Do not consider the same value definition multiple times!
            usedValueHolders.add(valueHolder);
            Object originalValue = valueHolder.getValue();
            Object convertedValue;
            if (valueHolder.isConverted()) {
                convertedValue = valueHolder.getConvertedValue();
                args.preparedArguments[paramIndex] = convertedValue;
            } else {
                MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
                try {
                    convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
                } catch (TypeMismatchException ex) {
                    throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClreplacedName(valueHolder.getValue()) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
                }
                Object sourceHolder = valueHolder.getSource();
                if (sourceHolder instanceof ConstructorArgumentValues.ValueHolder) {
                    Object sourceValue = ((ConstructorArgumentValues.ValueHolder) sourceHolder).getValue();
                    args.resolveNecessary = true;
                    args.preparedArguments[paramIndex] = sourceValue;
                }
            }
            args.arguments[paramIndex] = convertedValue;
            args.rawArguments[paramIndex] = originalValue;
        } else {
            MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
            // No explicit match found: we're either supposed to autowire or
            // have to fail creating an argument array for the given constructor.
            if (!autowiring) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Ambiguous argument values for parameter of type [" + paramType.getName() + "] - did you specify the correct bean references as arguments?");
            }
            try {
                Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter, fallback);
                args.rawArguments[paramIndex] = autowiredArgument;
                args.arguments[paramIndex] = autowiredArgument;
                args.preparedArguments[paramIndex] = autowiredArgumentMarker;
                args.resolveNecessary = true;
            } catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
            }
        }
    }
    for (String autowiredBeanName : autowiredBeanNames) {
        this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
        if (logger.isDebugEnabled()) {
            logger.debug("Autowiring by type from bean name '" + beanName + "' via " + (executable instanceof Constructor ? "constructor" : "factory method") + " to bean named '" + autowiredBeanName + "'");
        }
    }
    return args;
}

19 View Source File : UcfUtil.java
License : Apache License 2.0
Project Creator : Pardus-Engerek

public static PropertyDescriptor findAnnotatedProperty(Clreplaced<?> connectorClreplaced, Clreplaced<? extends Annotation> annotationClreplaced) {
    BeanWrapper connectorBean = new BeanWrapperImpl(connectorClreplaced);
    return findAnnotatedProperty(connectorBean, annotationClreplaced);
}

19 View Source File : UcfUtil.java
License : Apache License 2.0
Project Creator : Pardus-Engerek

public static PropertyDescriptor findAnnotatedProperty(BeanWrapper connectorBean, Clreplaced<? extends Annotation> annotationClreplaced) {
    for (PropertyDescriptor prop : connectorBean.getPropertyDescriptors()) {
        if (hasAnnotation(prop, annotationClreplaced)) {
            return prop;
        }
    }
    return null;
}

19 View Source File : BeanPropertySqlParameterSource.java
License : MIT License
Project Creator : mindcarver

/**
 * {@link SqlParameterSource} implementation that obtains parameter values
 * from bean properties of a given JavaBean object. The names of the bean
 * properties have to match the parameter names.
 *
 * <p>Uses a Spring BeanWrapper for bean property access underneath.
 *
 * @author Thomas Risberg
 * @author Juergen Hoeller
 * @since 2.0
 * @see NamedParameterJdbcTemplate
 * @see org.springframework.beans.BeanWrapper
 */
public clreplaced BeanPropertySqlParameterSource extends AbstractSqlParameterSource {

    private final BeanWrapper beanWrapper;

    @Nullable
    private String[] propertyNames;

    /**
     * Create a new BeanPropertySqlParameterSource for the given bean.
     * @param object the bean instance to wrap
     */
    public BeanPropertySqlParameterSource(Object object) {
        this.beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
    }

    @Override
    public boolean hasValue(String paramName) {
        return this.beanWrapper.isReadableProperty(paramName);
    }

    @Override
    @Nullable
    public Object getValue(String paramName) throws IllegalArgumentException {
        try {
            return this.beanWrapper.getPropertyValue(paramName);
        } catch (NotReadablePropertyException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    }

    /**
     * Derives a default SQL type from the corresponding property type.
     * @see org.springframework.jdbc.core.StatementCreatorUtils#javaTypeToSqlParameterType
     */
    @Override
    public int getSqlType(String paramName) {
        int sqlType = super.getSqlType(paramName);
        if (sqlType != TYPE_UNKNOWN) {
            return sqlType;
        }
        Clreplaced<?> propType = this.beanWrapper.getPropertyType(paramName);
        return StatementCreatorUtils.javaTypeToSqlParameterType(propType);
    }

    @Override
    @Nullable
    public String[] getParameterNames() {
        return getReadablePropertyNames();
    }

    /**
     * Provide access to the property names of the wrapped bean.
     * Uses support provided in the {@link PropertyAccessor} interface.
     * @return an array containing all the known property names
     */
    public String[] getReadablePropertyNames() {
        if (this.propertyNames == null) {
            List<String> names = new ArrayList<>();
            PropertyDescriptor[] props = this.beanWrapper.getPropertyDescriptors();
            for (PropertyDescriptor pd : props) {
                if (this.beanWrapper.isReadableProperty(pd.getName())) {
                    names.add(pd.getName());
                }
            }
            this.propertyNames = StringUtils.toStringArray(names);
        }
        return this.propertyNames;
    }
}

19 View Source File : Beans.java
License : MIT License
Project Creator : microapp-store

/**
 * Created  on 2017/12/29 0029.
 *
 * @author zt
 */
public clreplaced Beans<T> {

    static BeanWrapper beanWrapper = null;

    public static <T> Beans<T> me(T obj) {
        return new Beans<T>(obj);
    }

    private Beans(T obj) {
        beanWrapper = new BeanWrapperImpl(obj);
    }

    public Object get(String propName) {
        return beanWrapper.getPropertyValue(propName);
    }

    public void set(String propName, Object propVal) {
        beanWrapper.setPropertyValue(propName, propVal);
    }
}

19 View Source File : GenericPortletBean.java
License : Apache License 2.0
Project Creator : liferay

/**
 * Initialize the BeanWrapper for this GenericPortletBean, possibly with custom editors.
 *
 * @param   bw  the BeanWrapper to initialize
 *
 * @throws  BeansException  if thrown by BeanWrapper methods
 *
 * @see     org.springframework.beans.BeanWrapper#registerCustomEditor
 */
protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
}

19 View Source File : GenericPortletBean.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Initialize the BeanWrapper for this GenericPortletBean,
 * possibly with custom editors.
 * @param bw the BeanWrapper to initialize
 * @throws BeansException if thrown by BeanWrapper methods
 * @see org.springframework.beans.BeanWrapper#registerCustomEditor
 */
protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
}

19 View Source File : BeanPropertySqlParameterSource.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * {@link SqlParameterSource} implementation that obtains parameter values
 * from bean properties of a given JavaBean object. The names of the bean
 * properties have to match the parameter names.
 *
 * <p>Uses a Spring BeanWrapper for bean property access underneath.
 *
 * @author Thomas Risberg
 * @author Juergen Hoeller
 * @since 2.0
 * @see NamedParameterJdbcTemplate
 * @see org.springframework.beans.BeanWrapper
 */
public clreplaced BeanPropertySqlParameterSource extends AbstractSqlParameterSource {

    private final BeanWrapper beanWrapper;

    private String[] propertyNames;

    /**
     * Create a new BeanPropertySqlParameterSource for the given bean.
     * @param object the bean instance to wrap
     */
    public BeanPropertySqlParameterSource(Object object) {
        this.beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
    }

    @Override
    public boolean hasValue(String paramName) {
        return this.beanWrapper.isReadableProperty(paramName);
    }

    @Override
    public Object getValue(String paramName) throws IllegalArgumentException {
        try {
            return this.beanWrapper.getPropertyValue(paramName);
        } catch (NotReadablePropertyException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    }

    /**
     * Provide access to the property names of the wrapped bean.
     * Uses support provided in the {@link PropertyAccessor} interface.
     * @return an array containing all the known property names
     */
    public String[] getReadablePropertyNames() {
        if (this.propertyNames == null) {
            List<String> names = new ArrayList<String>();
            PropertyDescriptor[] props = this.beanWrapper.getPropertyDescriptors();
            for (PropertyDescriptor pd : props) {
                if (this.beanWrapper.isReadableProperty(pd.getName())) {
                    names.add(pd.getName());
                }
            }
            this.propertyNames = names.toArray(new String[names.size()]);
        }
        return this.propertyNames;
    }

    /**
     * Derives a default SQL type from the corresponding property type.
     * @see org.springframework.jdbc.core.StatementCreatorUtils#javaTypeToSqlParameterType
     */
    @Override
    public int getSqlType(String paramName) {
        int sqlType = super.getSqlType(paramName);
        if (sqlType != TYPE_UNKNOWN) {
            return sqlType;
        }
        Clreplaced<?> propType = this.beanWrapper.getPropertyType(paramName);
        return StatementCreatorUtils.javaTypeToSqlParameterType(propType);
    }
}

19 View Source File : BeanPropertyRowMapper.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Initialize the given BeanWrapper to be used for row mapping.
 * To be called for each row.
 * <p>The default implementation is empty. Can be overridden in subclreplacedes.
 * @param bw the BeanWrapper to initialize
 */
protected void initBeanWrapper(BeanWrapper bw) {
}

19 View Source File : BeanPropertyBindingResult.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Default implementation of the {@link Errors} and {@link BindingResult}
 * interfaces, for the registration and evaluation of binding errors on
 * JavaBean objects.
 *
 * <p>Performs standard JavaBean property access, also supporting nested
 * properties. Normally, application code will work with the
 * {@code Errors} interface or the {@code BindingResult} interface.
 * A {@link DataBinder} returns its {@code BindingResult} via
 * {@link DataBinder#getBindingResult()}.
 *
 * @author Juergen Hoeller
 * @since 2.0
 * @see DataBinder#getBindingResult()
 * @see DataBinder#initBeanPropertyAccess()
 * @see DirectFieldBindingResult
 */
@SuppressWarnings("serial")
public clreplaced BeanPropertyBindingResult extends AbstractPropertyBindingResult implements Serializable {

    private final Object target;

    private final boolean autoGrowNestedPaths;

    private final int autoGrowCollectionLimit;

    private transient BeanWrapper beanWrapper;

    /**
     * Creates a new instance of the {@link BeanPropertyBindingResult} clreplaced.
     * @param target the target bean to bind onto
     * @param objectName the name of the target object
     */
    public BeanPropertyBindingResult(Object target, String objectName) {
        this(target, objectName, true, Integer.MAX_VALUE);
    }

    /**
     * Creates a new instance of the {@link BeanPropertyBindingResult} clreplaced.
     * @param target the target bean to bind onto
     * @param objectName the name of the target object
     * @param autoGrowNestedPaths whether to "auto-grow" a nested path that contains a null value
     * @param autoGrowCollectionLimit the limit for array and collection auto-growing
     */
    public BeanPropertyBindingResult(Object target, String objectName, boolean autoGrowNestedPaths, int autoGrowCollectionLimit) {
        super(objectName);
        this.target = target;
        this.autoGrowNestedPaths = autoGrowNestedPaths;
        this.autoGrowCollectionLimit = autoGrowCollectionLimit;
    }

    @Override
    public final Object getTarget() {
        return this.target;
    }

    /**
     * Returns the {@link BeanWrapper} that this instance uses.
     * Creates a new one if none existed before.
     * @see #createBeanWrapper()
     */
    @Override
    public final ConfigurablePropertyAccessor getPropertyAccessor() {
        if (this.beanWrapper == null) {
            this.beanWrapper = createBeanWrapper();
            this.beanWrapper.setExtractOldValueForEditor(true);
            this.beanWrapper.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
            this.beanWrapper.setAutoGrowCollectionLimit(this.autoGrowCollectionLimit);
        }
        return this.beanWrapper;
    }

    /**
     * Create a new {@link BeanWrapper} for the underlying target object.
     * @see #getTarget()
     */
    protected BeanWrapper createBeanWrapper() {
        replacedert.state(this.target != null, "Cannot access properties on null bean instance '" + getObjectName() + "'!");
        return PropertyAccessorFactory.forBeanPropertyAccess(this.target);
    }
}

19 View Source File : CommonUtil.java
License : GNU General Public License v2.0
Project Creator : futurewei-cloud

/**
 * Return a bean null property names
 * @param bean a bean enreplacedy
 * @return return a bean null property names
 */
public static String[] getBeanNullPropertyNames(Object bean) {
    final BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
    return Stream.of(beanWrapper.getPropertyDescriptors()).map(FeatureDescriptor::getName).filter(propertyName -> {
        try {
            return beanWrapper.getPropertyValue(propertyName) == null;
        } catch (BeansException e) {
            return true;
        }
    }).toArray(String[]::new);
}

19 View Source File : CommonUtils.java
License : MIT License
Project Creator : 2bcoin

public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
    return Stream.of(wrappedSource.getPropertyDescriptors()).map(FeatureDescriptor::getName).filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null).toArray(String[]::new);
}

18 View Source File : MyBeanUtil.java
License : Apache License 2.0
Project Creator : wayn111

public static <T> T toBean(Map<String, Object> map, Clreplaced<T> beanType) {
    BeanWrapper beanWrapper = new BeanWrapperImpl(beanType);
    map.forEach((key, value) -> {
        if (beanWrapper.isWritableProperty(key)) {
            beanWrapper.setPropertyValue(key, value);
        }
    });
    return (T) beanWrapper.getWrappedInstance();
}

18 View Source File : OptionWriter.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Render the inner '{@code option}' tags using the supplied {@link Collection} of
 * objects as the source. The value of the {@link #valueProperty} field is used
 * when rendering the '{@code value}' of the '{@code option}' and the value of the
 * {@link #labelProperty} property is used when rendering the label.
 */
private void doRenderFromCollection(Collection<?> optionCollection, TagWriter tagWriter) throws JspException {
    for (Object item : optionCollection) {
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
        Object value;
        if (this.valueProperty != null) {
            value = wrapper.getPropertyValue(this.valueProperty);
        } else if (item instanceof Enum) {
            value = ((Enum<?>) item).name();
        } else {
            value = item;
        }
        Object label = (this.labelProperty != null ? wrapper.getPropertyValue(this.labelProperty) : item);
        renderOption(tagWriter, item, value, label);
    }
}

18 View Source File : AbstractMultiCheckedElementTag.java
License : MIT License
Project Creator : Vip-Augus

private void writeMapEntry(TagWriter tagWriter, @Nullable String valueProperty, @Nullable String labelProperty, Map.Entry<?, ?> entry, int itemIndex) throws JspException {
    Object mapKey = entry.getKey();
    Object mapValue = entry.getValue();
    BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
    BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
    Object renderValue = (valueProperty != null ? mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
    Object renderLabel = (labelProperty != null ? mapValueWrapper.getPropertyValue(labelProperty) : mapValue.toString());
    writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
}

18 View Source File : AbstractMultiCheckedElementTag.java
License : MIT License
Project Creator : Vip-Augus

private void writeObjectEntry(TagWriter tagWriter, @Nullable String valueProperty, @Nullable String labelProperty, Object item, int itemIndex) throws JspException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
    Object renderValue;
    if (valueProperty != null) {
        renderValue = wrapper.getPropertyValue(valueProperty);
    } else if (item instanceof Enum) {
        renderValue = ((Enum<?>) item).name();
    } else {
        renderValue = item;
    }
    Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
    writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}

18 View Source File : GroovyWebApplicationContext.java
License : MIT License
Project Creator : Vip-Augus

/**
 * {@link org.springframework.web.context.WebApplicationContext} implementation which takes
 * its configuration from Groovy bean definition scripts and/or XML files, as understood by
 * a {@link org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader}.
 * This is essentially the equivalent of
 * {@link org.springframework.context.support.GenericGroovyApplicationContext}
 * for a web environment.
 *
 * <p>By default, the configuration will be taken from "/WEB-INF/applicationContext.groovy"
 * for the root context, and "/WEB-INF/test-servlet.groovy" for a context with the namespace
 * "test-servlet" (like for a DispatcherServlet instance with the servlet-name "test").
 *
 * <p>The config location defaults can be overridden via the "contextConfigLocation"
 * context-param of {@link org.springframework.web.context.ContextLoader} and servlet
 * init-param of {@link org.springframework.web.servlet.FrameworkServlet}. Config locations
 * can either denote concrete files like "/WEB-INF/context.groovy" or Ant-style patterns
 * like "/WEB-INF/*-context.groovy" (see {@link org.springframework.util.PathMatcher}
 * javadoc for pattern details). Note that ".xml" files will be parsed as XML content;
 * all other kinds of resources will be parsed as Groovy scripts.
 *
 * <p>Note: In case of multiple config locations, later bean definitions will
 * override ones defined in earlier loaded files. This can be leveraged to
 * deliberately override certain bean definitions via an extra Groovy script.
 *
 * <p><b>For a WebApplicationContext that reads in a different bean definition format,
 * create an replacedogous subclreplaced of {@link AbstractRefreshableWebApplicationContext}.</b>
 * Such a context implementation can be specified as "contextClreplaced" context-param
 * for ContextLoader or "contextClreplaced" init-param for FrameworkServlet.
 *
 * @author Juergen Hoeller
 * @since 4.1
 * @see #setNamespace
 * @see #setConfigLocations
 * @see org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
 * @see org.springframework.web.context.ContextLoader#initWebApplicationContext
 * @see org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext
 */
public clreplaced GroovyWebApplicationContext extends AbstractRefreshableWebApplicationContext implements GroovyObject {

    /**
     * Default config location for the root context.
     */
    public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.groovy";

    /**
     * Default prefix for building a config location for a namespace.
     */
    public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

    /**
     * Default suffix for building a config location for a namespace.
     */
    public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".groovy";

    private final BeanWrapper contextWrapper = new BeanWrapperImpl(this);

    private MetaClreplaced metaClreplaced = GroovySystem.getMetaClreplacedRegistry().getMetaClreplaced(getClreplaced());

    /**
     * Loads the bean definitions via an GroovyBeanDefinitionReader.
     * @see org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        GroovyBeanDefinitionReader beanDefinitionReader = new GroovyBeanDefinitionReader(beanFactory);
        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        // Allow a subclreplaced to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }

    /**
     * Initialize the bean definition reader used for loading the bean
     * definitions of this context. Default implementation is empty.
     * <p>Can be overridden in subclreplacedes.
     * @param beanDefinitionReader the bean definition reader used by this context
     */
    protected void initBeanDefinitionReader(GroovyBeanDefinitionReader beanDefinitionReader) {
    }

    /**
     * Load the bean definitions with the given GroovyBeanDefinitionReader.
     * <p>The lifecycle of the bean factory is handled by the refreshBeanFactory method;
     * therefore this method is just supposed to load and/or register bean definitions.
     * <p>Delegates to a ResourcePatternResolver for resolving location patterns
     * into Resource instances.
     * @throws IOException if the required Groovy script or XML file isn't found
     * @see #refreshBeanFactory
     * @see #getConfigLocations
     * @see #getResources
     * @see #getResourcePatternResolver
     */
    protected void loadBeanDefinitions(GroovyBeanDefinitionReader reader) throws IOException {
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            for (String configLocation : configLocations) {
                reader.loadBeanDefinitions(configLocation);
            }
        }
    }

    /**
     * The default location for the root context is "/WEB-INF/applicationContext.groovy",
     * and "/WEB-INF/test-servlet.groovy" for a context with the namespace "test-servlet"
     * (like for a DispatcherServlet instance with the servlet-name "test").
     */
    @Override
    protected String[] getDefaultConfigLocations() {
        if (getNamespace() != null) {
            return new String[] { DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX };
        } else {
            return new String[] { DEFAULT_CONFIG_LOCATION };
        }
    }

    // Implementation of the GroovyObject interface
    public void setMetaClreplaced(MetaClreplaced metaClreplaced) {
        this.metaClreplaced = metaClreplaced;
    }

    public MetaClreplaced getMetaClreplaced() {
        return this.metaClreplaced;
    }

    public Object invokeMethod(String name, Object args) {
        return this.metaClreplaced.invokeMethod(this, name, args);
    }

    public void setProperty(String property, Object newValue) {
        this.metaClreplaced.setProperty(this, property, newValue);
    }

    @Nullable
    public Object getProperty(String property) {
        if (containsBean(property)) {
            return getBean(property);
        } else if (this.contextWrapper.isReadableProperty(property)) {
            return this.contextWrapper.getPropertyValue(property);
        }
        throw new NoSuchBeanDefinitionException(property);
    }
}

18 View Source File : StandardJmsActivationSpecFactory.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Apply the specified acknowledge mode to the ActivationSpec object.
 * <p>This implementation applies the standard JCA 1.5 acknowledge modes
 * "Auto-acknowledge" and "Dups-ok-acknowledge". It throws an exception in
 * case of {@code CLIENT_ACKNOWLEDGE} or {@code SESSION_TRANSACTED}
 * having been requested.
 * @param bw the BeanWrapper wrapping the ActivationSpec object
 * @param ackMode the configured acknowledge mode
 * (according to the constants in {@link javax.jms.Session}
 * @see javax.jms.Session#AUTO_ACKNOWLEDGE
 * @see javax.jms.Session#DUPS_OK_ACKNOWLEDGE
 * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
 * @see javax.jms.Session#SESSION_TRANSACTED
 */
protected void applyAcknowledgeMode(BeanWrapper bw, int ackMode) {
    if (ackMode == Session.SESSION_TRANSACTED) {
        throw new IllegalArgumentException("No support for SESSION_TRANSACTED: Only \"Auto-acknowledge\" " + "and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
    } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
        throw new IllegalArgumentException("No support for CLIENT_ACKNOWLEDGE: Only \"Auto-acknowledge\" " + "and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
    } else if (bw.isWritableProperty("acknowledgeMode")) {
        bw.setPropertyValue("acknowledgeMode", ackMode == Session.DUPS_OK_ACKNOWLEDGE ? "Dups-ok-acknowledge" : "Auto-acknowledge");
    } else if (ackMode == Session.DUPS_OK_ACKNOWLEDGE) {
        // Standard JCA 1.5 "acknowledgeMode" apparently not supported (e.g. WebSphere MQ 6.0.2.1)
        throw new IllegalArgumentException("Dups-ok-acknowledge not supported by underlying provider");
    }
}

18 View Source File : StandardJmsActivationSpecFactory.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Populate the given ApplicationSpec object with the settings
 * defined in the given configuration object.
 * <p>This implementation applies all standard JMS settings, but ignores
 * "maxConcurrency" and "prefetchSize" - not supported in standard JCA 1.5.
 * @param bw the BeanWrapper wrapping the ActivationSpec object
 * @param config the configured object holding common JMS settings
 */
protected void populateActivationSpecProperties(BeanWrapper bw, JmsActivationSpecConfig config) {
    String destinationName = config.getDestinationName();
    if (destinationName != null) {
        boolean pubSubDomain = config.isPubSubDomain();
        Object destination = destinationName;
        if (this.destinationResolver != null) {
            try {
                destination = this.destinationResolver.resolveDestinationName(null, destinationName, pubSubDomain);
            } catch (JMSException ex) {
                throw new DestinationResolutionException("Cannot resolve destination name [" + destinationName + "]", ex);
            }
        }
        bw.setPropertyValue("destination", destination);
        bw.setPropertyValue("destinationType", pubSubDomain ? Topic.clreplaced.getName() : Queue.clreplaced.getName());
    }
    if (bw.isWritableProperty("subscriptionDurability")) {
        bw.setPropertyValue("subscriptionDurability", config.isSubscriptionDurable() ? "Durable" : "NonDurable");
    } else if (config.isSubscriptionDurable()) {
        // Standard JCA 1.5 "subscriptionDurability" apparently not supported...
        throw new IllegalArgumentException("Durable subscriptions not supported by underlying provider");
    }
    if (config.isSubscriptionShared()) {
        throw new IllegalArgumentException("Shared subscriptions not supported for JCA-driven endpoints");
    }
    if (config.getSubscriptionName() != null) {
        bw.setPropertyValue("subscriptionName", config.getSubscriptionName());
    }
    if (config.getClientId() != null) {
        bw.setPropertyValue("clientId", config.getClientId());
    }
    if (config.getMessageSelector() != null) {
        bw.setPropertyValue("messageSelector", config.getMessageSelector());
    }
    applyAcknowledgeMode(bw, config.getAcknowledgeMode());
}

18 View Source File : AnnotationJmxAttributeSource.java
License : MIT License
Project Creator : Vip-Augus

@Nullable
private static <T> T copyPropertiesToBean(MergedAnnotation<? extends Annotation> ann, Clreplaced<T> beanClreplaced) {
    if (!ann.isPresent()) {
        return null;
    }
    T bean = BeanUtils.instantiateClreplaced(beanClreplaced);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    bw.setPropertyValues(new MutablePropertyValues(ann.asMap()));
    return bean;
}

18 View Source File : ConstructorResolver.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Resolve the constructor arguments for this bean into the resolvedValues object.
 * This may involve looking up other beans.
 * <p>This method is also used for handling invocations of static factory methods.
 */
private int resolveConstructorArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {
    TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
    TypeConverter converter = (customConverter != null ? customConverter : bw);
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
    int minNrOfArgs = cargs.getArgumentCount();
    for (Map.Entry<Integer, ConstructorArgumentValues.ValueHolder> entry : cargs.getIndexedArgumentValues().entrySet()) {
        int index = entry.getKey();
        if (index < 0) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid constructor argument index: " + index);
        }
        if (index > minNrOfArgs) {
            minNrOfArgs = index + 1;
        }
        ConstructorArgumentValues.ValueHolder valueHolder = entry.getValue();
        if (valueHolder.isConverted()) {
            resolvedValues.addIndexedArgumentValue(index, valueHolder);
        } else {
            Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue());
            ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType(), valueHolder.getName());
            resolvedValueHolder.setSource(valueHolder);
            resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder);
        }
    }
    for (ConstructorArgumentValues.ValueHolder valueHolder : cargs.getGenericArgumentValues()) {
        if (valueHolder.isConverted()) {
            resolvedValues.addGenericArgumentValue(valueHolder);
        } else {
            Object resolvedValue = valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue());
            ConstructorArgumentValues.ValueHolder resolvedValueHolder = new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType(), valueHolder.getName());
            resolvedValueHolder.setSource(valueHolder);
            resolvedValues.addGenericArgumentValue(resolvedValueHolder);
        }
    }
    return minNrOfArgs;
}

18 View Source File : PropertyPathFactoryBean.java
License : MIT License
Project Creator : Vip-Augus

/**
 * {@link FactoryBean} that evaluates a property path on a given target object.
 *
 * <p>The target object can be specified directly or via a bean name.
 *
 * <p>Usage examples:
 *
 * <pre clreplaced="code"><!-- target bean to be referenced by name -->
 * <bean id="tb" clreplaced="org.springframework.beans.TestBean" singleton="false">
 *   <property name="age" value="10"/>
 *   <property name="spouse">
 *     <bean clreplaced="org.springframework.beans.TestBean">
 *       <property name="age" value="11"/>
 *     </bean>
 *   </property>
 * </bean>
 *
 * <!-- will result in 12, which is the value of property 'age' of the inner bean -->
 * <bean id="propertyPath1" clreplaced="org.springframework.beans.factory.config.PropertyPathFactoryBean">
 *   <property name="targetObject">
 *     <bean clreplaced="org.springframework.beans.TestBean">
 *       <property name="age" value="12"/>
 *     </bean>
 *   </property>
 *   <property name="propertyPath" value="age"/>
 * </bean>
 *
 * <!-- will result in 11, which is the value of property 'spouse.age' of bean 'tb' -->
 * <bean id="propertyPath2" clreplaced="org.springframework.beans.factory.config.PropertyPathFactoryBean">
 *   <property name="targetBeanName" value="tb"/>
 *   <property name="propertyPath" value="spouse.age"/>
 * </bean>
 *
 * <!-- will result in 10, which is the value of property 'age' of bean 'tb' -->
 * <bean id="tb.age" clreplaced="org.springframework.beans.factory.config.PropertyPathFactoryBean"/></pre>
 *
 * <p>If you are using Spring 2.0 and XML Schema support in your configuration file(s),
 * you can also use the following style of configuration for property path access.
 * (See also the appendix enreplacedled 'XML Schema-based configuration' in the Spring
 * reference manual for more examples.)
 *
 * <pre clreplaced="code"> <!-- will result in 10, which is the value of property 'age' of bean 'tb' -->
 * <util:property-path id="name" path="testBean.age"/></pre>
 *
 * Thanks to Matthias Ernst for the suggestion and initial prototype!
 *
 * @author Juergen Hoeller
 * @since 1.1.2
 * @see #setTargetObject
 * @see #setTargetBeanName
 * @see #setPropertyPath
 */
public clreplaced PropertyPathFactoryBean implements FactoryBean<Object>, BeanNameAware, BeanFactoryAware {

    private static final Log logger = LogFactory.getLog(PropertyPathFactoryBean.clreplaced);

    @Nullable
    private BeanWrapper targetBeanWrapper;

    @Nullable
    private String targetBeanName;

    @Nullable
    private String propertyPath;

    @Nullable
    private Clreplaced<?> resultType;

    @Nullable
    private String beanName;

    @Nullable
    private BeanFactory beanFactory;

    /**
     * Specify a target object to apply the property path to.
     * Alternatively, specify a target bean name.
     * @param targetObject a target object, for example a bean reference
     * or an inner bean
     * @see #setTargetBeanName
     */
    public void setTargetObject(Object targetObject) {
        this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
    }

    /**
     * Specify the name of a target bean to apply the property path to.
     * Alternatively, specify a target object directly.
     * @param targetBeanName the bean name to be looked up in the
     * containing bean factory (e.g. "testBean")
     * @see #setTargetObject
     */
    public void setTargetBeanName(String targetBeanName) {
        this.targetBeanName = StringUtils.trimAllWhitespace(targetBeanName);
    }

    /**
     * Specify the property path to apply to the target.
     * @param propertyPath the property path, potentially nested
     * (e.g. "age" or "spouse.age")
     */
    public void setPropertyPath(String propertyPath) {
        this.propertyPath = StringUtils.trimAllWhitespace(propertyPath);
    }

    /**
     * Specify the type of the result from evaluating the property path.
     * <p>Note: This is not necessary for directly specified target objects
     * or singleton target beans, where the type can be determined through
     * introspection. Just specify this in case of a prototype target,
     * provided that you need matching by type (for example, for autowiring).
     * @param resultType the result type, for example "java.lang.Integer"
     */
    public void setResultType(Clreplaced<?> resultType) {
        this.resultType = resultType;
    }

    /**
     * The bean name of this PropertyPathFactoryBean will be interpreted
     * as "beanName.property" pattern, if neither "targetObject" nor
     * "targetBeanName" nor "propertyPath" have been specified.
     * This allows for concise bean definitions with just an id/name.
     */
    @Override
    public void setBeanName(String beanName) {
        this.beanName = StringUtils.trimAllWhitespace(BeanFactoryUtils.originalBeanName(beanName));
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
        if (this.targetBeanWrapper != null && this.targetBeanName != null) {
            throw new IllegalArgumentException("Specify either 'targetObject' or 'targetBeanName', not both");
        }
        if (this.targetBeanWrapper == null && this.targetBeanName == null) {
            if (this.propertyPath != null) {
                throw new IllegalArgumentException("Specify 'targetObject' or 'targetBeanName' in combination with 'propertyPath'");
            }
            // No other properties specified: check bean name.
            int dotIndex = (this.beanName != null ? this.beanName.indexOf('.') : -1);
            if (dotIndex == -1) {
                throw new IllegalArgumentException("Neither 'targetObject' nor 'targetBeanName' specified, and PropertyPathFactoryBean " + "bean name '" + this.beanName + "' does not follow 'beanName.property' syntax");
            }
            this.targetBeanName = this.beanName.substring(0, dotIndex);
            this.propertyPath = this.beanName.substring(dotIndex + 1);
        } else if (this.propertyPath == null) {
            // either targetObject or targetBeanName specified
            throw new IllegalArgumentException("'propertyPath' is required");
        }
        if (this.targetBeanWrapper == null && this.beanFactory.isSingleton(this.targetBeanName)) {
            // Eagerly fetch singleton target bean, and determine result type.
            Object bean = this.beanFactory.getBean(this.targetBeanName);
            this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
            this.resultType = this.targetBeanWrapper.getPropertyType(this.propertyPath);
        }
    }

    @Override
    @Nullable
    public Object getObject() throws BeansException {
        BeanWrapper target = this.targetBeanWrapper;
        if (target != null) {
            if (logger.isWarnEnabled() && this.targetBeanName != null && this.beanFactory instanceof ConfigurableBeanFactory && ((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
                logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " + "reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
            }
        } else {
            // Fetch prototype target bean...
            replacedert.state(this.beanFactory != null, "No BeanFactory available");
            replacedert.state(this.targetBeanName != null, "No target bean name specified");
            Object bean = this.beanFactory.getBean(this.targetBeanName);
            target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
        }
        replacedert.state(this.propertyPath != null, "No property path specified");
        return target.getPropertyValue(this.propertyPath);
    }

    @Override
    public Clreplaced<?> getObjectType() {
        return this.resultType;
    }

    /**
     * While this FactoryBean will often be used for singleton targets,
     * the invoked getters for the property path might return a new object
     * for each call, so we have to replacedume that we're not returning the
     * same object for each {@link #getObject()} call.
     */
    @Override
    public boolean isSingleton() {
        return false;
    }
}

18 View Source File : GroovyWebApplicationContext.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * {@link org.springframework.web.context.WebApplicationContext} implementation which takes
 * its configuration from Groovy bean definition scripts and/or XML files, as understood by
 * a {@link org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader}.
 * This is essentially the equivalent of
 * {@link org.springframework.context.support.GenericGroovyApplicationContext}
 * for a web environment.
 *
 * <p>By default, the configuration will be taken from "/WEB-INF/applicationContext.groovy"
 * for the root context, and "/WEB-INF/test-servlet.groovy" for a context with the namespace
 * "test-servlet" (like for a DispatcherServlet instance with the servlet-name "test").
 *
 * <p>The config location defaults can be overridden via the "contextConfigLocation"
 * context-param of {@link org.springframework.web.context.ContextLoader} and servlet
 * init-param of {@link org.springframework.web.servlet.FrameworkServlet}. Config locations
 * can either denote concrete files like "/WEB-INF/context.groovy" or Ant-style patterns
 * like "/WEB-INF/*-context.groovy" (see {@link org.springframework.util.PathMatcher}
 * javadoc for pattern details). Note that ".xml" files will be parsed as XML content;
 * all other kinds of resources will be parsed as Groovy scripts.
 *
 * <p>Note: In case of multiple config locations, later bean definitions will
 * override ones defined in earlier loaded files. This can be leveraged to
 * deliberately override certain bean definitions via an extra Groovy script.
 *
 * <p><b>For a WebApplicationContext that reads in a different bean definition format,
 * create an replacedogous subclreplaced of {@link AbstractRefreshableWebApplicationContext}.</b>
 * Such a context implementation can be specified as "contextClreplaced" context-param
 * for ContextLoader or "contextClreplaced" init-param for FrameworkServlet.
 *
 * @author Juergen Hoeller
 * @since 4.1
 * @see #setNamespace
 * @see #setConfigLocations
 * @see org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
 * @see org.springframework.web.context.ContextLoader#initWebApplicationContext
 * @see org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext
 */
public clreplaced GroovyWebApplicationContext extends AbstractRefreshableWebApplicationContext implements GroovyObject {

    /**
     * Default config location for the root context.
     */
    public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.groovy";

    /**
     * Default prefix for building a config location for a namespace.
     */
    public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

    /**
     * Default suffix for building a config location for a namespace.
     */
    public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".groovy";

    private final BeanWrapper contextWrapper = new BeanWrapperImpl(this);

    private MetaClreplaced metaClreplaced = GroovySystem.getMetaClreplacedRegistry().getMetaClreplaced(getClreplaced());

    /**
     * Loads the bean definitions via an GroovyBeanDefinitionReader.
     * @see org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        GroovyBeanDefinitionReader beanDefinitionReader = new GroovyBeanDefinitionReader(beanFactory);
        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        // Allow a subclreplaced to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }

    /**
     * Initialize the bean definition reader used for loading the bean
     * definitions of this context. Default implementation is empty.
     * <p>Can be overridden in subclreplacedes.
     * @param beanDefinitionReader the bean definition reader used by this context
     */
    protected void initBeanDefinitionReader(GroovyBeanDefinitionReader beanDefinitionReader) {
    }

    /**
     * Load the bean definitions with the given GroovyBeanDefinitionReader.
     * <p>The lifecycle of the bean factory is handled by the refreshBeanFactory method;
     * therefore this method is just supposed to load and/or register bean definitions.
     * <p>Delegates to a ResourcePatternResolver for resolving location patterns
     * into Resource instances.
     * @throws IOException if the required Groovy script or XML file isn't found
     * @see #refreshBeanFactory
     * @see #getConfigLocations
     * @see #getResources
     * @see #getResourcePatternResolver
     */
    protected void loadBeanDefinitions(GroovyBeanDefinitionReader reader) throws IOException {
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            for (String configLocation : configLocations) {
                reader.loadBeanDefinitions(configLocation);
            }
        }
    }

    /**
     * The default location for the root context is "/WEB-INF/applicationContext.groovy",
     * and "/WEB-INF/test-servlet.groovy" for a context with the namespace "test-servlet"
     * (like for a DispatcherServlet instance with the servlet-name "test").
     */
    @Override
    protected String[] getDefaultConfigLocations() {
        if (getNamespace() != null) {
            return new String[] { DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX };
        } else {
            return new String[] { DEFAULT_CONFIG_LOCATION };
        }
    }

    // Implementation of the GroovyObject interface
    @Override
    public void setMetaClreplaced(MetaClreplaced metaClreplaced) {
        this.metaClreplaced = metaClreplaced;
    }

    @Override
    public MetaClreplaced getMetaClreplaced() {
        return this.metaClreplaced;
    }

    @Override
    public Object invokeMethod(String name, Object args) {
        return this.metaClreplaced.invokeMethod(this, name, args);
    }

    @Override
    public void setProperty(String property, Object newValue) {
        this.metaClreplaced.setProperty(this, property, newValue);
    }

    @Override
    @Nullable
    public Object getProperty(String property) {
        if (containsBean(property)) {
            return getBean(property);
        } else if (this.contextWrapper.isReadableProperty(property)) {
            return this.contextWrapper.getPropertyValue(property);
        }
        throw new NoSuchBeanDefinitionException(property);
    }
}

18 View Source File : BeanUtils.java
License : Apache License 2.0
Project Creator : penggle

/**
 * 将Map形式的属性值(properties)填充到bean中去
 * @param bean
 * @param properties
 */
public static void populate(Object bean, Map<String, Object> properties) {
    if (!CollectionUtils.isEmpty(properties)) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
        for (Map.Entry<String, Object> property : properties.entrySet()) {
            if (beanWrapper.isWritableProperty(property.getKey())) {
                try {
                    beanWrapper.setPropertyValue(property.getKey(), property.getValue());
                } catch (NotWritablePropertyException e) {
                }
            }
        }
    }
}

18 View Source File : BookController.java
License : GNU General Public License v3.0
Project Creator : lizhongyue248

/**
 * 更新一个书单,提供一个书单的部分信息
 * PATCH   /api/v1/books/{id}   更新一条书单,提供部分信息
 *
 * @param id   更新的id
 * @param book 更新后的书单
 * @return http 响应
 */
@PatchMapping("/books/{id}")
public HttpEnreplacedy<?> booksPatch(@PathVariable Long id, @RequestBody Book book) {
    Book exist = bookRepository.findById(id).orElseThrow(() -> new ResourceNoFoundException(String.format("Book by id %s not found!", id)));
    BeanWrapper beanWrapper = new BeanWrapperImpl(book);
    PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
    List<String> nullPropertyNames = new ArrayList<>();
    for (PropertyDescriptor pd : propertyDescriptors) {
        if (beanWrapper.getPropertyValue(pd.getName()) == null) {
            nullPropertyNames.add(pd.getName());
        }
    }
    BeanUtils.copyProperties(book, exist, nullPropertyNames.toArray(new String[nullPropertyNames.size()]));
    return new ResponseEnreplacedy<>(bookRepository.save(exist), HttpStatus.OK);
}

18 View Source File : OptionWriter.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Renders the inner '{@code option}' tags using the supplied {@link Collection} of
 * objects as the source. The value of the {@link #valueProperty} field is used
 * when rendering the '{@code value}' of the '{@code option}' and the value of the
 * {@link #labelProperty} property is used when rendering the label.
 */
private void doRenderFromCollection(Collection<?> optionCollection, TagWriter tagWriter) throws JspException {
    for (Object item : optionCollection) {
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
        Object value;
        if (this.valueProperty != null) {
            value = wrapper.getPropertyValue(this.valueProperty);
        } else if (item instanceof Enum) {
            value = ((Enum<?>) item).name();
        } else {
            value = item;
        }
        Object label = (this.labelProperty != null ? wrapper.getPropertyValue(this.labelProperty) : item);
        renderOption(tagWriter, item, value, label);
    }
}

18 View Source File : AbstractMultiCheckedElementTag.java
License : Apache License 2.0
Project Creator : langtianya

private void writeObjectEntry(TagWriter tagWriter, String valueProperty, String labelProperty, Object item, int itemIndex) throws JspException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
    Object renderValue;
    if (valueProperty != null) {
        renderValue = wrapper.getPropertyValue(valueProperty);
    } else if (item instanceof Enum) {
        renderValue = ((Enum<?>) item).name();
    } else {
        renderValue = item;
    }
    Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
    writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}

18 View Source File : AbstractMultiCheckedElementTag.java
License : Apache License 2.0
Project Creator : langtianya

private void writeMapEntry(TagWriter tagWriter, String valueProperty, String labelProperty, Map.Entry<?, ?> entry, int itemIndex) throws JspException {
    Object mapKey = entry.getKey();
    Object mapValue = entry.getValue();
    BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
    BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
    Object renderValue = (valueProperty != null ? mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
    Object renderLabel = (labelProperty != null ? mapValueWrapper.getPropertyValue(labelProperty) : mapValue.toString());
    writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
}

18 View Source File : GroovyWebApplicationContext.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * {@link org.springframework.web.context.WebApplicationContext} implementation which takes
 * its configuration from Groovy bean definition scripts and/or XML files, as understood by
 * an {@link org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader}.
 * This is essentially the equivalent of
 * {@link org.springframework.context.support.GenericGroovyApplicationContext}
 * for a web environment.
 *
 * <p>By default, the configuration will be taken from "/WEB-INF/applicationContext.groovy"
 * for the root context, and "/WEB-INF/test-servlet.groovy" for a context with the namespace
 * "test-servlet" (like for a DispatcherServlet instance with the servlet-name "test").
 *
 * <p>The config location defaults can be overridden via the "contextConfigLocation"
 * context-param of {@link org.springframework.web.context.ContextLoader} and servlet
 * init-param of {@link org.springframework.web.servlet.FrameworkServlet}. Config locations
 * can either denote concrete files like "/WEB-INF/context.groovy" or Ant-style patterns
 * like "/WEB-INF/*-context.groovy" (see {@link org.springframework.util.PathMatcher}
 * javadoc for pattern details). Note that ".xml" files will be parsed as XML content;
 * all other kinds of resources will be parsed as Groovy scripts.
 *
 * <p>Note: In case of multiple config locations, later bean definitions will
 * override ones defined in earlier loaded files. This can be leveraged to
 * deliberately override certain bean definitions via an extra Groovy script.
 *
 * <p><b>For a WebApplicationContext that reads in a different bean definition format,
 * create an replacedogous subclreplaced of {@link AbstractRefreshableWebApplicationContext}.</b>
 * Such a context implementation can be specified as "contextClreplaced" context-param
 * for ContextLoader or "contextClreplaced" init-param for FrameworkServlet.
 *
 * @author Juergen Hoeller
 * @since 4.1
 * @see #setNamespace
 * @see #setConfigLocations
 * @see org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
 * @see org.springframework.web.context.ContextLoader#initWebApplicationContext
 * @see org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext
 */
public clreplaced GroovyWebApplicationContext extends AbstractRefreshableWebApplicationContext implements GroovyObject {

    /**
     * Default config location for the root context
     */
    public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.groovy";

    /**
     * Default prefix for building a config location for a namespace
     */
    public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

    /**
     * Default suffix for building a config location for a namespace
     */
    public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".groovy";

    private final BeanWrapper contextWrapper = new BeanWrapperImpl(this);

    private MetaClreplaced metaClreplaced = GroovySystem.getMetaClreplacedRegistry().getMetaClreplaced(getClreplaced());

    /**
     * Loads the bean definitions via an GroovyBeanDefinitionReader.
     * @see org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        GroovyBeanDefinitionReader beanDefinitionReader = new GroovyBeanDefinitionReader(beanFactory);
        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        // Allow a subclreplaced to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }

    /**
     * Initialize the bean definition reader used for loading the bean
     * definitions of this context. Default implementation is empty.
     * <p>Can be overridden in subclreplacedes.
     * @param beanDefinitionReader the bean definition reader used by this context
     */
    protected void initBeanDefinitionReader(GroovyBeanDefinitionReader beanDefinitionReader) {
    }

    /**
     * Load the bean definitions with the given GroovyBeanDefinitionReader.
     * <p>The lifecycle of the bean factory is handled by the refreshBeanFactory method;
     * therefore this method is just supposed to load and/or register bean definitions.
     * <p>Delegates to a ResourcePatternResolver for resolving location patterns
     * into Resource instances.
     * @throws IOException if the required Groovy script or XML file isn't found
     * @see #refreshBeanFactory
     * @see #getConfigLocations
     * @see #getResources
     * @see #getResourcePatternResolver
     */
    protected void loadBeanDefinitions(GroovyBeanDefinitionReader reader) throws IOException {
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            for (String configLocation : configLocations) {
                reader.loadBeanDefinitions(configLocation);
            }
        }
    }

    /**
     * The default location for the root context is "/WEB-INF/applicationContext.groovy",
     * and "/WEB-INF/test-servlet.groovy" for a context with the namespace "test-servlet"
     * (like for a DispatcherServlet instance with the servlet-name "test").
     */
    @Override
    protected String[] getDefaultConfigLocations() {
        if (getNamespace() != null) {
            return new String[] { DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX };
        } else {
            return new String[] { DEFAULT_CONFIG_LOCATION };
        }
    }

    // Implementation of the GroovyObject interface
    public void setMetaClreplaced(MetaClreplaced metaClreplaced) {
        this.metaClreplaced = metaClreplaced;
    }

    public MetaClreplaced getMetaClreplaced() {
        return this.metaClreplaced;
    }

    public Object invokeMethod(String name, Object args) {
        return this.metaClreplaced.invokeMethod(this, name, args);
    }

    public void setProperty(String property, Object newValue) {
        this.metaClreplaced.setProperty(this, property, newValue);
    }

    public Object getProperty(String property) {
        if (containsBean(property)) {
            return getBean(property);
        } else if (this.contextWrapper.isReadableProperty(property)) {
            return this.contextWrapper.getPropertyValue(property);
        }
        throw new NoSuchBeanDefinitionException(property);
    }
}

18 View Source File : StandardJmsActivationSpecFactory.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Apply the specified acknowledge mode to the ActivationSpec object.
 * <p>This implementation applies the standard JCA 1.5 acknowledge modes
 * "Auto-acknowledge" and "Dups-ok-acknowledge". It throws an exception in
 * case of {@code CLIENT_ACKNOWLEDGE} or {@code SESSION_TRANSACTED}
 * having been requested.
 * @param bw the BeanWrapper wrapping the ActivationSpec object
 * @param ackMode the configured acknowledge mode
 * (according to the constants in {@link javax.jms.Session}
 * @see javax.jms.Session#AUTO_ACKNOWLEDGE
 * @see javax.jms.Session#DUPS_OK_ACKNOWLEDGE
 * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
 * @see javax.jms.Session#SESSION_TRANSACTED
 */
protected void applyAcknowledgeMode(BeanWrapper bw, int ackMode) {
    if (ackMode == Session.SESSION_TRANSACTED) {
        throw new IllegalArgumentException("No support for SESSION_TRANSACTED: Only \"Auto-acknowledge\" " + "and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
    } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
        throw new IllegalArgumentException("No support for CLIENT_ACKNOWLEDGE: Only \"Auto-acknowledge\" " + "and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
    } else if (bw.isWritableProperty("acknowledgeMode")) {
        bw.setPropertyValue("acknowledgeMode", ackMode == Session.DUPS_OK_ACKNOWLEDGE ? "Dups-ok-acknowledge" : "Auto-acknowledge");
    } else if (ackMode == Session.DUPS_OK_ACKNOWLEDGE) {
        // Standard JCA 1.5 "acknowledgeMode" apparently not supported (e.g. WebSphere MQ 6.0.2.1)
        throw new IllegalArgumentException("Dups-ok-acknowledge not supported by underlying provider: " + this.activationSpecClreplaced.getName());
    }
}

18 View Source File : StandardJmsActivationSpecFactory.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Populate the given ApplicationSpec object with the settings
 * defined in the given configuration object.
 * <p>This implementation applies all standard JMS settings, but ignores
 * "maxConcurrency" and "prefetchSize" - not supported in standard JCA 1.5.
 * @param bw the BeanWrapper wrapping the ActivationSpec object
 * @param config the configured object holding common JMS settings
 */
protected void populateActivationSpecProperties(BeanWrapper bw, JmsActivationSpecConfig config) {
    String destinationName = config.getDestinationName();
    boolean pubSubDomain = config.isPubSubDomain();
    Object destination = destinationName;
    if (this.destinationResolver != null) {
        try {
            destination = this.destinationResolver.resolveDestinationName(null, destinationName, pubSubDomain);
        } catch (JMSException ex) {
            throw new DestinationResolutionException("Cannot resolve destination name [" + destinationName + "]", ex);
        }
    }
    bw.setPropertyValue("destination", destination);
    bw.setPropertyValue("destinationType", pubSubDomain ? Topic.clreplaced.getName() : Queue.clreplaced.getName());
    if (bw.isWritableProperty("subscriptionDurability")) {
        bw.setPropertyValue("subscriptionDurability", config.isSubscriptionDurable() ? "Durable" : "NonDurable");
    } else if (config.isSubscriptionDurable()) {
        // Standard JCA 1.5 "subscriptionDurability" apparently not supported...
        throw new IllegalArgumentException("Durable subscriptions not supported by underlying provider: " + this.activationSpecClreplaced.getName());
    }
    if (config.isSubscriptionShared()) {
        throw new IllegalArgumentException("Shared subscriptions not supported for JCA-driven endpoints");
    }
    if (config.getSubscriptionName() != null) {
        bw.setPropertyValue("subscriptionName", config.getSubscriptionName());
    }
    if (config.getClientId() != null) {
        bw.setPropertyValue("clientId", config.getClientId());
    }
    if (config.getMessageSelector() != null) {
        bw.setPropertyValue("messageSelector", config.getMessageSelector());
    }
    applyAcknowledgeMode(bw, config.getAcknowledgeMode());
}

18 View Source File : PropertyPathFactoryBean.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * {@link FactoryBean} that evaluates a property path on a given target object.
 *
 * <p>The target object can be specified directly or via a bean name.
 *
 * <p>Usage examples:
 *
 * <pre clreplaced="code"><!-- target bean to be referenced by name -->
 * <bean id="tb" clreplaced="org.springframework.beans.TestBean" singleton="false">
 *   <property name="age" value="10"/>
 *   <property name="spouse">
 *     <bean clreplaced="org.springframework.beans.TestBean">
 *       <property name="age" value="11"/>
 *     </bean>
 *   </property>
 * </bean>
 *
 * <!-- will result in 12, which is the value of property 'age' of the inner bean -->
 * <bean id="propertyPath1" clreplaced="org.springframework.beans.factory.config.PropertyPathFactoryBean">
 *   <property name="targetObject">
 *     <bean clreplaced="org.springframework.beans.TestBean">
 *       <property name="age" value="12"/>
 *     </bean>
 *   </property>
 *   <property name="propertyPath" value="age"/>
 * </bean>
 *
 * <!-- will result in 11, which is the value of property 'spouse.age' of bean 'tb' -->
 * <bean id="propertyPath2" clreplaced="org.springframework.beans.factory.config.PropertyPathFactoryBean">
 *   <property name="targetBeanName" value="tb"/>
 *   <property name="propertyPath" value="spouse.age"/>
 * </bean>
 *
 * <!-- will result in 10, which is the value of property 'age' of bean 'tb' -->
 * <bean id="tb.age" clreplaced="org.springframework.beans.factory.config.PropertyPathFactoryBean"/></pre>
 *
 * <p>If you are using Spring 2.0 and XML Schema support in your configuration file(s),
 * you can also use the following style of configuration for property path access.
 * (See also the appendix enreplacedled 'XML Schema-based configuration' in the Spring
 * reference manual for more examples.)
 *
 * <pre clreplaced="code"> <!-- will result in 10, which is the value of property 'age' of bean 'tb' -->
 * <util:property-path id="name" path="testBean.age"/></pre>
 *
 * Thanks to Matthias Ernst for the suggestion and initial prototype!
 *
 * @author Juergen Hoeller
 * @since 1.1.2
 * @see #setTargetObject
 * @see #setTargetBeanName
 * @see #setPropertyPath
 */
public clreplaced PropertyPathFactoryBean implements FactoryBean<Object>, BeanNameAware, BeanFactoryAware {

    private static final Log logger = LogFactory.getLog(PropertyPathFactoryBean.clreplaced);

    private BeanWrapper targetBeanWrapper;

    private String targetBeanName;

    private String propertyPath;

    private Clreplaced<?> resultType;

    private String beanName;

    private BeanFactory beanFactory;

    /**
     * Specify a target object to apply the property path to.
     * Alternatively, specify a target bean name.
     * @param targetObject a target object, for example a bean reference
     * or an inner bean
     * @see #setTargetBeanName
     */
    public void setTargetObject(Object targetObject) {
        this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
    }

    /**
     * Specify the name of a target bean to apply the property path to.
     * Alternatively, specify a target object directly.
     * @param targetBeanName the bean name to be looked up in the
     * containing bean factory (e.g. "testBean")
     * @see #setTargetObject
     */
    public void setTargetBeanName(String targetBeanName) {
        this.targetBeanName = StringUtils.trimAllWhitespace(targetBeanName);
    }

    /**
     * Specify the property path to apply to the target.
     * @param propertyPath the property path, potentially nested
     * (e.g. "age" or "spouse.age")
     */
    public void setPropertyPath(String propertyPath) {
        this.propertyPath = StringUtils.trimAllWhitespace(propertyPath);
    }

    /**
     * Specify the type of the result from evaluating the property path.
     * <p>Note: This is not necessary for directly specified target objects
     * or singleton target beans, where the type can be determined through
     * introspection. Just specify this in case of a prototype target,
     * provided that you need matching by type (for example, for autowiring).
     * @param resultType the result type, for example "java.lang.Integer"
     */
    public void setResultType(Clreplaced<?> resultType) {
        this.resultType = resultType;
    }

    /**
     * The bean name of this PropertyPathFactoryBean will be interpreted
     * as "beanName.property" pattern, if neither "targetObject" nor
     * "targetBeanName" nor "propertyPath" have been specified.
     * This allows for concise bean definitions with just an id/name.
     */
    @Override
    public void setBeanName(String beanName) {
        this.beanName = StringUtils.trimAllWhitespace(BeanFactoryUtils.originalBeanName(beanName));
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
        if (this.targetBeanWrapper != null && this.targetBeanName != null) {
            throw new IllegalArgumentException("Specify either 'targetObject' or 'targetBeanName', not both");
        }
        if (this.targetBeanWrapper == null && this.targetBeanName == null) {
            if (this.propertyPath != null) {
                throw new IllegalArgumentException("Specify 'targetObject' or 'targetBeanName' in combination with 'propertyPath'");
            }
            // No other properties specified: check bean name.
            int dotIndex = this.beanName.indexOf('.');
            if (dotIndex == -1) {
                throw new IllegalArgumentException("Neither 'targetObject' nor 'targetBeanName' specified, and PropertyPathFactoryBean " + "bean name '" + this.beanName + "' does not follow 'beanName.property' syntax");
            }
            this.targetBeanName = this.beanName.substring(0, dotIndex);
            this.propertyPath = this.beanName.substring(dotIndex + 1);
        } else if (this.propertyPath == null) {
            // either targetObject or targetBeanName specified
            throw new IllegalArgumentException("'propertyPath' is required");
        }
        if (this.targetBeanWrapper == null && this.beanFactory.isSingleton(this.targetBeanName)) {
            // Eagerly fetch singleton target bean, and determine result type.
            Object bean = this.beanFactory.getBean(this.targetBeanName);
            this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
            this.resultType = this.targetBeanWrapper.getPropertyType(this.propertyPath);
        }
    }

    @Override
    public Object getObject() throws BeansException {
        BeanWrapper target = this.targetBeanWrapper;
        if (target != null) {
            if (logger.isWarnEnabled() && this.targetBeanName != null && this.beanFactory instanceof ConfigurableBeanFactory && ((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
                logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " + "reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
            }
        } else {
            // Fetch prototype target bean...
            Object bean = this.beanFactory.getBean(this.targetBeanName);
            target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
        }
        return target.getPropertyValue(this.propertyPath);
    }

    @Override
    public Clreplaced<?> getObjectType() {
        return this.resultType;
    }

    /**
     * While this FactoryBean will often be used for singleton targets,
     * the invoked getters for the property path might return a new object
     * for each call, so we have to replacedume that we're not returning the
     * same object for each {@link #getObject()} call.
     */
    @Override
    public boolean isSingleton() {
        return false;
    }
}

18 View Source File : DepartmentDataServiceImpl.java
License : Apache License 2.0
Project Creator : kaituozhesh

/**
 * 获取对象中所有不为空的属性名  会获取父级属性
 *
 * @param source
 * @return
 */
private static Map<String, Object> getNotNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    Map<String, Object> paramMap = new HashMap<>();
    for (java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (!ObjectUtils.isEmpty(srcValue)) {
            paramMap.put(pd.getName(), srcValue);
        }
    }
    paramMap.remove("clreplaced");
    paramMap.remove("marketId");
    return paramMap;
}

18 View Source File : BeanMapper.java
License : MIT License
Project Creator : geekmall

private static String[] getNullOrEmptyCollectionPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    Set<String> emptyNames = new HashSet<String>();
    for (java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null)
            emptyNames.add(pd.getName());
        // 空集合也算
        if (srcValue instanceof Collection) {
            Collection collection = (Collection) srcValue;
            if (collection.size() == 0) {
                emptyNames.add(pd.getName());
            }
        }
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

18 View Source File : RouteManagerUtil.java
License : GNU General Public License v2.0
Project Creator : futurewei-cloud

public static String[] getNullPropertyNames(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    Set<String> emptyNames = new HashSet<String>();
    for (java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null)
            emptyNames.add(pd.getName());
    }
    String[] res = new String[emptyNames.size()];
    return emptyNames.toArray(res);
}

18 View Source File : ConvertedDatatablesData.java
License : Apache License 2.0
Project Creator : DISID

private static Map<String, Object> convert(Object value, ConversionService conversionService, DatatablesColumns columns, String propertySeparator) {
    BeanWrapper bean = new BeanWrapperImpl(value);
    Map<String, Object> convertedValue = new HashMap<>();
    for (Column column : columns.getColumns()) {
        String property = column.getData();
        convertedValue.put(property, convertProperty(bean, property, conversionService, propertySeparator));
    }
    return convertedValue;
}

See More Examples