Java Code Examples for org.springframework.beans.PropertyAccessorFactory

The following examples show how to use org.springframework.beans.PropertyAccessorFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdal   Source File: FormUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add a link on primary and dependent JComboBoxes by property name. 
 * When selection changes on primary use propertyName to get a Collection and fill dependent JComboBox with it
 * @param primary JComboBox when selection changes
 * @param dependent JComboBox that are filled with collection	
 * @param propertyName the property name for get the collection from primary selected item
 * @param addNull if true, add a null as first combobox item
 */
@SuppressWarnings("rawtypes")
public static void link(final JComboBox primary, final JComboBox dependent, final String propertyName, 
		final boolean addNull) {
	
	primary.addActionListener(new ActionListener() {
	
		public void actionPerformed(ActionEvent e) {
			Object selected = primary.getSelectedItem();
			if (selected != null) {
				BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(selected);
				if (wrapper.isWritableProperty(propertyName)) {
					Collection collection = (Collection) wrapper.getPropertyValue(propertyName);
					Vector<Object> vector = new Vector<Object>(collection);
					if (addNull) vector.add(0, null);
					DefaultComboBoxModel model = new DefaultComboBoxModel(vector);
					dependent.setModel(model);
				}
				else {
					log.error("Can't write on propety '" + propertyName + "' of class: '" + selected.getClass() + "'");
				}
			}
		}
	});
}
 
Example 2
Source Project: spring-analysis-note   Source File: OptionWriter.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 3
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);
}
 
Example 4
@Override
public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) {
	Class<?> activationSpecClassToUse = this.activationSpecClass;
	if (activationSpecClassToUse == null) {
		activationSpecClassToUse = determineActivationSpecClass(adapter);
		if (activationSpecClassToUse == null) {
			throw new IllegalStateException("Property 'activationSpecClass' is required");
		}
	}

	ActivationSpec spec = (ActivationSpec) BeanUtils.instantiateClass(activationSpecClassToUse);
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(spec);
	if (this.defaultProperties != null) {
		bw.setPropertyValues(this.defaultProperties);
	}
	populateActivationSpecProperties(bw, config);
	return spec;
}
 
Example 5
Source Project: spring-analysis-note   Source File: AnnotationBeanUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, @Nullable StringValueResolver valueResolver,
		String... excludedProperties) {

	Set<String> excluded = (excludedProperties.length == 0 ? Collections.emptySet() :
			new HashSet<>(Arrays.asList(excludedProperties)));
	Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	for (Method annotationProperty : annotationProperties) {
		String propertyName = annotationProperty.getName();
		if (!excluded.contains(propertyName) && bw.isWritableProperty(propertyName)) {
			Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
			if (valueResolver != null && value instanceof String) {
				value = valueResolver.resolveStringValue((String) value);
			}
			bw.setPropertyValue(propertyName, value);
		}
	}
}
 
Example 6
@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);
}
 
Example 7
Source Project: jdal   Source File: CompositeBinder.java    License: Apache License 2.0 6 votes vote down vote up
public void autobind(Object view) {
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(getModel());
	PropertyAccessor  viewPropertyAccessor = new DirectFieldAccessor(view);
	// iterate on model properties
	for (PropertyDescriptor pd : bw.getPropertyDescriptors()) {
		String propertyName = pd.getName();
		if ( !ignoredProperties.contains(propertyName) && viewPropertyAccessor.isReadableProperty(propertyName)) {
			Object control = viewPropertyAccessor.getPropertyValue(propertyName);
			if (control != null) {
				if (log.isDebugEnabled()) 
					log.debug("Found control: " + control.getClass().getSimpleName() + 
							" for property: " + propertyName);
				bind(control, propertyName);
			}
		}
	}
}
 
Example 8
Source Project: java-technology-stack   Source File: OptionWriter.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 9
Source Project: jdal   Source File: AnnotatedElementAccessor.java    License: Apache License 2.0 6 votes vote down vote up
public static Object getValue(AnnotatedElement element, Object target) {
	if (element instanceof Field) {
		ReflectionUtils.makeAccessible((Field) element); 
		return ReflectionUtils.getField((Field) element, target);
	}
	else if (element instanceof Method) {
		Method method = (Method) element;
		String name = method.getName();
		
		if (name.startsWith("set")) {
			return PropertyAccessorFactory.forBeanPropertyAccess(target).getPropertyValue(getPropertyName(name));
		}
	}
	
	return null;
}
 
Example 10
@Override
public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) {
	Class<?> activationSpecClassToUse = this.activationSpecClass;
	if (activationSpecClassToUse == null) {
		activationSpecClassToUse = determineActivationSpecClass(adapter);
		if (activationSpecClassToUse == null) {
			throw new IllegalStateException("Property 'activationSpecClass' is required");
		}
	}

	ActivationSpec spec = (ActivationSpec) BeanUtils.instantiateClass(activationSpecClassToUse);
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(spec);
	if (this.defaultProperties != null) {
		bw.setPropertyValues(this.defaultProperties);
	}
	populateActivationSpecProperties(bw, config);
	return spec;
}
 
Example 11
Source Project: syncope   Source File: AutowiringSpringBeanJobFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    Object job = beanFactory.getBean(bundle.getJobDetail().getKey().getName());
    if (isEligibleForPropertyPopulation(job)) {
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
        MutablePropertyValues pvs = new MutablePropertyValues();
        if (this.schedulerContext != null) {
            pvs.addPropertyValues(this.schedulerContext);
        }
        pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
        pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
        if (this.ignoredUnknownProperties != null) {
            for (String propName : this.ignoredUnknownProperties) {
                if (pvs.contains(propName) && !bw.isWritableProperty(propName)) {
                    pvs.removePropertyValue(propName);
                }
            }
            bw.setPropertyValues(pvs);
        } else {
            bw.setPropertyValues(pvs, true);
        }
    }
    return job;
}
 
Example 12
Source Project: java-technology-stack   Source File: PropertyPathFactoryBean.java    License: MIT License 6 votes vote down vote up
@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...
		Assert.state(this.beanFactory != null, "No BeanFactory available");
		Assert.state(this.targetBeanName != null, "No target bean name specified");
		Object bean = this.beanFactory.getBean(this.targetBeanName);
		target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	}
	Assert.state(this.propertyPath != null, "No property path specified");
	return target.getPropertyValue(this.propertyPath);
}
 
Example 13
private void assertRetryTemplateConstruction(final RetryTemplate retryTemplate, final long timeout, final long backOff) {
  final var wrapper = PropertyAccessorFactory.forDirectFieldAccess(retryTemplate);

  assertThat(wrapper.getPropertyValue("retryPolicy")).isInstanceOf(CompositeRetryPolicy.class);
  assertThat((RetryPolicy[]) wrapper.getPropertyValue("retryPolicy.policies"))
    .hasSize(2)
    .anyMatch(policy1 -> {
      if (policy1 instanceof TimeoutRetryPolicy) {
        final var timeoutRetryPolicy = (TimeoutRetryPolicy) policy1;
        assertThat(timeoutRetryPolicy.getTimeout()).isEqualTo(timeout);
        return true;
      }
      return false;
    })
    .anyMatch(policy2 -> {
      if (policy2 instanceof SimpleRetryPolicy) {
        final var simpleRetryPolicy = (SimpleRetryPolicy) policy2;
        assertThat(simpleRetryPolicy.getMaxAttempts()).isEqualTo(Integer.MAX_VALUE);
        return true;
      }
      return false;
    });

  assertThat(wrapper.getPropertyValue("backOffPolicy")).isInstanceOf(FixedBackOffPolicy.class);
  assertThat(((FixedBackOffPolicy) wrapper.getPropertyValue("backOffPolicy")).getBackOffPeriod()).isEqualTo(backOff);
}
 
Example 14
Source Project: lams   Source File: SpringBeanJobFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the job instance, populating it with property values taken
 * from the scheduler context, job data map and trigger data map.
 */
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
	Object job = super.createJobInstance(bundle);
	if (isEligibleForPropertyPopulation(job)) {
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
		MutablePropertyValues pvs = new MutablePropertyValues();
		if (this.schedulerContext != null) {
			pvs.addPropertyValues(this.schedulerContext);
		}
		pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
		pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
		if (this.ignoredUnknownProperties != null) {
			for (String propName : this.ignoredUnknownProperties) {
				if (pvs.contains(propName) && !bw.isWritableProperty(propName)) {
					pvs.removePropertyValue(propName);
				}
			}
			bw.setPropertyValues(pvs);
		}
		else {
			bw.setPropertyValues(pvs, true);
		}
	}
	return job;
}
 
Example 15
Source Project: lams   Source File: OptionWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 16
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);
}
 
Example 17
Source Project: uima-uimafit   Source File: ResourceInitializationUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Handle Spring-initialization of resoures produced by the UIMA framework.
 */
public static Resource initResource(Resource aResource, ApplicationContext aApplicationContext) {
  AutowireCapableBeanFactory beanFactory = aApplicationContext.getAutowireCapableBeanFactory();

  if (aResource instanceof PrimitiveAnalysisEngine_impl) {
    PropertyAccessor pa = PropertyAccessorFactory.forDirectFieldAccess(aResource);

    // Access the actual AnalysisComponent and initialize it
    AnalysisComponent analysisComponent = (AnalysisComponent) pa
            .getPropertyValue("mAnalysisComponent");
    initializeBean(beanFactory, analysisComponent, aResource.getMetaData().getName());
    pa.setPropertyValue("mAnalysisComponent", analysisComponent);

    return aResource;
  } else {
    return (Resource) beanFactory.initializeBean(aResource, aResource.getMetaData().getName());
  }
}
 
Example 18
/**
 * Provide parameter values in an {@link MapSqlParameterSource} based on values from
 * the provided item.
 * Supports accessing nested maps or arrays.
 *  e.g. :map1.level1.level2
 *    or :map1.array1[10].level2
 * However it assume keys for the maps are all String.
 * @param item the item to use for parameter values
 */
@Override
public SqlParameterSource createSqlParameterSource(T item) {
  BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
  if (beanWrapper.isReadableProperty(mapPropertyName)) {
      Map<String, Object> map = (Map<String, Object>) beanWrapper.getPropertyValue(mapPropertyName);
      if (shouldFlattenMap) {
        Map<String, Object> flattenMap = new HashMap<String, Object>();
        flatten(map, flattenMap, "");
        return new MapSqlParameterSource(flattenMap);
      } else {
        return new MapSqlParameterSource(map);
      }
  }
  return new MapSqlParameterSource();
}
 
Example 19
Source Project: blog_demos   Source File: AnnotationBeanUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) {
	Set<String> excluded =  new HashSet<String>(Arrays.asList(excludedProperties));
	Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	for (Method annotationProperty : annotationProperties) {
		String propertyName = annotationProperty.getName();
		if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) {
			Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
			if (valueResolver != null && value instanceof String) {
				value = valueResolver.resolveStringValue((String) value);
			}
			bw.setPropertyValue(propertyName, value);
		}
	}
}
 
Example 20
Source Project: blog_demos   Source File: PropertyPathFactoryBean.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 21
Source Project: spring4-understanding   Source File: AnnotationBeanUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) {
	Set<String> excluded = new HashSet<String>(Arrays.asList(excludedProperties));
	Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	for (Method annotationProperty : annotationProperties) {
		String propertyName = annotationProperty.getName();
		if (!excluded.contains(propertyName) && bw.isWritableProperty(propertyName)) {
			Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
			if (valueResolver != null && value instanceof String) {
				value = valueResolver.resolveStringValue((String) value);
			}
			bw.setPropertyValue(propertyName, value);
		}
	}
}
 
Example 22
Source Project: spring4-understanding   Source File: TilesConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(ApplicationContext applicationContext,
		LocaleResolver resolver) {

	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof ApplicationContextAware) {
			((ApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO", createLocaleDefinitionDao(applicationContext, resolver));
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, resolver);
	}
}
 
Example 23
Source Project: syncope   Source File: ReportletWizardBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Serializable onApplyInternal(final ReportletWrapper modelObject) {
    if (modelObject.getImplementationEngine() == ImplementationEngine.JAVA) {
        BeanWrapper confWrapper = PropertyAccessorFactory.forBeanPropertyAccess(modelObject.getConf());
        modelObject.getSCondWrapper().forEach((fieldName, pair) -> {
            confWrapper.setPropertyValue(fieldName, SearchUtils.buildFIQL(pair.getRight(), pair.getLeft()));
        });
        ImplementationTO reportlet = ImplementationRestClient.read(
                IdRepoImplementationType.REPORTLET, modelObject.getImplementationKey());
        try {
            reportlet.setBody(MAPPER.writeValueAsString(modelObject.getConf()));
            ImplementationRestClient.update(reportlet);
        } catch (Exception e) {
            throw new WicketRuntimeException(e);
        }
    }

    ReportTO reportTO = ReportRestClient.read(report);
    if (modelObject.isNew()) {
        reportTO.getReportlets().add(modelObject.getImplementationKey());
    }

    ReportRestClient.update(reportTO);
    return modelObject;
}
 
Example 24
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);
}
 
Example 25
Source Project: spring4-understanding   Source File: TilesConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(TilesApplicationContext applicationContext,
		TilesRequestContextFactory contextFactory, LocaleResolver resolver) {
	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof TilesApplicationContextAware) {
			((TilesApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO",
					createLocaleDefinitionDao(applicationContext, contextFactory, resolver));
		}
		if (factory instanceof Refreshable) {
			((Refreshable) factory).refresh();
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, contextFactory, resolver);
	}
}
 
Example 26
@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);
	}
}
 
Example 27
Source Project: dubai   Source File: BSAbstractMultiCheckedElementTag.java    License: MIT License 5 votes vote down vote up
/**
 * Copy & Paste, 无修正.
 */
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);
}
 
Example 28
@Override
@Nullable
public org.springframework.jmx.export.metadata.ManagedResource getManagedResource(Class<?> beanClass) throws InvalidMetadataException {
	MergedAnnotation<ManagedResource> ann = MergedAnnotations.from(beanClass, SearchStrategy.EXHAUSTIVE)
			.get(ManagedResource.class).withNonMergedAttributes();
	if (!ann.isPresent()) {
		return null;
	}
	Class<?> declaringClass = (Class<?>) ann.getSource();
	Class<?> target = (declaringClass != null && !declaringClass.isInterface() ? declaringClass : beanClass);
	if (!Modifier.isPublic(target.getModifiers())) {
		throw new InvalidMetadataException("@ManagedResource class '" + target.getName() + "' must be public");
	}

	org.springframework.jmx.export.metadata.ManagedResource bean = new org.springframework.jmx.export.metadata.ManagedResource();
	Map<String, Object> map = ann.asMap();
	List<PropertyValue> list = new ArrayList<>(map.size());
	map.forEach((attrName, attrValue) -> {
		if (!"value".equals(attrName)) {
			Object value = attrValue;
			if (this.embeddedValueResolver != null && value instanceof String) {
				value = this.embeddedValueResolver.resolveStringValue((String) value);
			}
			list.add(new PropertyValue(attrName, value));
		}
	});
	PropertyAccessorFactory.forBeanPropertyAccess(bean).setPropertyValues(new MutablePropertyValues(list));
	return bean;
}
 
Example 29
@Override
public void afterPropertiesSet() throws Exception {
	if(defaultAuthenticationEntryPoint==null){
		LoginUrlAuthenticationEntryPoint entryPoint = new LoginUrlAuthenticationEntryPoint(securityConfig.getLoginUrl());
		entryPoint.setForceHttps(forceHttps);
		entryPoint.setPortMapper(new PortMapperImpl(){
			public Integer lookupHttpsPort(Integer httpPort) {
				Integer port = super.lookupHttpsPort(httpPort);
				return port==null?httpsPort:port;
			}
		});
		PropertyAccessorFactory.forDirectFieldAccess(entryPoint).setPropertyValue("redirectStrategy.contextRelative", contextRelative);
		this.defaultAuthenticationEntryPoint = entryPoint;
	}
}
 
Example 30
@Nullable
private static <T> T copyPropertiesToBean(MergedAnnotation<? extends Annotation> ann, Class<T> beanClass) {
	if (!ann.isPresent()) {
		return null;
	}
	T bean = BeanUtils.instantiateClass(beanClass);
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	bw.setPropertyValues(new MutablePropertyValues(ann.asMap()));
	return bean;
}