Example usage for org.springframework.beans PropertyValue getValue

List of usage examples for org.springframework.beans PropertyValue getValue

Introduction

In this page you can find the example usage for org.springframework.beans PropertyValue getValue.

Prototype

@Nullable
public Object getValue() 

Source Link

Document

Return the value of the property.

Usage

From source file:uk.org.ponder.rsac.support.BeanDefUtil.java

static RSACBeanInfo convertBeanDef(BeanDefinition origdef, String beanname,
        ConfigurableListableBeanFactory factory, MethodAnalyser abdAnalyser, BeanDefConverter converter) {
    RSACBeanInfo rbi = new RSACBeanInfo();
    AbstractBeanDefinition def = getMergedBeanDefinition(factory, beanname, origdef);
    MutablePropertyValues pvs = def.getPropertyValues();
    PropertyValue[] values = pvs.getPropertyValues();
    for (int j = 0; j < values.length; ++j) {
        PropertyValue thispv = values[j];
        Object beannames = BeanDefUtil.propertyValueToBeanName(thispv.getValue(), converter);
        boolean skip = false;
        // skip recording the dependency if it was unresolvable (some
        // unrecognised
        // type) or was a single-valued type referring to a static dependency.
        // NB - we now record ALL dependencies - bean-copying strategy
        // discontinued.
        if (beannames == null
        // || beannames instanceof String
        // && !blankcontext.containsBean((String) beannames)
        ) {// w ww  . j  a va 2 s .  c  om
            skip = true;
        }
        if (!skip) {
            rbi.recordDependency(thispv.getName(), beannames);
        }
    }
    // NB - illegal cast here is unavoidable.
    // Bit of a problem here with Spring flow - apparently the bean class
    // will NOT be set for a "factory-method" bean UNTIL it has been
    // instantiated
    // via the logic in AbstractAutowireCapableBeanFactory l.376:
    // protected BeanWrapper instantiateUsingFactoryMethod(
    AbstractBeanDefinition abd = def;
    rbi.factorybean = abd.getFactoryBeanName();
    rbi.factorymethod = abd.getFactoryMethodName();
    rbi.initmethod = abd.getInitMethodName();
    rbi.destroymethod = abd.getDestroyMethodName();
    rbi.islazyinit = abd.isLazyInit();
    rbi.dependson = abd.getDependsOn();
    rbi.issingleton = abd.isSingleton();
    rbi.isabstract = abd.isAbstract();
    rbi.aliases = factory.containsBeanDefinition(beanname) ? factory.getAliases(beanname)
            : StringArrayParser.EMPTY_STRINGL;
    if (abd.hasConstructorArgumentValues()) {
        ConstructorArgumentValues cav = abd.getConstructorArgumentValues();
        boolean hasgeneric = !cav.getGenericArgumentValues().isEmpty();
        boolean hasindexed = !cav.getIndexedArgumentValues().isEmpty();
        if (hasgeneric && hasindexed) {
            throw new UnsupportedOperationException("RSAC Bean " + beanname
                    + " has both indexed and generic constructor arguments, which is not supported");
        }
        if (hasgeneric) {
            List cvalues = cav.getGenericArgumentValues();
            rbi.constructorargvals = new ConstructorArgumentValues.ValueHolder[cvalues.size()];
            for (int i = 0; i < cvalues.size(); ++i) {
                rbi.constructorargvals[i] = (ConstructorArgumentValues.ValueHolder) cvalues.get(i);
            }
        } else if (hasindexed) {
            Map cvalues = cav.getIndexedArgumentValues();
            rbi.constructorargvals = new ConstructorArgumentValues.ValueHolder[cvalues.size()];
            for (int i = 0; i < cvalues.size(); ++i) {
                rbi.constructorargvals[i] = (ConstructorArgumentValues.ValueHolder) cvalues.get(new Integer(i));
            }
        }
    }
    if (rbi.factorymethod == null) {
        // Core Spring change at 2.0M5 - ALL bean classes are now irrevocably
        // lazy!!
        // Package org.springframework.beans
        // introduced lazy loading (and lazy validation) of bean classes in
        // standard bean factories and bean definition readers
        AccessMethod bcnaccess = abdAnalyser.getAccessMethod("beanClassName");
        if (bcnaccess != null) {
            String bcn = (String) bcnaccess.getChildObject(abd);
            if (bcn != null) {
                rbi.beanclass = ClassGetter.forName(bcn);
                if (rbi.beanclass == null) {
                    throw new IllegalArgumentException("Class name " + bcn + " for bean definition with name "
                            + beanname + " cannot be resolved");
                }
            }
        } else {
            // all right then BE like that! We'll work out the class later.
            // NB - beandef.getBeanClass() was eliminated around 1.2, we must
            // use the downcast even earlier now.
            rbi.beanclass = abd.getBeanClass();
        }
    }
    return rbi;
}

From source file:org.springmodules.cache.config.ConfigAssert.java

/**
 * Asserts the given set of property values contains the expected property
 * value./*  www . j  av a  2 s . c  o  m*/
 * 
 * @param propertyValues
 *          the given set of property values
 * @param expectedPropertyValue
 *          the expected property value
 */
public static void assertPropertyIsPresent(MutablePropertyValues propertyValues,
        PropertyValue expectedPropertyValue) {

    String propertyName = expectedPropertyValue.getName();
    PropertyValue actualPropertyValue = propertyValues.getPropertyValue(propertyName);

    Assert.assertNotNull("Property " + StringUtils.quote(propertyName) + " not found", actualPropertyValue);

    Object expectedValue = expectedPropertyValue.getValue();
    Object actualValue = actualPropertyValue.getValue();
    String message = "<Property " + StringUtils.quote(propertyName) + ">";

    assertEquals(message, expectedValue, actualValue);
}

From source file:me.springframework.di.spring.SpringConfigurationLoader.java

/**
 * Loads a {@link MutableInstance} from one of the {@link BeanDefinition}s
 * provided by the {@link BeanDefinitionRegistry} passed in.
 * //from   www . j  ava 2  s .c  om
 * @param instance
 *            A {@link MutableInstance} to be populated.
 * @param definition
 *            A {@link BeanDefinition}, providing the meta data.
 */
private static void load(MutableInstance instance, BeanDefinition definition, MutableContext context) {
    instance.setReferencedType(definition.getBeanClassName());
    instance.setPrimitive(false);
    instance.setLazyInit(definition.isLazyInit());
    instance.setId("source" + counter++);
    instance.setFactoryMethod(definition.getFactoryMethodName());
    instance.setFactoryInstance(definition.getFactoryBeanName());
    if (ConfigurableBeanFactory.SCOPE_SINGLETON.equals(definition.getScope())) {
        instance.setScope(Scope.SINGLETON);
    }
    if (ConfigurableBeanFactory.SCOPE_PROTOTYPE.equals(definition.getScope())) {
        instance.setScope(Scope.PROTOTYPE);
    }
    if (definition instanceof AbstractBeanDefinition) {
        instance.setInitMethod(((AbstractBeanDefinition) definition).getInitMethodName());
        instance.setDestroyMethod(((AbstractBeanDefinition) definition).getDestroyMethodName());
    }
    if (!definition.getConstructorArgumentValues().isEmpty()) {
        List<MutableConstructorArgument> arguments = new ArrayList<MutableConstructorArgument>();
        for (Object object : definition.getConstructorArgumentValues().getGenericArgumentValues()) {
            MutableConstructorArgument argument = new MutableConstructorArgument(instance);
            argument.setInstance(instance);
            ValueHolder holder = (ValueHolder) object;
            argument.setSource(loadSource(context, argument, holder.getValue()));
            argument.setType(holder.getType());
            arguments.add(argument);
        }
        instance.setConstructorArguments(arguments);
    }
    Set<MutablePropertySetter> setters = new HashSet<MutablePropertySetter>();
    for (Object object : definition.getPropertyValues().getPropertyValueList()) {
        MutablePropertySetter setter = new MutablePropertySetter(instance);
        setter.setInstance(instance);
        PropertyValue value = (PropertyValue) object;
        setter.setName(value.getName());
        setter.setSource(loadSource(context, setter, value.getValue()));
        setters.add(setter);
    }
    instance.setSetters(setters);

    // added by woj
    instance.setAutowireCandidate(definition.isAutowireCandidate());
    if (definition instanceof AbstractBeanDefinition) {
        instance.setAutowireMode(((AbstractBeanDefinition) definition).getResolvedAutowireMode());
    } else {
        instance.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO);
    }
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Resolves the {@link CacheStatistics cache statistics} of the {@link TransactionalCache transactional cache} instance that facades a
 * specific {@link SimpleCache shared/*  ww w .  j  a  v  a2  s . c  o  m*/
 * cache} and provides it in a more script-friendly representation.
 *
 * @param sharedCacheName
 *            the name of the shared cache
 * @return a facade to a snapshot of the cache statistics
 */
public static AlfrescoCacheStatsFacade resolveStatisticsViaTransactional(final String sharedCacheName) {
    ParameterCheck.mandatoryString("sharedCacheName", sharedCacheName);

    LOGGER.debug("Trying to resolve transactional cache for shared cache {}", sharedCacheName);

    String txnCacheName = null;

    final WebApplicationContext applicationContext = ContextLoader.getCurrentWebApplicationContext();

    if (applicationContext instanceof ConfigurableApplicationContext) {
        final ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext)
                .getBeanFactory();
        final String[] txnCacheBeanNames = applicationContext.getBeanNamesForType(TransactionalCache.class,
                false, false);

        // this is a rather ugly reference lookup, but so far I see no other way
        for (final String txnCacheBeanName : txnCacheBeanNames) {
            final BeanDefinition txnCacheDefinition = beanFactory.getBeanDefinition(txnCacheBeanName);

            final PropertyValue sharedCacheValue = txnCacheDefinition.getPropertyValues()
                    .getPropertyValue("sharedCache");
            final PropertyValue nameValue = txnCacheDefinition.getPropertyValues().getPropertyValue("name");
            if (nameValue != null && sharedCacheValue != null) {
                final Object sharedCacheRef = sharedCacheValue.getValue();
                if (sharedCacheRef instanceof RuntimeBeanReference) {
                    final String sharedCacheBeanName = ((RuntimeBeanReference) sharedCacheRef).getBeanName();

                    Object nameValueObj = nameValue.getValue();
                    if (nameValueObj instanceof TypedStringValue) {
                        nameValueObj = ((TypedStringValue) nameValueObj).getValue();
                    }

                    if (EqualsHelper.nullSafeEquals(sharedCacheBeanName, sharedCacheName)) {
                        if (txnCacheName != null) {
                            LOGGER.info("Shared cache {} is referenced by multiple transactional caches",
                                    sharedCacheName);
                            txnCacheName = null;
                            break;
                        }
                        txnCacheName = String.valueOf(nameValueObj);
                        LOGGER.debug("Resolved transactional cache {} for shared cache {}", txnCacheName,
                                sharedCacheName);
                    } else {
                        try {
                            final DefaultSimpleCache<?, ?> defaultSimpleCache = applicationContext
                                    .getBean(sharedCacheBeanName, DefaultSimpleCache.class);
                            if (EqualsHelper.nullSafeEquals(defaultSimpleCache.getCacheName(),
                                    sharedCacheName)) {
                                if (txnCacheName != null) {
                                    LOGGER.info(
                                            "Shared cache {} is referenced by multiple transactional caches",
                                            sharedCacheName);
                                    txnCacheName = null;
                                    break;
                                }
                                txnCacheName = String.valueOf(nameValueObj);
                                LOGGER.debug("Resolved transactional cache {} for shared cache {}",
                                        txnCacheName, sharedCacheName);
                            }
                            continue;
                        } catch (final BeansException be) {
                            // ignore - can be expected e.g. in EE or with alternative cache implementations
                        }
                    }
                }
            }
        }

        if (txnCacheName == null) {
            LOGGER.debug("Unable to resolve unique transactional cache for shared cache {}", sharedCacheName);
        }
    } else {
        LOGGER.debug(
                "Application context is not a configurable application context - unable to resolve transactional cache");
    }

    AlfrescoCacheStatsFacade facade = null;
    if (txnCacheName != null) {
        final CacheStatistics cacheStatistics = applicationContext.getBean("cacheStatistics",
                CacheStatistics.class);
        try {
            final Map<OpType, OperationStats> allStats = cacheStatistics.allStats(txnCacheName);
            facade = new AlfrescoCacheStatsFacade(allStats);
        } catch (final NoStatsForCache e) {
            facade = new AlfrescoCacheStatsFacade(Collections.emptyMap());
        }
    }

    return facade;
}

From source file:com.mtgi.analytics.aop.config.v11.BtManagerBeanDefinitionParser.java

/** 
 * called by nested tags to push inner beans into the enclosing {@link BehaviorTrackingManagerImpl}.
 * @return <span>true if the inner bean was added to an enclosing {@link BehaviorTrackingManagerImpl}.  Otherwise, the bean definition
 * is not nested inside a &lt;bt:manager&gt; tag and therefore will have to be registered as a global bean in the application
 * context.</span>/* ww  w.  ja v a  2s.c o m*/
 */
protected static boolean registerNestedBean(BeanDefinitionHolder nested, String parentProperty,
        ParserContext parserContext) {
    //add parsed inner bean element to containing manager definition; e.g. persister or SessionContext impls.
    CompositeComponentDefinition parent = parserContext.getContainingComponent();
    if (parent instanceof ManagerComponentDefinition) {
        //we are nested; add to enclosing bean def.
        ManagerComponentDefinition mcd = (ManagerComponentDefinition) parent;
        BeanDefinition managerDef = parserContext.getContainingBeanDefinition();

        MutablePropertyValues props = managerDef.getPropertyValues();
        PropertyValue current = props.getPropertyValue(parentProperty);
        boolean innerBean = true;

        if (current != null) {
            //if the original value is a reference, replace it with an alias to the nested bean definition.
            //this means the nested bean takes the place of the default definition
            //in other places where it might be referenced, as well as during mbean export
            Object value = current.getValue();
            DefaultListableBeanFactory factory = mcd.getTemplateFactory();
            if (value instanceof RuntimeBeanReference) {
                String ref = ((RuntimeBeanReference) value).getBeanName();

                if (factory.getBeanDefinition(ref) == nested.getBeanDefinition()) {
                    //the nested definition is the same as the default definition
                    //by reference, so we don't need to make it an inner bean definition.
                    innerBean = false;
                }
            }
        }
        if (innerBean)
            props.addPropertyValue(parentProperty, nested);
        mcd.addNestedProperty(parentProperty);
        return true;
    }
    //bean is not nested inside bt:manager
    return false;
}

From source file:org.uimafit.component.initialize.ConfigurationParameterInitializer.java

/**
 * Initialize a component from an {@link UimaContext} This code can be a little confusing
 * because the configuration parameter annotations are used in two contexts: in describing the
 * component and to initialize member variables from a {@link UimaContext}. Here we are
 * performing the latter task. It is important to remember that the {@link UimaContext} passed
 * in to this method may or may not have been derived using reflection of the annotations (i.e.
 * using {@link ConfigurationParameterFactory} via e.g. a call to a AnalysisEngineFactory.create
 * method). It is just as possible for the description of the component to come directly from an
 * XML descriptor file. So, for example, just because a configuration parameter specifies a
 * default value, this does not mean that the passed in context will have a value for that
 * configuration parameter. It should be possible for a descriptor file to specify its own value
 * or to not provide one at all. If the context does not have a configuration parameter, then
 * the default value provided by the developer as specified by the defaultValue element of the
 * {@link ConfigurationParameter} will be used. See comments in the code for additional details.
 *
 * @param component the component to initialize.
 * @param context a UIMA context with configuration parameters.
 *///from   w ww .  j  a v  a 2 s .  co  m
public static void initialize(final Object component, final UimaContext context)
        throws ResourceInitializationException {
    MutablePropertyValues values = new MutablePropertyValues();
    List<String> mandatoryValues = new ArrayList<String>();

    for (Field field : ReflectionUtil.getFields(component)) { // component.getClass().getDeclaredFields())
        if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
            org.uimafit.descriptor.ConfigurationParameter annotation = field
                    .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);

            Object parameterValue;
            String parameterName = ConfigurationParameterFactory.getConfigurationParameterName(field);

            // Obtain either from the context - or - if the context does not provide the
            // parameter, check if there is a default value. Note there are three possibilities:
            // 1) Parameter present and set
            // 2) Parameter present and set to null (null value)
            // 3) Parameter not present (also provided as null value by UIMA)
            // Unfortunately we cannot make a difference between case 2 and 3 since UIMA does 
            // not allow us to actually get a list of the parameters set in the context. We can
            // only get a list of the declared parameters. Thus we have to rely on the null
            // value.
            parameterValue = context.getConfigParameterValue(parameterName);
            if (parameterValue == null) {
                parameterValue = ConfigurationParameterFactory.getDefaultValue(field);
            }

            if (parameterValue != null) {
                values.addPropertyValue(field.getName(), parameterValue);
            }

            // TODO does this check really belong here? It seems that
            // this check is already performed by UIMA
            if (annotation.mandatory()) {
                mandatoryValues.add(field.getName());

                //               if (parameterValue == null) {
                //                  final String key = ResourceInitializationException.CONFIG_SETTING_ABSENT;
                //                  throw new ResourceInitializationException(key,
                //                        new Object[] { configurationParameterName });
                //               }
            }
            //            else {
            //               if (parameterValue == null) {
            //                  continue;
            //               }
            //            }
            //            final Object fieldValue = convertValue(field, parameterValue);
            //            try {
            //               setParameterValue(component, field, fieldValue);
            //            }
            //            catch (Exception e) {
            //               throw new ResourceInitializationException(e);
            //            }
        }
    }

    DataBinder binder = new DataBinder(component) {
        @Override
        protected void checkRequiredFields(MutablePropertyValues mpvs) {
            String[] requiredFields = getRequiredFields();
            if (!ObjectUtils.isEmpty(requiredFields)) {
                Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
                PropertyValue[] pvs = mpvs.getPropertyValues();
                for (PropertyValue pv : pvs) {
                    String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
                    propertyValues.put(canonicalName, pv);
                }
                for (String field : requiredFields) {
                    PropertyValue pv = propertyValues.get(field);
                    boolean empty = (pv == null || pv.getValue() == null);
                    // For our purposes, empty Strings or empty String arrays do not count as
                    // empty. Empty is only "null".
                    //                  if (!empty) {
                    //                     if (pv.getValue() instanceof String) {
                    //                        empty = !StringUtils.hasText((String) pv.getValue());
                    //                     }
                    //                     else if (pv.getValue() instanceof String[]) {
                    //                        String[] values = (String[]) pv.getValue();
                    //                        empty = (values.length == 0 || !StringUtils.hasText(values[0]));
                    //                     }
                    //                  }
                    if (empty) {
                        // Use bind error processor to create FieldError.
                        getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
                        // Remove property from property values to bind:
                        // It has already caused a field error with a rejected value.
                        if (pv != null) {
                            mpvs.removePropertyValue(pv);
                            propertyValues.remove(field);
                        }
                    }
                }
            }
        }
    };
    binder.initDirectFieldAccess();
    PropertyEditorUtil.registerUimaFITEditors(binder);
    binder.setRequiredFields(mandatoryValues.toArray(new String[mandatoryValues.size()]));
    binder.bind(values);
    if (binder.getBindingResult().hasErrors()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Errors initializing [" + component.getClass() + "]");
        for (ObjectError error : binder.getBindingResult().getAllErrors()) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(error.getDefaultMessage());
        }
        throw new IllegalArgumentException(sb.toString());
    }
}

From source file:org.bytesoft.bytetcc.supports.dubbo.validator.ProtocolConfigValidator.java

public void validate() throws BeansException {
    MutablePropertyValues mpv = this.beanDefinition.getPropertyValues();
    PropertyValue pv = mpv.getPropertyValue("port");
    Object value = pv == null ? null : pv.getValue();
    if (pv == null || value == null) {
        throw new FatalBeanException(
                "The value of the attribute 'port' (<dubbo:protocol port='...' />) must be explicitly specified.");
    } else if ("-1".equals(value)) {
        throw new FatalBeanException(
                "The value of the attribute 'port' (<dubbo:protocol port='...' />) must be explicitly specified and not equal to -1.");
    }//  w  w w .  jav  a2s. co  m
}

From source file:org.synyx.hades.dao.orm.DaoInterfaceAwareBeanPostProcessor.java

/**
 * Returns the class which is configured in the given {@link PropertyValue}.
 * In case it is not a {@link TypedStringValue} or the value contained
 * cannot be interpreted as {@link Class} it will return null.
 * /*from   w w w. j  av a  2  s.  c  o  m*/
 * @param propertyValue
 * @return
 */
private Class<?> getClassForPropertyValue(PropertyValue propertyValue) {

    Object value = propertyValue.getValue();
    String className = null;

    if (value instanceof TypedStringValue) {
        className = ((TypedStringValue) value).getValue();
    } else if (value instanceof String) {
        className = (String) value;
    } else if (value instanceof Class<?>) {
        return (Class<?>) value;
    } else {
        return null;
    }

    try {
        return ClassUtils.resolveClassName(className,
                DaoInterfaceAwareBeanPostProcessor.class.getClassLoader());
    } catch (IllegalArgumentException ex) {
        return null;
    }
}

From source file:org.bytesoft.bytejta.supports.spring.TransactionEndpointPostProcessor.java

public void initializeCoordinator(ConfigurableListableBeanFactory beanFactory, BeanDefinition protocolDef,
        String compensableBeanId) throws BeansException {
    MutablePropertyValues mpv = protocolDef.getPropertyValues();
    PropertyValue pv = mpv.getPropertyValue("port");
    if (pv == null || pv.getValue() == null) {
        throw new FatalBeanException("Attribute 'port' of <dubbo:protocol ... /> is null.");
    }//from  w  ww .  j a  va 2  s  .c  om

    String host = CommonUtils.getInetAddress();
    String port = String.valueOf(pv.getValue());
    String identifier = String.format("%s:%s", host, port);

    BeanDefinition beanDef = beanFactory.getBeanDefinition(compensableBeanId);
    beanDef.getPropertyValues().addPropertyValue("identifier", identifier);
}

From source file:de.luzzifa.spring.test.CustomBeanPostProcessor.java

@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {
    final List<PropertyValue> original = getOriginalPropertyValuesList(pvs);
    final List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean cloneNecessary = false;

    for (PropertyValue pv : original) {
        final Object originalValue = pv.getValue();
        if ("${stringList}".equals(originalValue)) {
            final Object newPropertyValue = getNewPropertyValue();
            final PropertyValue npv = new PropertyValue(pv, newPropertyValue);
            deepCopy.add(npv);/*from w ww . j a  va 2s  .c o  m*/
            cloneNecessary = true;
        } else {
            deepCopy.add(pv);
        }
    }

    if (cloneNecessary) {
        // Set our (possibly massaged) deep copy.
        pvs = new MutablePropertyValues(deepCopy);
    }
    return pvs;
}