org.springframework.core.CollectionFactory Java Examples

The following examples show how to use org.springframework.core.CollectionFactory. 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 File: DataObjectWrapperBase.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Populates the property on the other side of the relationship.
 *
 * @param relationship the relationship on the wrapped data object for which to populate the inverse relationship.
 * @param propertyValue the value of the property.
 */
protected void populateInverseRelationship(MetadataChild relationship, Object propertyValue) {
    if (propertyValue != null) {
        MetadataChild inverseRelationship = relationship.getInverseRelationship();
        if (inverseRelationship != null) {
            DataObjectWrapper<?> wrappedRelationship = dataObjectService.wrap(propertyValue);
            if (inverseRelationship instanceof DataObjectCollection) {
                DataObjectCollection collectionRelationship = (DataObjectCollection)inverseRelationship;
                String colRelName = inverseRelationship.getName();
                Collection<Object> collection =
                        (Collection<Object>)wrappedRelationship.getPropertyValue(colRelName);
                if (collection == null) {
                    // if the collection is null, let's instantiate an empty one
                    collection =
                            CollectionFactory.createCollection(wrappedRelationship.getPropertyType(colRelName), 1);
                    wrappedRelationship.setPropertyValue(colRelName, collection);
                }
                collection.add(getWrappedInstance());
            }
        }
    }
}
 
Example #2
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 6 votes vote down vote up
private Object readCollection(final TypeInformation<?> type, final VPackSlice source) {
	if (!source.isArray()) {
		throw new MappingException(
				String.format("Can't read collection type %s from VPack type %s!", type, source.getType()));
	}

	final TypeInformation<?> componentType = getNonNullComponentType(type);
	final Class<?> collectionType = Iterable.class.equals(type.getType()) ? Collection.class : type.getType();
	final Collection<Object> collection = CollectionFactory.createCollection(collectionType,
		componentType.getType(), source.getLength());

	final Iterator<VPackSlice> iterator = source.arrayIterator();

	while (iterator.hasNext()) {
		final VPackSlice elem = iterator.next();
		collection.add(readInternal(componentType, elem));
	}

	return collection;
}
 
Example #3
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 6 votes vote down vote up
private Object readMap(final TypeInformation<?> type, final VPackSlice source) {
	if (!source.isObject()) {
		throw new MappingException(
				String.format("Can't read map type %s from VPack type %s!", type, source.getType()));
	}

	final Class<?> keyType = getNonNullComponentType(type).getType();
	final TypeInformation<?> valueType = getNonNullMapValueType(type);
	final Map<Object, Object> map = CollectionFactory.createMap(type.getType(), keyType, source.size());

	final Iterator<Entry<String, VPackSlice>> iterator = source.objectIterator();

	while (iterator.hasNext()) {
		final Entry<String, VPackSlice> entry = iterator.next();
		if (typeMapper.isTypeKey(entry.getKey())) {
			continue;
		}

		final Object key = convertIfNecessary(entry.getKey(), keyType);
		final VPackSlice value = entry.getValue();

		map.put(key, readInternal(valueType, value));
	}

	return map;
}
 
Example #4
Source File: MapBinder.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
@Override
protected Object bindAggregate(ConfigurationPropertyName name, Bindable<?> target,
                               AggregateElementBinder elementBinder) {
    Map<Object, Object> map = CollectionFactory.createMap((target.getValue() != null)
            ? Map.class : target.getType().resolve(Object.class), 0);
    Bindable<?> resolvedTarget = resolveTarget(target);
    boolean hasDescendants = hasDescendants(name);
    for (ConfigurationPropertySource source : getContext().getSources()) {
        if (!ConfigurationPropertyName.EMPTY.equals(name)) {
            ConfigurationProperty property = source.getConfigurationProperty(name);
            if (property != null && !hasDescendants) {
                return getContext().getConverter().convert(property.getValue(),
                        target);
            }
            source = source.filter(name::isAncestorOf);
        }
        new EntryBinder(name, resolvedTarget, elementBinder).bindEntries(source, map);
    }
    return map.isEmpty() ? null : map;
}
 
Example #5
Source File: CollectionBinder.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
@Override
protected Object bindAggregate(ConfigurationPropertyName name, Bindable<?> target,
                               AggregateElementBinder elementBinder) {
    Class<?> collectionType = (target.getValue() != null) ? List.class
            : target.getType().resolve(Object.class);
    ResolvableType aggregateType = ResolvableType.forClassWithGenerics(List.class,
            target.getType().asCollection().getGenerics());
    ResolvableType elementType = target.getType().asCollection().getGeneric();
    IndexedCollectionSupplier result = new IndexedCollectionSupplier(
            () -> CollectionFactory.createCollection(collectionType,
                    elementType.resolve(), 0));
    bindIndexed(name, target, elementBinder, aggregateType, elementType, result);
    if (result.wasSupplied()) {
        return result.get();
    }
    return null;
}
 
Example #6
Source File: ObjectToCollectionConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}

	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), 1);

	if (elementDesc == null || elementDesc.isCollection()) {
		target.add(source);
	}
	else {
		Object singleElement = this.conversionService.convert(source, sourceType, elementDesc);
		target.add(singleElement);
	}
	return target;
}
 
Example #7
Source File: MappingSolrConverter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private Object readCollection(Collection<?> source, TypeInformation<?> type, Object parent) {
	Assert.notNull(type);

	Class<?> collectionType = type.getType();
	if (CollectionUtils.isEmpty(source)) {
		return source;
	}

	collectionType = Collection.class.isAssignableFrom(collectionType) ? collectionType : List.class;

	Collection<Object> items;
	if (type.getType().isArray()) {
		items = new ArrayList<Object>();
	} else {
		items = CollectionFactory.createCollection(collectionType, source.size());
	}

	TypeInformation<?> componentType = type.getComponentType();

	Iterator<?> it = source.iterator();
	while (it.hasNext()) {
		items.add(readValue(it.next(), componentType, parent));
	}

	return type.getType().isArray() ? convertItemsToArrayOfType(type, items) : items;
}
 
Example #8
Source File: ObjectToCollectionConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}

	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), 1);

	if (elementDesc == null || elementDesc.isCollection()) {
		target.add(source);
	}
	else {
		Object singleElement = this.conversionService.convert(source, sourceType, elementDesc);
		target.add(singleElement);
	}
	return target;
}
 
Example #9
Source File: ObjectToCollectionConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}

	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), 1);

	if (elementDesc == null || elementDesc.isCollection()) {
		target.add(source);
	}
	else {
		Object singleElement = this.conversionService.convert(source, sourceType, elementDesc);
		target.add(singleElement);
	}
	return target;
}
 
Example #10
Source File: ObjectToCollectionConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}

	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), 1);

	if (elementDesc == null || elementDesc.isCollection()) {
		target.add(source);
	}
	else {
		Object singleElement = this.conversionService.convert(source, sourceType, elementDesc);
		target.add(singleElement);
	}
	return target;
}
 
Example #11
Source File: MBeanClientInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Collection<?> convertDataArrayToTargetCollection(Object[] array, Class<?> collectionType, Class<?> elementType)
		throws NoSuchMethodException {

	Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType());
	Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array));
	for (int i = 0; i < array.length; i++) {
		resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
	}
	return resultColl;
}
 
Example #12
Source File: CollectionToCollectionConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	Collection<?> sourceCollection = (Collection<?>) source;

	// Shortcut if possible...
	boolean copyRequired = !targetType.getType().isInstance(source);
	if (!copyRequired && sourceCollection.isEmpty()) {
		return source;
	}
	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	if (elementDesc == null && !copyRequired) {
		return source;
	}

	// At this point, we need a collection copy in any case, even if just for finding out about element copies...
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), sourceCollection.size());

	if (elementDesc == null) {
		target.addAll(sourceCollection);
	}
	else {
		for (Object sourceElement : sourceCollection) {
			Object targetElement = this.conversionService.convert(sourceElement,
					sourceType.elementTypeDescriptor(sourceElement), elementDesc);
			target.add(targetElement);
			if (sourceElement != targetElement) {
				copyRequired = true;
			}
		}
	}

	return (copyRequired ? target : source);
}
 
Example #13
Source File: BeanWrapperImpl.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
private Object newValue(Class<?> type, String name) {
	try {
		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			// TODO - only handles 2-dimensional arrays
			if (componentType.isArray()) {
				Object array = Array.newInstance(componentType, 1);
				Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
				return array;
			}
			else {
				return Array.newInstance(componentType, 0);
			}
		}
		else if (Collection.class.isAssignableFrom(type)) {
			return CollectionFactory.createCollection(type, 16);
		}
		else if (Map.class.isAssignableFrom(type)) {
			return CollectionFactory.createMap(type, 16);
		}
		else {
			return type.newInstance();
		}
	}
	catch (Exception ex) {
		// TODO Root cause exception context is lost here... should we throw another exception type that preserves context instead?
		throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
				"Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path: " + ex);
	}
}
 
Example #14
Source File: AbstractNestablePropertyAccessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
	try {
		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			// TODO - only handles 2-dimensional arrays
			if (componentType.isArray()) {
				Object array = Array.newInstance(componentType, 1);
				Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
				return array;
			}
			else {
				return Array.newInstance(componentType, 0);
			}
		}
		else if (Collection.class.isAssignableFrom(type)) {
			TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
			return CollectionFactory.createCollection(type, (elementDesc != null ? elementDesc.getType() : null), 16);
		}
		else if (Map.class.isAssignableFrom(type)) {
			TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
			return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
		}
		else {
			return BeanUtils.instantiate(type);
		}
	}
	catch (Exception ex) {
		// TODO: Root cause exception context is lost here; just exception message preserved.
		// Should we throw another exception type that preserves context instead?
		throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
				"Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path: " + ex);
	}
}
 
Example #15
Source File: CollectionToCollectionConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	Collection<?> sourceCollection = (Collection<?>) source;

	// Shortcut if possible...
	boolean copyRequired = !targetType.getType().isInstance(source);
	if (!copyRequired && sourceCollection.isEmpty()) {
		return source;
	}
	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	if (elementDesc == null && !copyRequired) {
		return source;
	}

	// At this point, we need a collection copy in any case, even if just for finding out about element copies...
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), sourceCollection.size());

	if (elementDesc == null) {
		target.addAll(sourceCollection);
	}
	else {
		for (Object sourceElement : sourceCollection) {
			Object targetElement = this.conversionService.convert(sourceElement,
					sourceType.elementTypeDescriptor(sourceElement), elementDesc);
			target.add(targetElement);
			if (sourceElement != targetElement) {
				copyRequired = true;
			}
		}
	}

	return (copyRequired ? target : source);
}
 
Example #16
Source File: YamlPropertiesFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Template method that subclasses may override to construct the object
 * returned by this factory. The default implementation returns a
 * properties with the content of all resources.
 * <p>Invoked lazily the first time {@link #getObject()} is invoked in
 * case of a shared singleton; else, on each {@link #getObject()} call.
 * @return the object returned by this factory
 * @see #process(MatchCallback) ()
 */
protected Properties createProperties() {
	final Properties result = CollectionFactory.createStringAdaptingProperties();
	process(new MatchCallback() {
		@Override
		public void process(Properties properties, Map<String, Object> map) {
			result.putAll(properties);
		}
	});
	return result;
}
 
Example #17
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the given {@link List} into a collection of the given {@link TypeInformation}
 * .
 * @param targetType must not be {@literal null}.
 * @param sourceValue must not be {@literal null}.
 * @return the converted {@link Collection} or array, will never be {@literal null}.
 */
@Nullable
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object readCollectionOrArray(TypeInformation<?> targetType, List sourceValue) {

	Assert.notNull(targetType, "Target type must not be null");

	Class<?> collectionType = targetType.getType();

	TypeInformation<?> componentType = targetType.getComponentType() != null ? targetType.getComponentType()
			: ClassTypeInformation.OBJECT;
	Class<?> rawComponentType = componentType.getType();

	collectionType = Collection.class.isAssignableFrom(collectionType) ? collectionType : List.class;
	Collection<Object> items = targetType.getType().isArray() ? new ArrayList<>(sourceValue.size())
			: CollectionFactory.createCollection(collectionType, rawComponentType, sourceValue.size());

	if (sourceValue.isEmpty()) {
		return getPotentiallyConvertedSimpleRead(items, collectionType);
	}

	for (Object obj : sourceValue) {

		if (obj instanceof Map) {
			items.add(read(componentType, (Map) obj));
		}
		else if (obj instanceof List) {
			items.add(readCollectionOrArray(ClassTypeInformation.OBJECT, (List) obj));
		}
		else {
			items.add(getPotentiallyConvertedSimpleRead(obj, rawComponentType));
		}
	}

	return getPotentiallyConvertedSimpleRead(items, targetType.getType());
}
 
Example #18
Source File: YamlProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean process(Map<String, Object> map, MatchCallback callback) {
	Properties properties = CollectionFactory.createStringAdaptingProperties();
	properties.putAll(getFlattenedMap(map));

	if (this.documentMatchers.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Merging document (no matchers set): " + map);
		}
		callback.process(properties, map);
		return true;
	}

	MatchStatus result = MatchStatus.ABSTAIN;
	for (DocumentMatcher matcher : this.documentMatchers) {
		MatchStatus match = matcher.matches(properties);
		result = MatchStatus.getMostSpecific(match, result);
		if (match == MatchStatus.FOUND) {
			if (logger.isDebugEnabled()) {
				logger.debug("Matched document with document matcher: " + properties);
			}
			callback.process(properties, map);
			return true;
		}
	}

	if (result == MatchStatus.ABSTAIN && this.matchDefault) {
		if (logger.isDebugEnabled()) {
			logger.debug("Matched document with default matcher: " + map);
		}
		callback.process(properties, map);
		return true;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Unmatched document: " + map);
	}
	return false;
}
 
Example #19
Source File: MyResultProcessor.java    From specification-with-projection with MIT License 5 votes vote down vote up
private static Collection<Object> createCollectionFor(Collection<?> source) {

        try {
            return CollectionFactory.createCollection(source.getClass(), source.size());
        } catch (RuntimeException o_O) {
            return CollectionFactory.createApproximateCollection(source, source.size());
        }
    }
 
Example #20
Source File: AbstractNestablePropertyAccessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
	try {
		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			// TODO - only handles 2-dimensional arrays
			if (componentType.isArray()) {
				Object array = Array.newInstance(componentType, 1);
				Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
				return array;
			}
			else {
				return Array.newInstance(componentType, 0);
			}
		}
		else if (Collection.class.isAssignableFrom(type)) {
			TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
			return CollectionFactory.createCollection(type, (elementDesc != null ? elementDesc.getType() : null), 16);
		}
		else if (Map.class.isAssignableFrom(type)) {
			TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
			return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
		}
		else {
			return BeanUtils.instantiate(type);
		}
	}
	catch (Throwable ex) {
		throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
				"Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path", ex);
	}
}
 
Example #21
Source File: CollectionToCollectionConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	Collection<?> sourceCollection = (Collection<?>) source;

	// Shortcut if possible...
	boolean copyRequired = !targetType.getType().isInstance(source);
	if (!copyRequired && sourceCollection.isEmpty()) {
		return source;
	}
	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	if (elementDesc == null && !copyRequired) {
		return source;
	}

	// At this point, we need a collection copy in any case, even if just for finding out about element copies...
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), sourceCollection.size());

	if (elementDesc == null) {
		target.addAll(sourceCollection);
	}
	else {
		for (Object sourceElement : sourceCollection) {
			Object targetElement = this.conversionService.convert(sourceElement,
					sourceType.elementTypeDescriptor(sourceElement), elementDesc);
			target.add(targetElement);
			if (sourceElement != targetElement) {
				copyRequired = true;
			}
		}
	}

	return (copyRequired ? target : source);
}
 
Example #22
Source File: MBeanClientInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Collection<?> convertDataArrayToTargetCollection(Object[] array, Class<?> collectionType, Class<?> elementType)
		throws NoSuchMethodException {

	Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType());
	Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array));
	for (int i = 0; i < array.length; i++) {
		resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
	}
	return resultColl;
}
 
Example #23
Source File: WebDataBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Determine an empty value for the specified field.
 * <p>The default implementation returns:
 * <ul>
 * <li>{@code Boolean.FALSE} for boolean fields
 * <li>an empty array for array types
 * <li>Collection implementations for Collection types
 * <li>Map implementations for Map types
 * <li>else, {@code null} is used as default
 * </ul>
 * @param field the name of the field
 * @param fieldType the type of the field
 * @return the empty value (for most fields: null)
 */
protected Object getEmptyValue(String field, Class<?> fieldType) {
	if (fieldType != null) {
		try {
			if (boolean.class == fieldType || Boolean.class == fieldType) {
				// Special handling of boolean property.
				return Boolean.FALSE;
			}
			else if (fieldType.isArray()) {
				// Special handling of array property.
				return Array.newInstance(fieldType.getComponentType(), 0);
			}
			else if (Collection.class.isAssignableFrom(fieldType)) {
				return CollectionFactory.createCollection(fieldType, 0);
			}
			else if (Map.class.isAssignableFrom(fieldType)) {
				return CollectionFactory.createMap(fieldType, 0);
			}
		}
		catch (IllegalArgumentException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Failed to create default value - falling back to null: " + ex.getMessage());
			}
		}
	}
	// Default value: null.
	return null;
}
 
Example #24
Source File: MBeanClientInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Collection<?> convertDataArrayToTargetCollection(Object[] array, Class<?> collectionType, Class<?> elementType)
		throws NoSuchMethodException {

	Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType());
	Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array));
	for (int i = 0; i < array.length; i++) {
		resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
	}
	return resultColl;
}
 
Example #25
Source File: YamlProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean process(Map<String, Object> map, MatchCallback callback) {
	Properties properties = CollectionFactory.createStringAdaptingProperties();
	properties.putAll(getFlattenedMap(map));

	if (this.documentMatchers.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Merging document (no matchers set): " + map);
		}
		callback.process(properties, map);
		return true;
	}

	MatchStatus result = MatchStatus.ABSTAIN;
	for (DocumentMatcher matcher : this.documentMatchers) {
		MatchStatus match = matcher.matches(properties);
		result = MatchStatus.getMostSpecific(match, result);
		if (match == MatchStatus.FOUND) {
			if (logger.isDebugEnabled()) {
				logger.debug("Matched document with document matcher: " + properties);
			}
			callback.process(properties, map);
			return true;
		}
	}

	if (result == MatchStatus.ABSTAIN && this.matchDefault) {
		if (logger.isDebugEnabled()) {
			logger.debug("Matched document with default matcher: " + map);
		}
		callback.process(properties, map);
		return true;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Unmatched document: " + map);
	}
	return false;
}
 
Example #26
Source File: AbstractNestablePropertyAccessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Object newValue(Class<?> type, @Nullable TypeDescriptor desc, String name) {
	try {
		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			// TODO - only handles 2-dimensional arrays
			if (componentType.isArray()) {
				Object array = Array.newInstance(componentType, 1);
				Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
				return array;
			}
			else {
				return Array.newInstance(componentType, 0);
			}
		}
		else if (Collection.class.isAssignableFrom(type)) {
			TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
			return CollectionFactory.createCollection(type, (elementDesc != null ? elementDesc.getType() : null), 16);
		}
		else if (Map.class.isAssignableFrom(type)) {
			TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
			return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
		}
		else {
			Constructor<?> ctor = type.getDeclaredConstructor();
			if (Modifier.isPrivate(ctor.getModifiers())) {
				throw new IllegalAccessException("Auto-growing not allowed with private constructor: " + ctor);
			}
			return BeanUtils.instantiateClass(ctor);
		}
	}
	catch (Throwable ex) {
		throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
				"Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path", ex);
	}
}
 
Example #27
Source File: WebDataBinder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine an empty value for the specified field.
 * <p>The default implementation returns:
 * <ul>
 * <li>{@code Boolean.FALSE} for boolean fields
 * <li>an empty array for array types
 * <li>Collection implementations for Collection types
 * <li>Map implementations for Map types
 * <li>else, {@code null} is used as default
 * </ul>
 * @param fieldType the type of the field
 * @return the empty value (for most fields: {@code null})
 * @since 5.0
 */
@Nullable
public Object getEmptyValue(Class<?> fieldType) {
	try {
		if (boolean.class == fieldType || Boolean.class == fieldType) {
			// Special handling of boolean property.
			return Boolean.FALSE;
		}
		else if (fieldType.isArray()) {
			// Special handling of array property.
			return Array.newInstance(fieldType.getComponentType(), 0);
		}
		else if (Collection.class.isAssignableFrom(fieldType)) {
			return CollectionFactory.createCollection(fieldType, 0);
		}
		else if (Map.class.isAssignableFrom(fieldType)) {
			return CollectionFactory.createMap(fieldType, 0);
		}
	}
	catch (IllegalArgumentException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("Failed to create default value - falling back to null: " + ex.getMessage());
		}
	}
	// Default value: null.
	return null;
}
 
Example #28
Source File: CollectionToCollectionConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (source == null) {
		return null;
	}
	Collection<?> sourceCollection = (Collection<?>) source;

	// Shortcut if possible...
	boolean copyRequired = !targetType.getType().isInstance(source);
	if (!copyRequired && sourceCollection.isEmpty()) {
		return source;
	}
	TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();
	if (elementDesc == null && !copyRequired) {
		return source;
	}

	// At this point, we need a collection copy in any case, even if just for finding out about element copies...
	Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),
			(elementDesc != null ? elementDesc.getType() : null), sourceCollection.size());

	if (elementDesc == null) {
		target.addAll(sourceCollection);
	}
	else {
		for (Object sourceElement : sourceCollection) {
			Object targetElement = this.conversionService.convert(sourceElement,
					sourceType.elementTypeDescriptor(sourceElement), elementDesc);
			target.add(targetElement);
			if (sourceElement != targetElement) {
				copyRequired = true;
			}
		}
	}

	return (copyRequired ? target : source);
}
 
Example #29
Source File: MBeanClientInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Collection<?> convertDataArrayToTargetCollection(Object[] array, Class<?> collectionType, Class<?> elementType)
		throws NoSuchMethodException {

	Method fromMethod = elementType.getMethod("from", array.getClass().getComponentType());
	Collection<Object> resultColl = CollectionFactory.createCollection(collectionType, Array.getLength(array));
	for (int i = 0; i < array.length; i++) {
		resultColl.add(ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
	}
	return resultColl;
}
 
Example #30
Source File: WebDataBinder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Determine an empty value for the specified field.
 * <p>The default implementation returns:
 * <ul>
 * <li>{@code Boolean.FALSE} for boolean fields
 * <li>an empty array for array types
 * <li>Collection implementations for Collection types
 * <li>Map implementations for Map types
 * <li>else, {@code null} is used as default
 * </ul>
 * @param fieldType the type of the field
 * @return the empty value (for most fields: {@code null})
 * @since 5.0
 */
@Nullable
public Object getEmptyValue(Class<?> fieldType) {
	try {
		if (boolean.class == fieldType || Boolean.class == fieldType) {
			// Special handling of boolean property.
			return Boolean.FALSE;
		}
		else if (fieldType.isArray()) {
			// Special handling of array property.
			return Array.newInstance(fieldType.getComponentType(), 0);
		}
		else if (Collection.class.isAssignableFrom(fieldType)) {
			return CollectionFactory.createCollection(fieldType, 0);
		}
		else if (Map.class.isAssignableFrom(fieldType)) {
			return CollectionFactory.createMap(fieldType, 0);
		}
	}
	catch (IllegalArgumentException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("Failed to create default value - falling back to null: " + ex.getMessage());
		}
	}
	// Default value: null.
	return null;
}