private void registerBeanConfigsWithRegistry(BeanDefinitionRegistry registry) { for (BeanConfiguration bc : beanConfigs.values()) { String beanName = bc.getName(); if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] Registering bean [" + beanName + "]"); if (LOG.isTraceEnabled()) { PropertyValue[] pvs = bc.getBeanDefinition().getPropertyValues().getPropertyValues(); for (PropertyValue pv : pvs) { LOG.trace( "[RuntimeConfiguration] With property [" + pv.getName() + "] set to [" + pv.getValue() + "]"); } } } if (registry.containsBeanDefinition(beanName)) { removeBeanDefinition(registry, beanName); } registry.registerBeanDefinition(beanName, bc.getBeanDefinition()); registerBeanAliases(registry, beanName); } }
private void registerBeanDefinitionsWithRegistry(BeanDefinitionRegistry registry) { for (Object key : beanDefinitions.keySet()) { BeanDefinition bd = beanDefinitions.get(key); if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] Registering bean [" + key + "]"); if (LOG.isTraceEnabled()) { PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues(); for (PropertyValue pv : pvs) { LOG.trace( "[RuntimeConfiguration] With property [" + pv.getName() + "] set to [" + pv.getValue() + "]"); } } } final String beanName = key.toString(); if (registry.containsBeanDefinition(beanName)) { removeBeanDefinition(registry, beanName); } registry.registerBeanDefinition(beanName, bd); registerBeanAliases(registry, beanName); } }
private boolean propertyStartsWithFieldMarkerPrefix(PropertyValue pv, String fieldMarkerPrefix) { String propertyName = pv.getName().indexOf(PATH_SEPARATOR) > -1 ? StringUtils.substringAfterLast(pv.getName(), ".") : pv.getName(); return propertyName.startsWith(fieldMarkerPrefix); }
@SuppressWarnings({"unchecked"}) private void parseProcessors( Element element, ParserContext parserContext, GenericBeanDefinition beanDefinition) { Element processorsElement = DomUtils.getChildElementByTagName(element, EVENT_PROCESSORS_ELEMENT); Element snapshotTriggerElement = DomUtils.getChildElementByTagName(element, SNAPSHOT_TRIGGER_ELEMENT); if (snapshotTriggerElement != null) { BeanDefinition triggerDefinition = snapshotterTriggerParser.parse(snapshotTriggerElement, parserContext); PropertyValue aggregateCache = beanDefinition.getPropertyValues().getPropertyValue("cache"); if (aggregateCache != null) { triggerDefinition.getPropertyValues().add("aggregateCache", aggregateCache.getValue()); } beanDefinition.getPropertyValues().add(SNAPSHOTTER_TRIGGER_PROPERTY, triggerDefinition); } if (processorsElement != null) { List<Object> processorsList = parserContext.getDelegate().parseListElement(processorsElement, beanDefinition); if (!processorsList.isEmpty()) { beanDefinition.getPropertyValues().add(EVENT_STREAM_DECORATORS_PROPERTY, processorsList); } } }
private void filterNestedParameterMaps(MutablePropertyValues mpvs) { for (PropertyValue pv : mpvs.getPropertyValues()) { final Object value = pv.getValue(); if (isNotCandidateForBinding(value)) { mpvs.removePropertyValue(pv); } } }
/** * Checks for structured properties. Structured properties are properties with a name containg a * "_" * * @param propertyValues */ @SuppressWarnings("unchecked") private void checkStructuredProperties(MutablePropertyValues propertyValues) { PropertyValue[] pvs = propertyValues.getPropertyValues(); for (PropertyValue propertyValue : pvs) { if (!isStructured(propertyValue)) { continue; } String propertyName = getNameOf(propertyValue); Class<?> type = bean.getPropertyType(propertyName); if (type != null) { PropertyEditor editor = findCustomEditor(type, propertyName); if (null != editor && StructuredPropertyEditor.class.isAssignableFrom(editor.getClass())) { StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) editor; List fields = new ArrayList(); fields.addAll(structuredEditor.getRequiredFields()); fields.addAll(structuredEditor.getOptionalFields()); Map<String, String> fieldValues = new HashMap<String, String>(); try { for (Object fld : fields) { String field = (String) fld; PropertyValue partialStructValue = propertyValues.getPropertyValue( propertyName + STRUCTURED_PROPERTY_SEPERATOR + field); if (partialStructValue == null && structuredEditor.getRequiredFields().contains(field)) { throw new MissingPropertyException( "Required structured property is missing [" + field + "]"); } else if (partialStructValue == null) { continue; } fieldValues.put(field, getStringValue(partialStructValue)); } try { Object value = structuredEditor.assemble(type, fieldValues); for (Object fld : fields) { String field = (String) fld; PropertyValue partialStructValue = propertyValues.getPropertyValue( propertyName + STRUCTURED_PROPERTY_SEPERATOR + field); if (null != partialStructValue) { partialStructValue.setConvertedValue(getStringValue(partialStructValue)); } } propertyValues.addPropertyValue(new PropertyValue(propertyName, value)); } catch (IllegalArgumentException iae) { LOG.warn( "Unable to parse structured date from request for date [" + propertyName + "]", iae); } } catch (InvalidPropertyException ipe) { // ignore } } } } }
/** * Check the given property values against the required fields, generating missing field errors * where appropriate. * * @param mpvs the property values to be bound (can be modified) * @see #getRequiredFields * @see #getBindingErrorProcessor * @see BindingErrorProcessor#processMissingFieldError */ 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); 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); } } } } }
private PropertyValues filterPropertyValues(PropertyValues propertyValues, String prefix) { if (prefix == null || prefix.length() == 0) return propertyValues; PropertyValue[] valueArray = propertyValues.getPropertyValues(); MutablePropertyValues newValues = new MutablePropertyValues(); for (PropertyValue propertyValue : valueArray) { String name = propertyValue.getName(); final String prefixWithDot = prefix + PREFIX_SEPERATOR; if (name.startsWith(prefixWithDot)) { name = name.substring(prefixWithDot.length(), name.length()); newValues.addPropertyValue(name, propertyValue.getValue()); } } return newValues; }
@SuppressWarnings("unchecked") private void bindCollectionAssociation(MutablePropertyValues mpvs, PropertyValue pv) { Object v = pv.getValue(); Collection collection = (Collection) bean.getPropertyValue(pv.getName()); collection.clear(); final Class associatedType = getReferencedTypeForCollection(pv.getName(), getTarget()); final boolean isArray = v != null && v.getClass().isArray(); final PropertyEditor propertyEditor = findCustomEditor(collection.getClass(), pv.getName()); if (propertyEditor == null) { if (isDomainAssociation(associatedType)) { if (isArray) { Object[] identifiers = (Object[]) v; for (Object id : identifiers) { if (id != null) { associateObjectForId(pv, id, associatedType); } } mpvs.removePropertyValue(pv); } else if (v != null && (v instanceof String)) { associateObjectForId(pv, v, associatedType); mpvs.removePropertyValue(pv); } } else if (GrailsDomainConfigurationUtil.isBasicType(associatedType)) { if (isArray) { Object[] values = (Object[]) v; List list = collection instanceof List ? (List) collection : null; for (int i = 0; i < values.length; i++) { Object value = values[i]; try { Object newValue = getTypeConverter().convertIfNecessary(value, associatedType); if (list != null) { if (i > list.size() - 1) { list.add(i, newValue); } else { list.set(i, newValue); } } else { collection.add(newValue); } } catch (TypeMismatchException e) { // ignore } } } } } }
private String getNameOf(PropertyValue propertyValue) { String name = propertyValue.getName(); if (name.indexOf(STRUCTURED_PROPERTY_SEPERATOR) == -1) { return name; } return name.substring(0, name.indexOf(STRUCTURED_PROPERTY_SEPERATOR)); }
public BeanDefinition parse(Element element, ParserContext parserContent) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(GetMentionsMessageProcessor.class.getName()); String configRef = element.getAttribute("config-ref"); if ((configRef != null) && (!StringUtils.isBlank(configRef))) { builder.addPropertyValue("moduleObject", configRef); } if ((element.getAttribute("page") != null) && (!StringUtils.isBlank(element.getAttribute("page")))) { builder.addPropertyValue("page", element.getAttribute("page")); } if ((element.getAttribute("count") != null) && (!StringUtils.isBlank(element.getAttribute("count")))) { builder.addPropertyValue("count", element.getAttribute("count")); } if ((element.getAttribute("sinceId") != null) && (!StringUtils.isBlank(element.getAttribute("sinceId")))) { builder.addPropertyValue("sinceId", element.getAttribute("sinceId")); } BeanDefinition definition = builder.getBeanDefinition(); definition.setAttribute( MuleHierarchicalBeanDefinitionParserDelegate.MULE_NO_RECURSE, Boolean.TRUE); MutablePropertyValues propertyValues = parserContent.getContainingBeanDefinition().getPropertyValues(); if (parserContent .getContainingBeanDefinition() .getBeanClassName() .equals("org.mule.config.spring.factories.PollingMessageSourceFactoryBean")) { propertyValues.addPropertyValue("messageProcessor", definition); } else { if (parserContent .getContainingBeanDefinition() .getBeanClassName() .equals("org.mule.enricher.MessageEnricher")) { propertyValues.addPropertyValue("enrichmentMessageProcessor", definition); } else { PropertyValue messageProcessors = propertyValues.getPropertyValue("messageProcessors"); if ((messageProcessors == null) || (messageProcessors.getValue() == null)) { propertyValues.addPropertyValue("messageProcessors", new ManagedList()); } List listMessageProcessors = ((List) propertyValues.getPropertyValue("messageProcessors").getValue()); listMessageProcessors.add(definition); } } return definition; }
@SuppressWarnings("unchecked") protected Map<String, Object> getPropertyMap( BeanDefinitionBuilder bean, boolean lazyInstantiation) { PropertyValue propertyValue = bean.getBeanDefinition().getPropertyValues().getPropertyValue("properties"); Map<String, Object> map = null; if (propertyValue == null) { if (lazyInstantiation) { map = new HashMap<String, Object>(); bean.addPropertyValue("properties", map); } } else { map = (Map<String, Object>) propertyValue.getValue(); } return map; }
/** * Check the given property values against the allowed fields, removing values for fields that are * not allowed. * * @param mpvs the property values to be bound (can be modified) * @see #getAllowedFields * @see #isAllowed(String) */ protected void checkAllowedFields(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName()); if (!isAllowed(field)) { mpvs.removePropertyValue(pv); getBindingResult().recordSuppressedField(field); if (logger.isDebugEnabled()) { logger.debug( "Field [" + field + "] has been removed from PropertyValues " + "and will not be bound, because it has not been found in the list of allowed fields"); } } } }
private String getStringValue(PropertyValue yearProperty) { Object value = yearProperty.getValue(); if (value == null) return null; if (value.getClass().isArray()) { return ((String[]) value)[0]; } return (String) value; }
@SuppressWarnings("unchecked") private void filterBlankValuesWhenTargetIsNullable(MutablePropertyValues mpvs) { Object target = getTarget(); Map constrainedProperties = resolveConstrainedProperties(target, domainClass); if (constrainedProperties == null) { return; } PropertyValue[] valueArray = mpvs.getPropertyValues(); for (PropertyValue propertyValue : valueArray) { if (BLANK.equals(propertyValue.getValue())) { ConstrainedProperty cp = getConstrainedPropertyForPropertyValue(constrainedProperties, propertyValue); if (shouldNullifyBlankString(propertyValue, cp)) { propertyValue.setConvertedValue(null); } } } }
/** * Auto-creates the a type if it is null and is possible to auto-create. * * @param mpvs A MutablePropertyValues instance */ protected void autoCreateIfPossible(MutablePropertyValues mpvs) { PropertyValue[] pvs = mpvs.getPropertyValues(); for (PropertyValue pv : pvs) { String propertyName = pv.getName(); if (propertyName.indexOf(PATH_SEPARATOR) > -1) { String[] propertyNames = propertyName.split("\\."); BeanWrapper currentBean = bean; for (String name : propertyNames) { Object created = autoCreatePropertyIfPossible(currentBean, name, pv.getValue()); if (created != null) { currentBean = new BeanWrapperImpl(created); } else { break; } } } else { autoCreatePropertyIfPossible(bean, propertyName, pv.getValue()); } } }
/** * This overrides the method from WebDataBinder to allow for nested checkbox handling, so property * paths such as a._b will result in the boolean b on object a getting set to false. */ @Override protected void checkFieldMarkers(MutablePropertyValues mpvs) { if (getFieldMarkerPrefix() == null) { return; } String fieldMarkerPrefix = getFieldMarkerPrefix(); PropertyValue[] pvArray = mpvs.getPropertyValues(); for (PropertyValue pv : pvArray) { // start of variation from superclass method if (propertyStartsWithFieldMarkerPrefix(pv, fieldMarkerPrefix)) { String field = stripFieldMarkerPrefix(pv.getName(), fieldMarkerPrefix); // end of variation from superclass method if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) { Class<?> fieldType = getPropertyAccessor().getPropertyType(field); mpvs.add(field, getEmptyValue(field, fieldType)); } mpvs.removePropertyValue(pv); } } }
/** * Interrogates the specified properties looking for properites that represent associations to * other classes (e.g., 'author.id'). If such a property is found, this method attempts to load * the specified instance of the association (by ID) and set it on the target object. * * @param mpvs the <code>MutablePropertyValues</code> object holding the parameters from the * request */ protected void bindAssociations(MutablePropertyValues mpvs) { for (PropertyValue pv : mpvs.getPropertyValues()) { String propertyName = pv.getName(); String propertyNameToCheck = propertyName; final int i = propertyName.indexOf('.'); if (i > -1) { propertyNameToCheck = propertyName.substring(0, i); } if (!isAllowed(propertyNameToCheck)) continue; if (propertyName.endsWith(IDENTIFIER_SUFFIX)) { propertyName = propertyName.substring(0, propertyName.length() - 3); if (!isAllowed(propertyName)) continue; if (isReadableAndPersistent(propertyName) && bean.isWritableProperty(propertyName)) { if (NULL_ASSOCIATION.equals(pv.getValue())) { bean.setPropertyValue(propertyName, null); mpvs.removePropertyValue(pv); } else { Class<?> type = getPropertyTypeForPath(propertyName); Object persisted = getPersistentInstance(type, pv.getValue()); if (persisted != null) { bean.setPropertyValue(propertyName, persisted); } } } } else { if (isReadableAndPersistent(propertyName)) { Class<?> type = getPropertyTypeForPath(propertyName); if (Collection.class.isAssignableFrom(type)) { bindCollectionAssociation(mpvs, pv); } } } } }
@SuppressWarnings("unchecked") private ConstrainedProperty getConstrainedPropertyForPropertyValue( Map constrainedProperties, PropertyValue propertyValue) { final String propertyName = propertyValue.getName(); if (propertyName.indexOf(PATH_SEPARATOR) > -1) { String[] propertyNames = propertyName.split("\\."); Object target = getTarget(); Object value = getPropertyValueForPath(target, propertyNames); if (value != null) { Map nestedConstrainedProperties = resolveConstrainedProperties(value); if (nestedConstrainedProperties != null) { return (ConstrainedProperty) nestedConstrainedProperties.get(propertyNames[propertyNames.length - 1]); } } } else { return (ConstrainedProperty) constrainedProperties.get(propertyName); } return null; }
/** * Adds the annotated classes and the mapping resources to the existing Session Factory * configuration. * * @param configurableListableBeanFactory the good ol' bean factory */ @SuppressWarnings("unchecked") public void postProcessBeanFactory( ConfigurableListableBeanFactory configurableListableBeanFactory) { if (configurableListableBeanFactory.containsBean(sessionFactoryBeanName)) { BeanDefinition sessionFactoryBeanDefinition = configurableListableBeanFactory.getBeanDefinition(sessionFactoryBeanName); MutablePropertyValues propertyValues = sessionFactoryBeanDefinition.getPropertyValues(); if (mappingResources != null) { // do we have existing resourses? PropertyValue propertyValue = propertyValues.getPropertyValue("mappingResources"); if (propertyValue == null) { propertyValue = new PropertyValue("mappingResources", new ArrayList()); propertyValues.addPropertyValue(propertyValue); } // value is expected to be a list. List existingMappingResources = (List) propertyValue.getValue(); existingMappingResources.addAll(mappingResources); } if (annotatedClasses != null) { // do we have existing resources? PropertyValue propertyValue = propertyValues.getPropertyValue("annotatedClasses"); if (propertyValue == null) { propertyValue = new PropertyValue("annotatedClasses", new ArrayList()); propertyValues.addPropertyValue(propertyValue); } // value is expected to be a list. List existingMappingResources = (List) propertyValue.getValue(); existingMappingResources.addAll(annotatedClasses); } if (configLocations != null) { PropertyValue propertyValue = propertyValues.getPropertyValue("configLocations"); if (propertyValue == null) { propertyValue = new PropertyValue("configLocations", new ArrayList()); propertyValues.addPropertyValue(propertyValue); } List existingConfigLocations = (List) propertyValue.getValue(); existingConfigLocations.addAll(configLocations); } if (hibernateProperties != null) { PropertyValue propertyValue = propertyValues.getPropertyValue("hibernateProperties"); if (propertyValue == null) { propertyValue = new PropertyValue("hibernateProperties", new Properties()); propertyValues.addPropertyValue(propertyValue); } Properties existingHibernateProperties = (Properties) propertyValue.getValue(); existingHibernateProperties.putAll(hibernateProperties); } } else { throw new NoSuchBeanDefinitionException( "No bean named [" + sessionFactoryBeanName + "] exists within the bean factory. " + "Cannot post process session factory to add Hibernate resource definitions."); } }
private boolean needRemove(String beanName, BeanDefinition beanDefinition) { if (ArrayUtils.isNotEmpty(removedBeanNames)) { for (String removedBeanName : removedBeanNames) { if (beanName.equals(removedBeanName)) { return true; } if (beanDefinition.getBeanClassName().equals(removedBeanName)) { return true; } } } if (this.removedBeanProperties != null) { Set<String[]> propertiesSet = removedBeanProperties.get(beanName); if (propertiesSet != null) { Iterator<String[]> iter = propertiesSet.iterator(); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); while (iter.hasNext()) { String[] properties = iter.next(); if (properties.length == 1) { // 先移除 propertyValues.removePropertyValue(properties[0]); // 如果需要替换,替换掉值(只支持基本属性) if (this.replaceBeanProperties != null) { String key = beanName + "@" + properties[0]; if (this.replaceBeanProperties.containsKey(key)) { propertyValues.add(properties[0], this.replaceBeanProperties.get(key)); } } } else { PropertyValue propertyValue = propertyValues.getPropertyValue(properties[0]); if (propertyValue != null) { Object nextValue = propertyValue.getValue(); // 目前只支持 二级 + 移除Map的 if (nextValue instanceof ManagedMap) { TypedStringValue typedStringValue = new TypedStringValue(properties[1]); ((ManagedMap) nextValue).remove(typedStringValue); // 如果需要替换,替换掉值(只支持基本属性) if (this.replaceBeanProperties != null) { String key = beanName + "@" + properties[0] + "@" + properties[1]; if (this.replaceBeanProperties.containsKey(key)) { ((ManagedMap) nextValue) .put(properties[1], this.replaceBeanProperties.get(key)); } } } } } } } } String className = beanDefinition.getBeanClassName(); // spring data jpa if (className.equals("com.sishuok.es.common.repository.support.SimpleBaseRepositoryFactoryBean") || className.equals( "org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean")) { PropertyValue repositoryInterfaceValue = beanDefinition.getPropertyValues().getPropertyValue("repositoryInterface"); if (repositoryInterfaceValue != null) { className = repositoryInterfaceValue.getValue().toString(); } } if (ArrayUtils.isEmpty(this.removedClassPatterns)) { return false; } if (ArrayUtils.isNotEmpty(this.includeClassPatterns)) { for (String includeClassPattern : includeClassPatterns) { if (className.matches(includeClassPattern)) { return false; } } } for (String removedClassPattern : removedClassPatterns) { if (className.matches(removedClassPattern)) { return true; } } return false; }
private String getPropertyValue(BeanDefinition beanDefinition, String propertyName) { PropertyValue propertyValue = beanDefinition.getPropertyValues().getPropertyValue(propertyName); return propertyValue != null ? (String) propertyValue.getValue() : ""; }
private boolean shouldNullifyBlankString(PropertyValue propertyValue, ConstrainedProperty cp) { return cp != null && cp.isNullable() && BLANK.equals(propertyValue.getValue()); }
private boolean isStructured(PropertyValue propertyValue) { String name = propertyValue.getName(); return name.indexOf(STRUCTURED_PROPERTY_SEPERATOR) != -1; }
private void associateObjectForId(PropertyValue pv, Object id, Class<?> associatedType) { final Object target = getTarget(); final Object obj = getPersistentInstance(associatedType, id); addAssociationToTarget(pv.getName(), target, obj); }