/** * Injects the properties from the given Map to the given object. Additionally, a bean factory can be passed in for * copying property editors inside the injector. * * @param instance bean instance to configure * @param properties * @param beanFactory */ public static void applyMapOntoInstance(Object instance, Map<String, ?> properties, AbstractBeanFactory beanFactory) { if (properties != null && !properties.isEmpty()) { BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance); beanWrapper.setAutoGrowNestedPaths(true); // configure bean wrapper (using method from Spring 2.5.6) if (beanFactory != null) { beanFactory.copyRegisteredEditorsTo(beanWrapper); } for (Iterator<?> iterator = properties.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator.next(); String propertyName = entry.getKey(); if (beanWrapper.isWritableProperty(propertyName)) { beanWrapper.setPropertyValue(propertyName, entry.getValue()); } } } }
/** * This implementation applies the passed-in job data map as bean property * values, and delegates to {@code executeInternal} afterwards. * @see #executeInternal */ @Override public final void execute(JobExecutionContext context) throws JobExecutionException { try { // Reflectively adapting to differences between Quartz 1.x and Quartz 2.0... Scheduler scheduler = (Scheduler) ReflectionUtils.invokeMethod(getSchedulerMethod, context); Map<?, ?> mergedJobDataMap = (Map<?, ?>) ReflectionUtils.invokeMethod(getMergedJobDataMapMethod, context); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValues(scheduler.getContext()); pvs.addPropertyValues(mergedJobDataMap); bw.setPropertyValues(pvs, true); } catch (SchedulerException ex) { throw new JobExecutionException(ex); } executeInternal(context); }
/** * 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); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job); if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) { MutablePropertyValues pvs = new MutablePropertyValues(); if (this.schedulerContext != null) { pvs.addPropertyValues(this.schedulerContext); } pvs.addPropertyValues(getJobDetailDataMap(bundle)); pvs.addPropertyValues(getTriggerDataMap(bundle)); 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; }
/** * 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); } } }
@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); }
/** * This follows a path (like object.childobject.value), to its end value, so it can compare the values of two * paths. * This method follows the path recursively until it reaches the end value. * * @param object object to search * @param path path of value * @return result */ private Object deepValue(final Object object, final String path) { final List<String> paths = new LinkedList<>(Arrays.asList(path.split("\\."))); final String currentPath = paths.get(0); final PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(object); Object field = accessor.getPropertyValue(currentPath); paths.remove(0); if ((field != null) && (!paths.isEmpty())) { field = deepValue(field, String.join(".", paths)); } return field; }
/** * Write the value to the existingEntity field with the name of key * * @param <T> Type of the entity * @param existingEntity The entity we are changing * @param key The key we are changing * @param value The new value */ private <T extends BaseEntity> void writeToEntity(T existingEntity, String key, Object value) { final PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(existingEntity); if (accessor.getPropertyType(key) != null) { try { if (value.getClass().equals(JSONObject.class) && ((JSONObject) value).has("_isMap") && ((JSONObject) value).get("_isMap").equals(true)) { writeArrayMapToEntity(accessor, key, (JSONObject) value); } else if (value.getClass().equals(JSONObject.class)) { writeObjectToEntity(accessor, key, (JSONObject) value); } else if (value.getClass().equals(JSONArray.class)) { writeArrayToEntity(accessor, key, (JSONArray) value); } else if (isFieldValid(accessor, key, existingEntity.getClass())) { writeValueToEntity(accessor, key, value); } } catch (JSONException e) { logger.info("[FormParse] [writeToEntity] Unable To Process JSON", e); } } }
@SuppressWarnings("unchecked") @Override public ID getId(T entity) { Class<?> domainClass = getJavaType(); while (domainClass != Object.class) { for (Field field : domainClass.getDeclaredFields()) { if (field.getAnnotation(Id.class) != null) { try { return (ID) field.get(entity); } catch (IllegalArgumentException | IllegalAccessException e) { BeanWrapper beanWrapper = PropertyAccessorFactory .forBeanPropertyAccess(entity); return (ID) beanWrapper.getPropertyValue(field.getName()); } } } domainClass = domainClass.getSuperclass(); } throw new IllegalStateException("id not found"); }
protected void initJob(TriggerFiredBundle bundle, Object job) { // The following code is copied from SpringBeanJobFactory in spring-context-support-4.2.5.RELEASE BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job); if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) { MutablePropertyValues pvs = new MutablePropertyValues(); if (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); } } }
@Around("@annotation(com.newtranx.util.mysql.fabric.WithShardKey) || @within(com.newtranx.util.mysql.fabric.WithShardKey)") public Object setShardKey(ProceedingJoinPoint pjp) throws Throwable { Method method = AspectJUtils.getMethod(pjp); String key = null; boolean force = method.getAnnotation(WithShardKey.class).force(); int i = 0; for (Parameter p : method.getParameters()) { ShardKey a = p.getAnnotation(ShardKey.class); if (a != null) { if (key != null) throw new RuntimeException("found multiple shardkey"); Object obj = pjp.getArgs()[i]; if (StringUtils.isEmpty(a.property())) key = obj.toString(); else { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj); key = bw.getPropertyValue(a.property()).toString(); } } i++; } if (key == null) throw new RuntimeException("can not find shardkey"); fabricShardKey.set(key, force); return pjp.proceed(); }
@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); } }
/** * 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); } }
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); }
@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); } }
/** * 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); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job); if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) { 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; }
@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; }
/** * 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); } } }
@Override public Object add(Object object) { SqlModel<Object> sqlModel = sqlBuilder.insertSelectiveSql(object); checkSqlModel(sqlModel); SqlParameterSource paramSource = new BeanPropertySqlParameterSource(object); KeyHolder generatedKeyHolder = new GeneratedKeyHolder(); namedPjdbcTemplate.update(sqlModel.getSql(), paramSource, generatedKeyHolder); Number num = generatedKeyHolder.getKey(); String[] primaryKeys = sqlModel.getPrimaryKeys(); if(primaryKeys != null && primaryKeys.length > 0){ BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object); beanWrapper.setPropertyValue(primaryKeys[0], num); } return object; }
/** * Copy & Paste, 无修正. */ 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); }
@Override public void fillFromEnv(List<String> env, Object target) { Map<String, String> envMap = extractEnvListToMap(env); final BeanWrapper propertyAccess = PropertyAccessorFactory.forBeanPropertyAccess(target); ReflectionUtils.doWithLocalFields(target.getClass(), f -> { final EnvironmentVariable[] annos = f.getAnnotationsByType(EnvironmentVariable.class); final Optional<String> evValue = Stream.of(annos) .map(evAnno -> envMap.get(evAnno.value())) .filter(val -> val != null) .findFirst(); if (evValue.isPresent()) { propertyAccess.setPropertyValue(f.getName(), conversionService.convert(evValue.get(), f.getType())); } }); }
public String getEntityPath(Object target) { BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(target); int i= 0; StringBuilder result = new StringBuilder(); for(String id : identity){ Object value = wrapper.getPropertyValue(id); result.append(value); if( i < identity.length -1){result.append("/");} i++; } return result.toString(); }
/** * 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); } }
/** * This implementation applies the passed-in job data map as bean property * values, and delegates to {@code executeInternal} afterwards. * @see #executeInternal */ public final void execute(JobExecutionContext context) throws JobExecutionException { try { // Reflectively adapting to differences between Quartz 1.x and Quartz 2.0... Scheduler scheduler = (Scheduler) ReflectionUtils.invokeMethod(getSchedulerMethod, context); Map<?, ?> mergedJobDataMap = (Map<?, ?>) ReflectionUtils.invokeMethod(getMergedJobDataMapMethod, context); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValues(scheduler.getContext()); pvs.addPropertyValues(mergedJobDataMap); bw.setPropertyValues(pvs, true); } catch (SchedulerException ex) { throw new JobExecutionException(ex); } executeInternal(context); }
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; }
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 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; }
protected void init(Object entity) { this.entity = entity; beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(entity); PropertyDescriptor[] descriptors = beanWrapper.getPropertyDescriptors(); if (descriptors.length > 1) { for (PropertyDescriptor descriptor : descriptors) { if (beanWrapper.isReadableProperty(descriptor.getName())) { privateFields.add(descriptor.getName()); } } } Field[] fields = BeanFields.get(entity.getClass()); if (fields != null) { for (Field field : fields) { publicFeilds.put(field.getName(), field); } } }
@Test //As we provide default in the schema for better code completion we should check if they match to the underlying pool defaults public void parseInternal_defaultPoolAttribute_matchesPoolConfiguration() throws Exception { //Arrange PoolProperties poolProperties = new PoolProperties(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-defaultPoolAttributes.xml", getClass())); //Act BeanDefinition definition = beanFactory.getBeanDefinition("test"); BeanDefinition dataSourceFactory = (BeanDefinition) definition.getPropertyValues().getPropertyValue("dataSourceFactory").getValue(); //Assert BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(poolProperties); for (PropertyValue propertyValue : dataSourceFactory.getPropertyValues().getPropertyValueList()) { assertEquals(beanWrapper.getPropertyValue(propertyValue.getName()).toString(), propertyValue.getValue()); } }
public static void main(String[] args) { Department department = new Department(); department.setName("test"); Department parent = new Department(); parent.setName("parent"); department.setParent(parent); BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(department); wrapper.setPropertyValue("name", "test1"); wrapper.setPropertyValue("parent.name", "parent1"); System.out.println(department.getName()); System.out.println(department.getParent().getName()); //======================================== Department dept = new Department(); DirectFieldAccessor accessor = new DirectFieldAccessor(dept); accessor.setPropertyValue("level", 5); System.out.println(dept.getLevel()); }
/** {@inheritDoc} */ public <T> T getPluginInstance(Class<T> pluginClass, PluginConfig pluginConfig) { T pluginInstance = beanWithNameOfType(pluginConfig.getPluginClass(), pluginClass); if (pluginInstance == null) { return null; } Map<String, String> parameters = new HashMap<String, String>(pluginConfig.getParameterMap()); BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(pluginInstance); try { wrapper.setPropertyValues(parameters); } catch (BeansException e) { error(e, "Could not set properties on report definition: %s", e.getMessage()); } return pluginInstance; }
/** * This test ensures that the Spring Bean accessor classes work properly * since our REST implementation uses bean access to update the values. */ @Test public void testBeanWrapperAccess() throws Exception { createRequisition(); Requisition r = m_repository.getRequisition(m_defaultForeignSourceName); BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(r); assertEquals("AC", wrapper.getPropertyValue("node[0].category[0].name")); assertEquals("UK", wrapper.getPropertyValue("node[0].category[1].name")); assertEquals("low", wrapper.getPropertyValue("node[0].category[2].name")); try { wrapper.getPropertyValue("node[1].category[0].name"); fail("Did not catch expected InvalidPropertyException exception"); } catch (InvalidPropertyException e) { // Expected failure } assertEquals(0, ((RequisitionCategory[])wrapper.getPropertyValue("node[1].category")).length); wrapper.setPropertyValue("node[1].categories[0]", new RequisitionCategory("Hello world")); wrapper.setPropertyValue("node[1].categories[1]", new RequisitionCategory("Hello again")); assertEquals(2, ((RequisitionCategory[])wrapper.getPropertyValue("node[1].category")).length); }
public void mergeGeolocation(final OnmsGeolocation from) { if (from == null) { return; } final BeanWrapper toBean = PropertyAccessorFactory.forBeanPropertyAccess(this); final BeanWrapper fromBean = PropertyAccessorFactory.forBeanPropertyAccess(from); final PropertyDescriptor[] pds = fromBean.getPropertyDescriptors(); for (final PropertyDescriptor pd : pds) { final String propertyName = pd.getName(); if (propertyName.equals("class")) { continue; } final Object propertyValue = fromBean.getPropertyValue(propertyName); if (propertyValue != null) { toBean.setPropertyValue(propertyName, propertyValue); } } }