Java Code Examples for org.springframework.data.util.TypeInformation#getType()

The following examples show how to use org.springframework.data.util.TypeInformation#getType() . 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: DefaultNeo4jConverter.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Object readValueForProperty(@Nullable Value value, TypeInformation<?> type) {

	boolean valueIsLiteralNullOrNullValue = value == null || value == Values.NULL;

	try {
		Class<?> rawType = type.getType();

		if (!valueIsLiteralNullOrNullValue && isCollection(type)) {
			Collection<Object> target = createCollection(rawType, type.getComponentType().getType(), value.size());
			value.values().forEach(
				element -> target.add(conversionService.convert(element, type.getComponentType().getType())));
			return target;
		}

		return conversionService.convert(valueIsLiteralNullOrNullValue ? null : value, rawType);
	} catch (Exception e) {
		String msg = String.format("Could not convert %s into %s", value, type.toString());
		throw new TypeMismatchDataAccessException(msg, e);
	}
}
 
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: BasicKeyValuePersistentEntity.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
/**
 * @param information must not be {@literal null}.
 * @param fallbackKeySpaceResolver can be {@literal null}.
 */
public BasicKeyValuePersistentEntity(TypeInformation<T> information,
		@Nullable KeySpaceResolver fallbackKeySpaceResolver) {

	super(information);

	Class<T> type = information.getType();
	String keySpace = AnnotationBasedKeySpaceResolver.INSTANCE.resolveKeySpace(type);

	if (StringUtils.hasText(keySpace)) {

		this.keyspace = keySpace;
		this.keyspaceExpression = detectExpression(keySpace);
	} else {

		this.keyspace = resolveKeyspace(fallbackKeySpaceResolver, type);
		this.keyspaceExpression = null;
	}
}
 
Example 4
Source File: AbstractResolver.java    From spring-data with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object proxy(
	final String id,
	final TypeInformation<?> type,
	final A annotation,
	final ResolverCallback<A> callback) {
	final ProxyInterceptor interceptor = new ProxyInterceptor(id, type, annotation, callback, conversionService);
	if (type.getType().isInterface()) {
		final ProxyFactory proxyFactory = new ProxyFactory(new Class<?>[] { type.getType() });
		for (final Class<?> interf : type.getType().getInterfaces()) {
			proxyFactory.addInterface(interf);
		}
		proxyFactory.addInterface(LazyLoadingProxy.class);
		proxyFactory.addAdvice(interceptor);
		return proxyFactory.getProxy();
	} else {
		final Factory factory = (Factory) objenesis.newInstance(enhancedTypeFor(type.getType()));
		factory.setCallbacks(new Callback[] { interceptor });
		return factory;
	}
}
 
Example 5
Source File: MappingSolrConverter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <S extends Object> S read(TypeInformation<S> targetTypeInformation, Map<String, ?> source) {
	if (source == null) {
		return null;
	}
	Assert.notNull(targetTypeInformation);
	Class<S> rawType = targetTypeInformation.getType();

	// in case there's a custom conversion for the document
	if (hasCustomReadTarget(source.getClass(), rawType)) {
		return convert(source, rawType);
	}

	SolrPersistentEntity<S> entity = (SolrPersistentEntity<S>) mappingContext.getPersistentEntity(rawType);
	return read(entity, source, null);
}
 
Example 6
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Nullable
@SuppressWarnings("unchecked")
private <T> T readValue(Object value, TypeInformation<?> type) {

	Class<?> rawType = type.getType();

	if (this.conversions.hasCustomReadTarget(value.getClass(), rawType)) {
		return (T) this.conversionService.convert(value, rawType);
	}
	else if (value instanceof List) {
		return (T) readCollectionOrArray(type, (List) value);
	}
	else if (value instanceof Map) {
		return (T) read(type, (Map) value);
	}
	else {
		return (T) getPotentiallyConvertedSimpleRead(value, rawType);
	}
}
 
Example 7
Source File: MappingCrateConverter.java    From spring-data-crate with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to read the value based on the value type.
 *
 * @param value the value to convert.
 * @param type the type information.
 * @param parent the optional parent.
 * @param <R> the target type.
 * @return the converted object.
 */
@SuppressWarnings("unchecked")
private <R> R readValue(Object value, TypeInformation<?> type, Object parent) {
 
 Class<?> rawType = type.getType();
 
 if(conversions.hasCustomReadTarget(value.getClass(), rawType)) {
  return (R) conversionService.convert(value, rawType);			  
 }else if(value instanceof CrateDocument) {
  return (R) read(type, (CrateDocument) value, parent);
 }else if(value instanceof CrateArray) {
  return (R) readCollection(type, (CrateArray) value, parent);
 } else {
  return (R) getPotentiallyConvertedSimpleRead(value, rawType);
 }
}
 
Example 8
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 9
Source File: DatastorePersistentEntityImpl.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param information type information about the underlying entity type.
 * @param datastoreMappingContext a mapping context used to get metadata for related
 *     persistent entities.
 */
public DatastorePersistentEntityImpl(TypeInformation<T> information,
		DatastoreMappingContext datastoreMappingContext) {
	super(information);

	Class<?> rawType = information.getType();

	this.datastoreMappingContext = datastoreMappingContext;
	this.context = new StandardEvaluationContext();
	this.kind = findAnnotation(Entity.class);
	this.discriminatorField = findAnnotation(DiscriminatorField.class);
	this.discriminatorValue = findAnnotation(DiscriminatorValue.class);
	this.classBasedKindName = this.hasTableName() ? this.kind.name()
			: StringUtils.uncapitalize(rawType.getSimpleName());
	this.kindNameExpression = detectExpression();
}
 
Example 10
Source File: SpannerPersistentEntityImpl.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link SpannerPersistentEntityImpl}.
 * @param information type information about the underlying entity type.
 * @param spannerMappingContext a mapping context that can be used to create persistent
 *     entities from properties of this entity
 * @param spannerEntityProcessor an entity processor used to create keys by converting and
 *     combining id properties, as well as to convert keys to property values
 */
public SpannerPersistentEntityImpl(TypeInformation<T> information,
		SpannerMappingContext spannerMappingContext, SpannerEntityProcessor spannerEntityProcessor) {
	super(information);

	Assert.notNull(spannerMappingContext,
			"A non-null SpannerMappingContext is required.");
	Assert.notNull(spannerEntityProcessor, "A non-null SpannerEntityProcessor is required.");

	this.spannerMappingContext = spannerMappingContext;

	this.spannerEntityProcessor = spannerEntityProcessor;

	this.rawType = information.getType();

	this.context = new StandardEvaluationContext();

	this.table = this.findAnnotation(Table.class);
	Where annotation = findAnnotation(Where.class);
	this.where = annotation != null ? annotation.value() : "";
	this.tableNameExpression = detectExpression();
}
 
Example 11
Source File: MappingCrateConverter.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
/**
 * Read an incoming {@link CrateDocument} into the target entity.
 *
 * @param type the type information of the target entity.
 * @param source the document to convert.
 * @param parent an optional parent object.
 * @param <R> the entity type.
 * @return the converted entity.
 */
@SuppressWarnings("unchecked")
protected <R> R read(final TypeInformation<R> type, final CrateDocument source, final Object parent) {
	
    if(source == null) {
    	return null;
    }

    TypeInformation<? extends R> typeToUse = typeMapper.readType(source, type);
    Class<? extends R> rawType = typeToUse.getType();

    if(conversions.hasCustomReadTarget(source.getClass(), rawType)) {
      return conversionService.convert(source, rawType);
    }

    if(typeToUse.isMap()) {
      return (R) readMap(typeToUse, source, parent);
    }

    CratePersistentEntity<R> entity = (CratePersistentEntity<R>) mappingContext.getPersistentEntity(typeToUse);
    
    if(entity == null) {
      throw new MappingException("No mapping metadata found for " + rawType.getName());
    }
    
    return read(entity, source, parent);
}
 
Example 12
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 13
Source File: FreemarkerTemplateQuery.java    From spring-data-jpa-extra with Apache License 2.0 5 votes vote down vote up
private Query createJpaQuery(String queryString) {
    Class<?> objectType = getQueryMethod().getReturnedObjectType();

    //get original proxy query.
    Query oriProxyQuery;

    //must be hibernate QueryImpl
    NativeQuery query;

    if (useJpaSpec && getQueryMethod().isQueryForEntity()) {
        oriProxyQuery = getEntityManager().createNativeQuery(queryString, objectType);
    } else {
        oriProxyQuery = getEntityManager().createNativeQuery(queryString);
        query = AopTargetUtils.getTarget(oriProxyQuery);
        Class<?> genericType;
        //find generic type
        if (objectType.isAssignableFrom(Map.class)) {
            genericType = objectType;
        } else {
            ClassTypeInformation<?> ctif = ClassTypeInformation.from(objectType);
            TypeInformation<?> actualType = ctif.getActualType();
            genericType = actualType.getType();
        }
        if (genericType != Void.class) {
            QueryBuilder.transform(query, genericType);
        }
    }
    //return the original proxy query, for a series of JPA actions, e.g.:close em.
    return oriProxyQuery;
}
 
Example 14
Source File: DefaultDatastoreEntityConverter.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public <T, R> Map<T, R> readAsMap(BaseEntity entity, TypeInformation mapTypeInformation) {
	Assert.notNull(mapTypeInformation, "mapTypeInformation can't be null");
	if (entity == null) {
		return null;
	}
	Map<T, R> result;
	if (!mapTypeInformation.getType().isInterface()) {
		try {
			result = (Map<T, R>) ((Constructor<?>) mapTypeInformation.getType().getConstructor()).newInstance();
		}
		catch (Exception e) {
			throw new DatastoreDataException("Unable to create an instance of a custom map type: "
					+ mapTypeInformation.getType()
					+ " (make sure the class is public and has a public no-args constructor)", e);
		}
	}
	else {
		result = new HashMap<>();
	}

	EntityPropertyValueProvider propertyValueProvider = new EntityPropertyValueProvider(
			entity, this.conversions);
	Set<String> fieldNames = entity.getNames();
	for (String field : fieldNames) {
		result.put(this.conversions.convertOnRead(field, NOT_EMBEDDED, mapTypeInformation.getComponentType()),
				propertyValueProvider.getPropertyValue(field,
						EmbeddedType.of(mapTypeInformation.getMapValueType()),
						mapTypeInformation.getMapValueType()));
	}
	return result;
}
 
Example 15
Source File: MappingCrateConverter.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
/**
 * Read a collection from the source object.
 *
 * @param targetType the target type.
 * @param source the list as source.
 * @param parent the optional parent.
 * @return the converted {@link Collection} or array, will never be {@literal null}.
 */
private Object readCollection(final TypeInformation<?> targetType, final CrateArray source, final Object parent) {
	
	notNull(targetType);

    Class<?> collectionType = targetType.getType();
    
    if(source.isEmpty()) {
      return getPotentiallyConvertedSimpleRead(new HashSet<Object>(), collectionType);
    }

    collectionType = Collection.class.isAssignableFrom(collectionType) ? collectionType : List.class;
    
    Collection<Object> items = targetType.getType().isArray() ? new ArrayList<Object>(source.size()) :
    															createCollection(collectionType, source.size());
    
    TypeInformation<?> componentType = targetType.getComponentType();
    
    Class<?> rawComponentType = componentType == null ? null : componentType.getType();

    for(Object object : source) {
    	if(object instanceof CrateDocument) {
    		items.add(read(componentType, (CrateDocument) object, parent));
    	}else {
    		items.add(getPotentiallyConvertedSimpleRead(object, rawComponentType));
    	}
    }
    
    return getPotentiallyConvertedSimpleRead(items, targetType.getType());
  }
 
Example 16
Source File: MappingSolrConverter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T readValue(Object value, TypeInformation<?> type, Object parent) {
	if (value == null) {
		return null;
	}

	Assert.notNull(type);
	Class<?> rawType = type.getType();
	if (hasCustomReadTarget(value.getClass(), rawType)) {
		return (T) convert(value, rawType);
	}

	Object documentValue = null;
	if (value instanceof SolrInputField) {
		documentValue = ((SolrInputField) value).getValue();
	} else {
		documentValue = value;
	}

	if (documentValue instanceof Collection) {
		return (T) readCollection((Collection<?>) documentValue, type, parent);
	} else if (canConvert(documentValue.getClass(), rawType)) {
		return (T) convert(documentValue, rawType);
	}

	return (T) documentValue;

}
 
Example 17
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 5 votes vote down vote up
private void addTypeKeyIfNecessary(
	final TypeInformation<?> definedType,
	final Object value,
	final VPackBuilder sink) {

	final Class<?> referenceType = definedType != null ? definedType.getType() : Object.class;
	final Class<?> valueType = ClassUtils.getUserClass(value.getClass());
	if (!valueType.equals(referenceType)) {
		typeMapper.writeType(valueType, sink);
	}
}
 
Example 18
Source File: MappingSolrConverter.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private Object readWildcardMap(Map<String, ?> source, SolrPersistentProperty property, Object parent,
		WildcardPosition wildcardPosition) {

	TypeInformation<?> mapTypeInformation = property.getTypeInformation().getMapValueType();
	Class<?> rawMapType = mapTypeInformation.getType();

	Class<?> genericTargetType;
	if (mapTypeInformation.getTypeArguments() != null && !mapTypeInformation.getTypeArguments().isEmpty()) {
		genericTargetType = mapTypeInformation.getTypeArguments().get(0).getType();
	} else {
		genericTargetType = Object.class;
	}

	Map<String, Object> values;
	if (LinkedHashMap.class.isAssignableFrom(property.getActualType())) {
		values = new LinkedHashMap<String, Object>();
	} else {
		values = new HashMap<String, Object>();
	}

	for (Map.Entry<String, ?> potentialMatch : source.entrySet()) {

		String key = potentialMatch.getKey();

		if (!wildcardPosition.match(property.getFieldName(), key)) {
			continue;
		}

		if (property.isDynamicProperty()) {
			key = wildcardPosition.extractName(property.getFieldName(), key);
		}
		Object value = potentialMatch.getValue();

		if (value instanceof Iterable) {

			if (rawMapType.isArray() || ClassUtils.isAssignable(rawMapType, value.getClass())) {
				List<Object> nestedValues = new ArrayList<Object>();
				for (Object o : (Iterable<?>) value) {
					nestedValues.add(readValue(property, o, parent, genericTargetType));
				}
				values.put(key, (rawMapType.isArray() ? nestedValues.toArray() : nestedValues));
			} else {
				throw new IllegalArgumentException(
						"Incompartible types found. Expected " + rawMapType + " for " + property.getName()
								+ " with name " + property.getFieldName() + ", but found " + value.getClass());
			}
		} else {

			if (rawMapType.isArray() || ClassUtils.isAssignable(rawMapType, List.class)) {
				ArrayList<Object> singletonArrayList = new ArrayList<Object>(1);
				Object read = readValue(property, value, parent, genericTargetType);
				singletonArrayList.add(read);
				values.put(key, (rawMapType.isArray() ? singletonArrayList.toArray() : singletonArrayList));

			} else {
				values.put(key, getValue(property, value, parent));
			}
		}
	}

	return values.isEmpty() ? null : values;
}
 
Example 19
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 20
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 4 votes vote down vote up
private Object readInternal(final TypeInformation<?> type, final VPackSlice source) {
	if (source == null) {
		return null;
	}

	if (VPackSlice.class.isAssignableFrom(type.getType())) {
		return source;
	}

	final TypeInformation<?> typeToUse = (source.isArray() || source.isObject()) ? typeMapper.readType(source, type)
			: type;
	final Class<?> rawTypeToUse = typeToUse.getType();

	if (conversions.hasCustomReadTarget(VPackSlice.class, typeToUse.getType())) {
		return conversionService.convert(source, rawTypeToUse);
	}

	if (conversions.hasCustomReadTarget(DBDocumentEntity.class, typeToUse.getType())) {
		return conversionService.convert(readSimple(DBDocumentEntity.class, source), rawTypeToUse);
	}

	if (!source.isArray() && !source.isObject()) {
		return convertIfNecessary(readSimple(rawTypeToUse, source), rawTypeToUse);
	}

	if (DBDocumentEntity.class.isAssignableFrom(rawTypeToUse)) {
		return readSimple(rawTypeToUse, source);
	}

	if (BaseDocument.class.isAssignableFrom(rawTypeToUse)) {
		return readBaseDocument(rawTypeToUse, source);
	}

	if (typeToUse.isMap()) {
		return readMap(typeToUse, source);
	}

	if (!source.isArray() && ClassTypeInformation.OBJECT.equals(typeToUse)) {
		return readMap(ClassTypeInformation.MAP, source);
	}

	if (typeToUse.getType().isArray()) {
		return readArray(typeToUse, source);
	}

	if (typeToUse.isCollectionLike()) {
		return readCollection(typeToUse, source);
	}

	if (ClassTypeInformation.OBJECT.equals(typeToUse)) {
		return readCollection(ClassTypeInformation.COLLECTION, source);
	}

	final ArangoPersistentEntity<?> entity = context.getRequiredPersistentEntity(rawTypeToUse);
	return readEntity(typeToUse, source, entity);
}