/** * Render the home page with the specified template. */ protected void renderHome(Map<String, Object> model) { InitializrMetadata metadata = metadataProvider.get(); model.put("serviceUrl", generateAppUrl()); BeanWrapperImpl wrapper = new BeanWrapperImpl(metadata); for (PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) { if ("types".equals(descriptor.getName())) { model.put("types", removeTypes(metadata.getTypes())); } else { model.put(descriptor.getName(), wrapper.getPropertyValue(descriptor.getName())); } } }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field); Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch); boolean result = false; if(fieldValue != null) { //Passwords are kept as char arrays, other values mostly as Strings if(fieldValue instanceof char[]) result = Arrays.equals((char[])fieldValue, (char[])fieldMatchValue); else result = fieldValue.equals(fieldMatchValue); } else result = fieldMatchValue == null; return result; }
@Override public void afterPropertiesSet() throws Exception { BeanWrapper bw = new BeanWrapperImpl(ThreadPoolTaskExecutor.class); determinePoolSizeRange(bw); if (this.queueCapacity != null) { bw.setPropertyValue("queueCapacity", this.queueCapacity); } if (this.keepAliveSeconds != null) { bw.setPropertyValue("keepAliveSeconds", this.keepAliveSeconds); } if (this.rejectedExecutionHandler != null) { bw.setPropertyValue("rejectedExecutionHandler", this.rejectedExecutionHandler); } if (this.beanName != null) { bw.setPropertyValue("threadNamePrefix", this.beanName + "-"); } this.target = (TaskExecutor) bw.getWrappedInstance(); if (this.target instanceof InitializingBean) { ((InitializingBean) this.target).afterPropertiesSet(); } }
@Override public Object configureBean(Object existingBean, String beanName) throws BeansException { markBeanAsCreated(beanName); BeanDefinition mbd = getMergedBeanDefinition(beanName); RootBeanDefinition bd = null; if (mbd instanceof RootBeanDefinition) { RootBeanDefinition rbd = (RootBeanDefinition) mbd; bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition()); } if (!mbd.isPrototype()) { if (bd == null) { bd = new RootBeanDefinition(mbd); } bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader()); } BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); populateBean(beanName, bd, bw); return initializeBean(beanName, existingBean, bd); }
@Override public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { // Use non-singleton bean definition, to avoid registering bean as dependent bean. final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) { return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance(); } else { Object bean; final BeanFactory parent = this; if (System.getSecurityManager() != null) { bean = AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return getInstantiationStrategy().instantiate(bd, null, parent); } }, getAccessControlContext()); } else { bean = getInstantiationStrategy().instantiate(bd, null, parent); } populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean)); return bean; } }
/** * Instantiate the given bean using its default constructor. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @return BeanWrapper for the new instance */ protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { try { Object beanInstance; final BeanFactory parent = this; if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { return getInstantiationStrategy().instantiate(mbd, beanName, parent); } }, getAccessControlContext()); } else { beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); } BeanWrapper bw = new BeanWrapperImpl(beanInstance); initBeanWrapper(bw); return bw; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } }
protected AbstractBeanDefinition createBeanDefinition() { AbstractBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(this.clazz); if (!CollectionUtils.isEmpty(this.constructorArgs)) { ConstructorArgumentValues cav = new ConstructorArgumentValues(); for (Object constructorArg : this.constructorArgs) { cav.addGenericArgumentValue(constructorArg); } bd.setConstructorArgumentValues(cav); } if (this.parentName != null) { bd.setParentName(this.parentName); } this.definitionWrapper = new BeanWrapperImpl(bd); return bd; }
@Test public void testComplexObject() { ValueBean bean = new ValueBean(); BeanWrapper bw = new BeanWrapperImpl(bean); Integer value = new Integer(1); bw.setPropertyValue("value", value); assertEquals("value not set correctly", bean.getValue(), value); value = new Integer(2); bw.setPropertyValue("value", value.toString()); assertEquals("value not converted", bean.getValue(), value); bw.setPropertyValue("value", null); assertNull("value not null", bean.getValue()); bw.setPropertyValue("value", ""); assertNull("value not converted to null", bean.getValue()); }
@Test public void testComplexObject() { TestBean tb = new TestBean(); String newName = "Rod"; String tbString = "Kerry_34"; BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(ITestBean.class, new TestBeanEditor()); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("age", new Integer(55))); pvs.addPropertyValue(new PropertyValue("name", newName)); pvs.addPropertyValue(new PropertyValue("touchy", "valid")); pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); assertTrue("spouse is non-null", tb.getSpouse() != null); assertTrue("spouse name is Kerry and age is 34", tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34); }
@Test public void testCustomEditorForSingleProperty() { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); bw.setPropertyValue("name", "value"); bw.setPropertyValue("touchy", "value"); assertEquals("prefixvalue", bw.getPropertyValue("name")); assertEquals("prefixvalue", tb.getName()); assertEquals("value", bw.getPropertyValue("touchy")); assertEquals("value", tb.getTouchy()); }
@Test public void testCustomEditorForSingleNestedProperty() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, "spouse.name", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); bw.setPropertyValue("spouse.name", "value"); bw.setPropertyValue("touchy", "value"); assertEquals("prefixvalue", bw.getPropertyValue("spouse.name")); assertEquals("prefixvalue", tb.getSpouse().getName()); assertEquals("value", bw.getPropertyValue("touchy")); assertEquals("value", tb.getTouchy()); }
private static Map<String, Object> convert(Object value, ConversionService conversionService) { BeanWrapper bean = new BeanWrapperImpl(value); PropertyDescriptor[] properties = bean.getPropertyDescriptors(); Map<String, Object> convertedValue = new HashMap<>(properties.length); for (int i = 0; i < properties.length; i++) { String name = properties[i].getName(); Object propertyValue = bean.getPropertyValue(name); if (propertyValue != null && conversionService.canConvert(propertyValue.getClass(), String.class)) { TypeDescriptor source = bean.getPropertyTypeDescriptor(name); String convertedPropertyValue = (String) conversionService.convert(propertyValue, source, TYPE_STRING); convertedValue.put(name, convertedPropertyValue); } } return convertedValue; }
@Test public void testCharacterEditor() { CharBean cb = new CharBean(); BeanWrapper bw = new BeanWrapperImpl(cb); bw.setPropertyValue("myChar", new Character('c')); assertEquals('c', cb.getMyChar()); bw.setPropertyValue("myChar", "c"); assertEquals('c', cb.getMyChar()); bw.setPropertyValue("myChar", "\u0041"); assertEquals('A', cb.getMyChar()); bw.setPropertyValue("myChar", "\\u0022"); assertEquals('"', cb.getMyChar()); CharacterEditor editor = new CharacterEditor(false); editor.setAsText("M"); assertEquals("M", editor.getAsText()); }
@Test public void testCharacterEditorWithAllowEmpty() { CharBean cb = new CharBean(); BeanWrapper bw = new BeanWrapperImpl(cb); bw.registerCustomEditor(Character.class, new CharacterEditor(true)); bw.setPropertyValue("myCharacter", new Character('c')); assertEquals(new Character('c'), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", "c"); assertEquals(new Character('c'), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", "\u0041"); assertEquals(new Character('A'), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", " "); assertEquals(new Character(' '), cb.getMyCharacter()); bw.setPropertyValue("myCharacter", ""); assertNull(cb.getMyCharacter()); }
@Test public void testIndexedPropertiesWithListPropertyEditor() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { List<TestBean> result = new ArrayList<TestBean>(); result.add(new TestBean("list" + text, 99)); setValue(result); } }); bw.setPropertyValue("list", "1"); assertEquals("list1", ((TestBean) bean.getList().get(0)).getName()); bw.setPropertyValue("list[0]", "test"); assertEquals("test", bean.getList().get(0)); }
@Test public void testConversionToOldCollections() throws PropertyVetoException { OldCollectionsBean tb = new OldCollectionsBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(Vector.class, new CustomCollectionEditor(Vector.class)); bw.registerCustomEditor(Hashtable.class, new CustomMapEditor(Hashtable.class)); bw.setPropertyValue("vector", new String[] {"a", "b"}); assertEquals(2, tb.getVector().size()); assertEquals("a", tb.getVector().get(0)); assertEquals("b", tb.getVector().get(1)); bw.setPropertyValue("hashtable", Collections.singletonMap("foo", "bar")); assertEquals(1, tb.getHashtable().size()); assertEquals("bar", tb.getHashtable().get("foo")); }
public Object getValue(Object target) { BeanWrapper bw = new BeanWrapperImpl(target); Object object = bw.getPropertyValue(field.getName()); if(object == null) return null; boolean isEnum = object.getClass().isEnum(); if (object.getClass().isEnum() && IEnumMessage.class.isAssignableFrom(object.getClass())) { return ((IEnumMessage) object).getValue(); } if (object instanceof DateTime) { DateTime dateTime = (DateTime) object; return dateTime.toString("yyyy-MM-dd HH:mm:ss"); } return object; }
@Test public void testBeanWrapperCreatesNewNestedMaps() throws Exception { TargetWithNestedMap target = new TargetWithNestedMap(); BeanWrapperImpl wrapper = new BeanWrapperImpl(target); wrapper.setAutoGrowNestedPaths(true); // For a nested map, you only have to get an element of it for it to be created wrapper.getPropertyValue("nested[foo]"); // To decide what type to create for nested[foo] we need to look ahead and see // what the user is trying to bind it to, e.g. if nested[foo][bar] then it's a map wrapper.setPropertyValue("nested[foo]", new LinkedHashMap<String, Object>()); // But it might equally well be a collection, if nested[foo][0] wrapper.setPropertyValue("nested[foo]", new ArrayList<Object>()); // Then it would have to be actually bound to get the list to auto-grow wrapper.setPropertyValue("nested[foo][0]", "bar"); assertThat(wrapper.getPropertyValue("nested[foo][0]")).isNotNull(); }
/** * Modify the property values so that period separated property paths are valid for * map keys. Also creates new maps for properties of map type that are null (assuming * all maps are potentially nested). The standard bracket {@code[...]} dereferencing * is also accepted. * @param propertyValues the property values * @param target the target object * @return modified property values */ private MutablePropertyValues modifyProperties(MutablePropertyValues propertyValues, Object target) { propertyValues = getPropertyValuesForNamePrefix(propertyValues); if (target instanceof MapHolder) { propertyValues = addMapPrefix(propertyValues); } BeanWrapper wrapper = new BeanWrapperImpl(target); wrapper.setConversionService( new RelaxedConversionService(getConversionService())); wrapper.setAutoGrowNestedPaths(true); List<PropertyValue> sortedValues = new ArrayList<PropertyValue>(); Set<String> modifiedNames = new HashSet<String>(); List<String> sortedNames = getSortedPropertyNames(propertyValues); for (String name : sortedNames) { PropertyValue propertyValue = propertyValues.getPropertyValue(name); PropertyValue modifiedProperty = modifyProperty(wrapper, propertyValue); if (modifiedNames.add(modifiedProperty.getName())) { sortedValues.add(modifiedProperty); } } return new MutablePropertyValues(sortedValues); }
private PrismSchema generateConnectorConfigurationSchema(ConnectorStruct struct) { Class<? extends ConnectorInstance> connectorClass = struct.connectorClass; PropertyDescriptor connectorConfigurationProp = UcfUtil.findAnnotatedProperty(connectorClass, ManagedConnectorConfiguration.class); PrismSchema connectorSchema = new PrismSchemaImpl(struct.connectorObject.getNamespace(), prismContext); // Create configuration type - the type used by the "configuration" element PrismContainerDefinitionImpl<?> configurationContainerDef = ((PrismSchemaImpl) connectorSchema).createPropertyContainerDefinition( ResourceType.F_CONNECTOR_CONFIGURATION.getLocalPart(), SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_TYPE_LOCAL_NAME); Class<?> configurationClass = connectorConfigurationProp.getPropertyType(); BeanWrapper configurationClassBean = new BeanWrapperImpl(configurationClass); for (PropertyDescriptor prop: configurationClassBean.getPropertyDescriptors()) { if (!UcfUtil.hasAnnotation(prop, ConfigurationProperty.class)) { continue; } ItemDefinition<?> itemDef = createPropertyDefinition(configurationContainerDef, prop); LOGGER.trace("Configuration item definition for {}: {}", prop.getName(), itemDef); } return connectorSchema; }
private void applyConfigurationToConfigurationClass(PrismContainerValue<?> configurationContainer) throws ConfigurationException { BeanWrapper connectorBean = new BeanWrapperImpl(this); PropertyDescriptor connectorConfigurationProp = UcfUtil.findAnnotatedProperty(connectorBean, ManagedConnectorConfiguration.class); if (connectorConfigurationProp == null) { return; } Class<?> configurationClass = connectorConfigurationProp.getPropertyType(); Object configurationObject; try { configurationObject = configurationClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ConfigurationException("Cannot instantiate configuration "+configurationClass); } BeanWrapper configurationClassBean = new BeanWrapperImpl(configurationObject); for (Item<?, ?> configurationItem: configurationContainer.getItems()) { if (! (configurationItem instanceof PrismProperty<?>)) { throw new ConfigurationException("Only properties are supported for now"); } PrismProperty<?> configurationProperty = (PrismProperty<?>)configurationItem; Object realValue = configurationProperty.getRealValue(); configurationClassBean.setPropertyValue(configurationProperty.getElementName().getLocalPart(), realValue); } connectorBean.setPropertyValue(connectorConfigurationProp.getName(), configurationObject); }
public static Field findFieldWithAnnotation(Class<?> domainObjClass, Class<? extends Annotation> annotationClass) throws SecurityException, BeansException { BeanWrapper wrapper = new BeanWrapperImpl(domainObjClass); PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors(); for (PropertyDescriptor descriptor : descriptors) { Field candidate = getField(domainObjClass, descriptor.getName()); if (candidate != null) { if (candidate.getAnnotation(annotationClass) != null) { return candidate; } } } for (Field field : getAllFields(domainObjClass)) { if (field.getAnnotation(annotationClass) != null) { return field; } } return null; }
public static Object getFieldWithAnnotation(Object domainObj, Class<? extends Annotation> annotationClass) throws SecurityException, BeansException { Object value = null; Field field = findFieldWithAnnotation(domainObj, annotationClass); if (field != null && field.getAnnotation(annotationClass) != null) { try { PropertyDescriptor descriptor = org.springframework.beans.BeanUtils.getPropertyDescriptor(domainObj.getClass(), field.getName()); if (descriptor != null) { BeanWrapper wrapper = new BeanWrapperImpl(domainObj); value = wrapper.getPropertyValue(field.getName()); } else { value = ReflectionUtils.getField(field, domainObj); } return value; } catch (IllegalArgumentException iae) {} } return value; }
public void persist(Object entity) { // ReflectionUtils. BeanWrapper instance = new BeanWrapperImpl(entity); try { Object obj = instance.getPropertyValue("identification"); if (obj == null) { instance.setPropertyValue("identification", new Identification()); obj = instance.getPropertyValue("identification"); } if (obj instanceof Identification) { Identification ident = (Identification) obj; ident.setCreated(new Date()); } } catch (Exception e) { log.warn(e.getMessage()); } em.persist(entity); }
@Override public void registerCustomEditors(PropertyEditorRegistry registry) { if (!(registry instanceof BeanWrapperImpl)) { return; } BeanWrapperImpl beanWrapper = (BeanWrapperImpl) registry; Class<?> clazz = null; try { clazz = Class.forName(SchedulerFactoryBean, true, registry.getClass().getClassLoader()); } catch (Throwable e) { LOGGER.info("cannot find class for " + SchedulerFactoryBean, e); } if (null == clazz || null == beanWrapper.getWrappedClass() || !clazz.isAssignableFrom(beanWrapper.getWrappedClass())) { return; } registry.registerCustomEditor(Object.class, "triggers", new QuartzSchedulerBeanTargetEditor(context)); }
private static Object convertProperty(BeanWrapper parentBean, String property, ConversionService conversionService, Map<String, Object> parentValue) { TypeDescriptor source = parentBean.getPropertyTypeDescriptor(property); Object propertyValue = parentBean.getPropertyValue(property); int dotIndex = property.indexOf('.'); if (dotIndex > 0) { String baseProperty = property.substring(0, dotIndex); String childProperty = property.substring(dotIndex + 1); Map<String, Object> childValue = getChildValue(parentValue, baseProperty, childProperty); BeanWrapper childBean = new BeanWrapperImpl(parentBean.getPropertyValue(baseProperty)); Object convertedProperty = convertProperty(childBean, childProperty, conversionService, childValue); childValue.put(childProperty, convertedProperty); return childValue; } else { String convertedPropertyValue = (String) conversionService.convert(propertyValue, source, TYPE_STRING); return convertedPropertyValue; } }
@SuppressWarnings("unchecked") public static <E> E handle(Object obj,Class<E> clz,Map<String,Strategy<?>> targetAndStrategy) throws Exception{ E bean = null; if(clz.isAssignableFrom(obj.getClass())){ bean = (E)obj; }else{ throw new Exception("Object obj is not an instance of Class clz"); } BeanWrapper bw = new BeanWrapperImpl(bean); Set<String> keySet = targetAndStrategy.keySet(); for (String key : keySet) { @SuppressWarnings("rawtypes") Strategy s = targetAndStrategy.get(key); Object oldVal = bw.getPropertyValue(key); Object handledValue = s.handle(oldVal); bw.setPropertyValue(key, handledValue); } return bean; }
/** * Initializes this instance with the defaults defined in the specified * {@link InitializrMetadata}. */ public void initialize(InitializrMetadata metadata) { BeanWrapperImpl bean = new BeanWrapperImpl(this); metadata.defaults().forEach((key, value) -> { if (bean.isWritableProperty(key)) { // We want to be able to infer a package name if none has been // explicitly set if (!key.equals("packageName")) { bean.setPropertyValue(key, value); } } }); }
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); }
@Override protected Object loadRepresentation(final InputStream in) throws IOException { final Properties props = (Properties) super.loadRepresentation(in); final Object bean = instantiateBean(); new BeanWrapperImpl(bean).setPropertyValues(new MutablePropertyValues(props), false); return bean; }