Java Code Examples for org.springframework.core.CollectionFactory#createMap()

The following examples show how to use org.springframework.core.CollectionFactory#createMap() . 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: 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 2
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 3
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;
}
 
Example 4
Source File: AbstractNestablePropertyAccessor.java    From spring-analysis-note 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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: MapBinder.java    From spring-cloud-gray with Apache License 2.0 4 votes vote down vote up
private Map<Object, Object> createNewMap(Class<?> mapClass, Map<Object, Object> map) {
    Map<Object, Object> result = CollectionFactory.createMap(mapClass, map.size());
    result.putAll(map);
    return result;
}
 
Example 12
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the given {@link Map} into a {@link Map}. will recursively resolve nested
 * {@link Map}s as well.
 * @param type the {@link Map} {@link TypeInformation} to be used to unmarshal this
 * {@link Map}.
 * @param sourceMap must not be {@literal null}
 * @return the converted {@link Map}.
 */
protected Map<Object, Object> readMap(TypeInformation<?> type, Map<String, Object> sourceMap) {

	Assert.notNull(sourceMap, "Source map must not be null");

	Class<?> mapType = this.typeMapper.readType(sourceMap, type).getType();

	TypeInformation<?> keyType = type.getComponentType();
	TypeInformation<?> valueType = type.getMapValueType();

	Class<?> rawKeyType = keyType != null ? keyType.getType() : null;
	Class<?> rawValueType = valueType != null ? valueType.getType() : null;

	Map<Object, Object> map = CollectionFactory.createMap(mapType, rawKeyType, sourceMap.keySet().size());

	for (Entry<String, Object> entry : sourceMap.entrySet()) {

		if (this.typeMapper.isTypeKey(entry.getKey())) {
			continue;
		}

		Object key = entry.getKey();

		if (rawKeyType != null && !rawKeyType.isAssignableFrom(key.getClass())) {
			key = this.conversionService.convert(key, rawKeyType);
		}

		Object value = entry.getValue();
		TypeInformation<?> defaultedValueType = valueType != null ? valueType : ClassTypeInformation.OBJECT;

		if (value instanceof Map) {
			map.put(key, read(defaultedValueType, (Map) value));
		}
		else if (value instanceof List) {
			map.put(key,
					readCollectionOrArray(valueType != null ? valueType : ClassTypeInformation.LIST, (List) value));
		}
		else {
			map.put(key, getPotentiallyConvertedSimpleRead(value, rawValueType));
		}
	}

	return map;
}
 
Example 13
Source File: DataBinderMappingJackson2HttpMessageConverter.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Before call to {@link ObjectMapper#readValue(java.io.InputStream, Class)}
 * creates a {@link ServletRequestDataBinder} and put it to current Thread
 * in order to be used by the {@link DataBinderDeserializer}.
 * <p/>
 * Ref: <a href=
 * "http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use">When
 * to use Thread Local?</a>
 * 
 * @param javaType
 * @param inputMessage
 * @return
 */
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
    try {
        Object target = null;
        String objectName = null;

        // CRear el DataBinder con un target object en funcion del javaType,
        // ponerlo en el thread local
        Class<?> clazz = javaType.getRawClass();
        if (Collection.class.isAssignableFrom(clazz)) {
            Class<?> contentClazz = javaType.getContentType().getRawClass();
            target = new DataBinderList<Object>(contentClazz);
            objectName = "list";
        }
        else if (Map.class.isAssignableFrom(clazz)) {
            // TODO Class<?> contentClazz =
            // javaType.getContentType().getRawClass();
            target = CollectionFactory.createMap(clazz, 0);
            objectName = "map";
        }
        else {
            target = BeanUtils.instantiateClass(clazz);
            objectName = "bean";
        }

        WebDataBinder binder = new ServletRequestDataBinder(target,
                objectName);
        binder.setConversionService(this.conversionService);
        binder.setAutoGrowNestedPaths(true);
        binder.setValidator(validator);

        ThreadLocalUtil.setThreadVariable(
                BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"),
                binder);

        Object value = getObjectMapper().readValue(inputMessage.getBody(),
                javaType);

        return value;
    }
    catch (IOException ex) {
        throw new HttpMessageNotReadableException(
                "Could not read JSON: ".concat(ex.getMessage()), ex);
    }
}
 
Example 14
Source File: MapKeyValueAdapter.java    From spring-data-keyvalue with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link MapKeyValueAdapter} using the given {@link Map} as backing store.
 *
 * @param mapType must not be {@literal null}.
 */
@SuppressWarnings("rawtypes")
public MapKeyValueAdapter(Class<? extends Map> mapType) {
	this(CollectionFactory.createMap(mapType, 100), mapType);
}