Java Code Examples for org.springframework.data.util.ClassTypeInformation

The following examples show how to use org.springframework.data.util.ClassTypeInformation. These examples are extracted from open source projects. 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 Project: sdn-rx   Source File: ReactiveNeo4jQueryMethod.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ReactiveNeo4jQueryMethod} from the given parameters.
 *
 * @param method   must not be {@literal null}.
 * @param metadata must not be {@literal null}.
 * @param factory  must not be {@literal null}.
 */
ReactiveNeo4jQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) {
	super(method, metadata, factory);

	if (hasParameterOfType(method, Pageable.class)) {

		TypeInformation<?> returnType = ClassTypeInformation.fromReturnTypeOf(method);

		boolean multiWrapper = ReactiveWrappers.isMultiValueType(returnType.getType());
		boolean singleWrapperWithWrappedPageableResult = ReactiveWrappers.isSingleValueType(returnType.getType())
			&& (PAGE_TYPE.isAssignableFrom(returnType.getRequiredComponentType())
			|| SLICE_TYPE.isAssignableFrom(returnType.getRequiredComponentType()));

		if (singleWrapperWithWrappedPageableResult) {
			throw new InvalidDataAccessApiUsageException(
				String.format("'%s.%s' must not use sliced or paged execution. Please use Flux.buffer(size, skip).",
					ClassUtils.getShortName(method.getDeclaringClass()), method.getName()));
		}

		if (!multiWrapper) {
			throw new IllegalStateException(String.format(
				"Method has to use a multi-item reactive wrapper return type. Offending method: %s",
				method.toString()));
		}
	}
}
 
Example 2
Source Project: spring-data   Source File: DefaultArangoTypeMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> TypeInformation<? extends T> readType(final VPackSlice source, final TypeInformation<T> basicType) {
	Assert.notNull(source, "Source must not be null!");
	Assert.notNull(basicType, "Basic type must not be null!");

	final TypeInformation<?> documentsTargetType = readType(source);

	if (documentsTargetType == null) {
		return basicType;
	}

	final Class<T> rawType = basicType.getType();

	final boolean isMoreConcreteCustomType = rawType == null
			|| rawType.isAssignableFrom(documentsTargetType.getType()) && !rawType.equals(documentsTargetType);

	if (!isMoreConcreteCustomType) {
		return basicType;
	}

	final ClassTypeInformation<?> targetType = ClassTypeInformation.from(documentsTargetType.getType());

	return (TypeInformation<? extends T>) basicType.specialize(targetType);
}
 
Example 3
@Test
public void testSpELInvalidName() {
	this.thrown.expect(SpannerDataException.class);
	this.thrown.expectMessage(
			"Error getting table name for EntityWithExpression; nested exception is " +
					"org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException: " +
					"Only letters, numbers, and underscores are allowed in table names: " +
					"table_; DROP TABLE your_table;");

	SpannerPersistentEntityImpl<EntityWithExpression> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(EntityWithExpression.class));

	ApplicationContext applicationContext = mock(ApplicationContext.class);
	when(applicationContext.getBean("tablePostfix"))
			.thenReturn("; DROP TABLE your_table;");
	when(applicationContext.containsBean("tablePostfix")).thenReturn(true);

	entity.setApplicationContext(applicationContext);
	entity.tableName();
}
 
Example 4
@Nullable
private TypeInformation<?> detectAssociationTargetType() {

	if (!isAssociation()) {
		return null;
	}

	for (Class<? extends Annotation> annotationType : ASSOCIATION_ANNOTATIONS) {

		Annotation annotation = findAnnotation(annotationType);

		if (annotation == null) {
			continue;
		}

		Object entityValue = AnnotationUtils.getValue(annotation, "targetEntity");

		if (entityValue == null || entityValue.equals(void.class)) {
			continue;
		}

		return ClassTypeInformation.from((Class<?>) entityValue);
	}

	return null;
}
 
Example 5
/**
 * Obtains the domain type information from the given method parameter. Will
 * favor an explicitly registered on through
 * {@link QuerydslPredicate#root()} but use the actual type of the method's
 * return type as fallback.
 * 
 * @param parameter
 *            must not be {@literal null}.
 * @return
 */
static TypeInformation<?> extractTypeInfo(MethodParameter parameter) {

	QuerydslPredicate annotation = parameter.getParameterAnnotation(QuerydslPredicate.class);

	if (annotation != null && !Object.class.equals(annotation.root())) {
		return ClassTypeInformation.from(annotation.root());
	}

	Class<?> containingClass = parameter.getContainingClass();
	if (ClassUtils.isAssignable(EntityController.class, containingClass)) {
		ResolvableType resolvableType = ResolvableType.forClass(containingClass);
		return ClassTypeInformation.from(resolvableType.as(EntityController.class).getGeneric(0).resolve());
	}

	return detectDomainType(ClassTypeInformation.fromReturnTypeOf(parameter.getMethod()));
}
 
Example 6
Source Project: sdn-rx   Source File: Neo4jQuerySupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts parameter as needed by the query generated, which is not covered by standard conversion services.
 *
 * @param parameter The parameter to fit into the generated query.
 * @return A parameter that fits the place holders of a generated query
 */
final Object convertParameter(Object parameter) {

	if (parameter == null) {
		// According to https://neo4j.com/docs/cypher-manual/current/syntax/working-with-null/#cypher-null-intro
		// it does not make any sense to continue if a `null` value gets into a comparison
		// but we just warn the users and do not throw an exception on `null`.
		log.warn("Do not use `null` as a property value for comparison."
			+ " It will always be false and return an empty result.");

		return Values.NULL;
	}

	// Maybe move all of those into Neo4jConverter at some point.
	if (parameter instanceof Range) {
		return convertRange((Range) parameter);
	} else if (parameter instanceof Distance) {
		return calculateDistanceInMeter((Distance) parameter);
	} else if (parameter instanceof Circle) {
		return convertCircle((Circle) parameter);
	} else if (parameter instanceof Instant) {
		return ((Instant) parameter).atOffset(ZoneOffset.UTC);
	} else if (parameter instanceof Box) {
		return convertBox((Box) parameter);
	} else if (parameter instanceof BoundingBox) {
		return convertBoundingBox((BoundingBox) parameter);
	}

	// Good hook to check the NodeManager whether the thing is an entity and we replace the value with a known id.
	return mappingContext.getConverter()
		.writeValueFromProperty(parameter, ClassTypeInformation.from(parameter.getClass()));
}
 
Example 7
Source Project: sdn-rx   Source File: PartValidator.java    License: Apache License 2.0 5 votes vote down vote up
private void validatePointProperty(Part part) {

		Assert.isTrue(ClassTypeInformation.from(Point.class)
			.isAssignableFrom(part.getProperty().getLeafProperty().getTypeInformation()), () -> String
			.format("Can not derive query for '%s': %s works only with spatial properties", queryMethod,
				part.getType()));
	}
 
Example 8
Source Project: sdn-rx   Source File: DefaultNeo4jConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldCatchConversionErrors() {
	Value value = Values.value("Das funktioniert nicht.");

	assertThatExceptionOfType(TypeMismatchDataAccessException.class)
		.isThrownBy(() -> defaultNeo4jConverter.readValueForProperty(value, ClassTypeInformation.from(Date.class)))
		.withMessageStartingWith("Could not convert \"Das funktioniert nicht.\" into java.util.Date;")
		.withCauseInstanceOf(ConversionFailedException.class)
		.withRootCauseInstanceOf(DateTimeParseException.class);
}
 
Example 9
Source Project: sdn-rx   Source File: DefaultNeo4jConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldCatchUncoercibleErrors() {
	Value value = Values.value("Das funktioniert nicht.");

	assertThatExceptionOfType(TypeMismatchDataAccessException.class)
		.isThrownBy(() -> defaultNeo4jConverter.readValueForProperty(value, ClassTypeInformation.from(LocalDate.class)))
		.withMessageStartingWith("Could not convert \"Das funktioniert nicht.\" into java.time.LocalDate;")
		.withCauseInstanceOf(ConversionFailedException.class)
		.withRootCauseInstanceOf(Uncoercible.class);
}
 
Example 10
Source Project: sdn-rx   Source File: DefaultNeo4jConverterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldCatchUncoerfcibleErrors() {
	Value value = Values.value("Das funktioniert nicht.");

	assertThatExceptionOfType(TypeMismatchDataAccessException.class)
		.isThrownBy(
			() -> defaultNeo4jConverter.readValueForProperty(value, ClassTypeInformation.from(ReactiveNeo4jClient.class)))
		.withMessageStartingWith(
			"Could not convert \"Das funktioniert nicht.\" into org.neo4j.springframework.data.core.ReactiveNeo4jClient;")
		.withRootCauseInstanceOf(ConverterNotFoundException.class);
}
 
Example 11
Source Project: flow-platform-x   Source File: MongoConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MongoMappingContext mongoMappingContext() throws ClassNotFoundException {
    FlowMappingContext mappingContext = new FlowMappingContext();
    mappingContext.setInitialEntitySet(getInitialEntitySet());
    mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder());
    mappingContext.setFieldNamingStrategy(fieldNamingStrategy());

    mappingContext.addCustomizedPersistentEntity(ClassTypeInformation.from(ExecutedCmd.class), "executed_cmd");

    return mappingContext;
}
 
Example 12
Source Project: spring-data   Source File: DefaultArangoConverter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Optional<Object> readReference(
	final VPackSlice source,
	final ArangoPersistentProperty property,
	final Annotation annotation) {

	final Optional<ReferenceResolver<Annotation>> resolver = resolverFactory.getReferenceResolver(annotation);

	if (!resolver.isPresent() || source.isNone()) {
		return Optional.empty();
	}

	else if (property.isCollectionLike()) {
		final Collection<String> ids;
		try {
			ids = (Collection<String>) readCollection(ClassTypeInformation.COLLECTION, source);
		} catch (final ClassCastException e) {
			throw new MappingException("All references must be of type String!", e);
		}

		return resolver.map(res -> res.resolveMultiple(ids, property.getTypeInformation(), annotation));
	}

	else {
		if (!source.isString()) {
			throw new MappingException(
					String.format("A reference must be of type String, but got VPack type %s!", source.getType()));
		}

		return resolver.map(res -> res.resolveOne(source.getAsString(), property.getTypeInformation(), annotation));
	}
}
 
Example 13
Source Project: spring-data   Source File: DefaultArangoConverter.java    License: Apache License 2.0 5 votes vote down vote up
private BaseDocument readBaseDocument(final Class<?> type, final VPackSlice source) {
	@SuppressWarnings("unchecked")
	final Map<String, Object> properties = (Map<String, Object>) readMap(ClassTypeInformation.MAP, source);

	if (BaseDocument.class.equals(type)) {
		return new BaseDocument(properties);
	} //
	else if (BaseEdgeDocument.class.equals(type)) {
		return new BaseEdgeDocument(properties);
	} //
	else {
		throw new MappingException(String.format("Can't read type %s as %s!", type, BaseDocument.class));
	}
}
 
Example 14
Source Project: spring-data   Source File: DefaultArangoConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(final Object source, final VPackBuilder sink) {
	if (source == null) {
		writeSimple(null, null, sink);
		return;
	}

	final Object entity = source instanceof LazyLoadingProxy ? ((LazyLoadingProxy) source).getEntity() : source;

	writeInternal(null, entity, sink, ClassTypeInformation.OBJECT);
}
 
Example 15
Source Project: spring-data   Source File: DefaultArangoConverter.java    License: Apache License 2.0 5 votes vote down vote up
private void writeProperty(final Object source, final VPackBuilder sink, final ArangoPersistentProperty property) {
	if (source == null) {
		return;
	}

	final TypeInformation<?> sourceType = ClassTypeInformation.from(source.getClass());
	final String fieldName = property.getFieldName();

	if (property.getRef().isPresent()) {
		if (sourceType.isCollectionLike()) {
			writeReferences(fieldName, source, sink);
		} else {
			writeReference(fieldName, source, sink);
		}
	}

	else if (property.getRelations().isPresent()) {
		// nothing to store
	}

	else if (property.getFrom().isPresent() || property.getTo().isPresent()) {
		if (!sourceType.isCollectionLike()) {
			writeReference(fieldName, source, sink);
		}
	}

	else {
		final Object entity = source instanceof LazyLoadingProxy ? ((LazyLoadingProxy) source).getEntity() : source;
		writeInternal(fieldName, entity, sink, property.getTypeInformation());
	}
}
 
Example 16
Source Project: dubbox   Source File: MappingSolrConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <S, R> List<R> read(SolrDocumentList source, Class<R> type) {
	if (source == null) {
		return Collections.emptyList();
	}

	List<R> resultList = new ArrayList<R>(source.size());
	TypeInformation<R> typeInformation = ClassTypeInformation.from(type);
	for (Map<String, ?> item : source) {
		resultList.add(read(typeInformation, item));
	}

	return resultList;
}
 
Example 17
Source Project: spring-cloud-gcp   Source File: DatastoreTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> Map<String, T> findByIdAsMap(Key key, Class<T> valueType) {
	Assert.notNull(key, "A non-null Key is required.");
	Assert.notNull(valueType, "A non-null valueType is required.");

	Entity entity = getDatastoreReadWriter().get(key);
	return this.datastoreEntityConverter.readAsMap(String.class, ClassTypeInformation.from(valueType), entity);
}
 
Example 18
Source Project: spring-cloud-gcp   Source File: TwoStepsConversions.java    License: Apache License 2.0 5 votes vote down vote up
private EntityValue convertOnWriteSingleEmbeddedMap(Object val, String kindName,
		TypeInformation valueTypeInformation) {
	return applyEntityValueBuilder(null, kindName, (builder) -> {
		Map map = (Map) val;
		for (Object key : map.keySet()) {
			String field = convertOnReadSingle(convertOnWriteSingle(key).get(),
					ClassTypeInformation.from(String.class));
			builder.set(field,
					convertOnWrite(map.get(key),
							EmbeddedType.of(valueTypeInformation),
							field, valueTypeInformation));
		}
	}, false);
}
 
Example 19
@Override
public <T, R> Map<T, R> readAsMap(Class<T> keyType, TypeInformation<R> componentType,
		BaseEntity entity) {
	if (entity == null) {
		return null;
	}
	Map<T, R> result = new HashMap<>();
	return readAsMap(entity, ClassTypeInformation.from(result.getClass()));
}
 
Example 20
@Test
public void testRawTableName() {
	DatastorePersistentEntityImpl<EntityNoCustomName> entity = new DatastorePersistentEntityImpl<>(
			ClassTypeInformation.from(EntityNoCustomName.class), null);

	assertThat(entity.kindName()).isEqualTo("entityNoCustomName");
}
 
Example 21
@Test
public void testEmptyCustomTableName() {
	DatastorePersistentEntityImpl<EntityEmptyCustomName> entity = new DatastorePersistentEntityImpl<>(
			ClassTypeInformation.from(EntityEmptyCustomName.class), null);

	assertThat(entity.kindName()).isEqualTo("entityEmptyCustomName");
}
 
Example 22
@Test
public void testExpressionResolutionWithoutApplicationContext() {
	this.expectedException.expect(SpelEvaluationException.class);
	this.expectedException.expectMessage("Property or field 'kindPostfix' cannot be found on null");
	DatastorePersistentEntityImpl<EntityWithExpression> entity = new DatastorePersistentEntityImpl<>(
			ClassTypeInformation.from(EntityWithExpression.class), null);

	entity.kindName();
}
 
Example 23
@Test
public void testExpressionResolutionFromApplicationContext() {
	DatastorePersistentEntityImpl<EntityWithExpression> entity = new DatastorePersistentEntityImpl<>(
			ClassTypeInformation.from(EntityWithExpression.class), null);

	ApplicationContext applicationContext = mock(ApplicationContext.class);
	when(applicationContext.getBean("kindPostfix")).thenReturn("something");
	when(applicationContext.containsBean("kindPostfix")).thenReturn(true);

	entity.setApplicationContext(applicationContext);
	assertThat(entity.kindName()).isEqualTo("kind_something");
}
 
Example 24
@Test
public void testApplicationContextPassing() {
	DatastorePersistentEntityImpl mockEntity = mock(
			DatastorePersistentEntityImpl.class);
	DatastoreMappingContext context = createDatastoreMappingContextWith(mockEntity);
	ApplicationContext applicationContext = mock(ApplicationContext.class);
	context.setApplicationContext(applicationContext);

	context.createPersistentEntity(ClassTypeInformation.from(Object.class));

	verify(mockEntity, times(1)).setApplicationContext(eq(applicationContext));
}
 
Example 25
@Test
public void testApplicationContextIsNotSet() {
	DatastorePersistentEntityImpl mockEntity = mock(
			DatastorePersistentEntityImpl.class);
	DatastoreMappingContext context = createDatastoreMappingContextWith(mockEntity);

	context.createPersistentEntity(ClassTypeInformation.from(Object.class));

	verifyZeroInteractions(mockEntity);
}
 
Example 26
Source Project: spring-cloud-gcp   Source File: DatastoreTemplateTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findByIdAsMapTest() {
	Key keyForMap = createFakeKey("map1");

	Entity datastoreEntity = Entity.newBuilder(keyForMap).set("field1", 1L).build();
	when(this.datastore.get(eq(keyForMap))).thenReturn(datastoreEntity);

	this.datastoreTemplate.findByIdAsMap(keyForMap, Long.class);
	verify(this.datastoreEntityConverter, times(1))
			.readAsMap(eq(String.class), eq(ClassTypeInformation.from(Long.class)), eq(datastoreEntity));
}
 
Example 27
@Test
public void testApplicationContextPassing() {
	SpannerPersistentEntityImpl mockEntity = mock(SpannerPersistentEntityImpl.class);
	SpannerMappingContext context = createSpannerMappingContextWith(mockEntity);
	ApplicationContext applicationContext = mock(ApplicationContext.class);
	context.setApplicationContext(applicationContext);

	context.createPersistentEntity(ClassTypeInformation.from(Object.class));

	verify(mockEntity, times(1)).setApplicationContext(eq(applicationContext));
}
 
Example 28
@Test
public void testApplicationContextIsNotSet() {
	SpannerPersistentEntityImpl mockEntity = mock(SpannerPersistentEntityImpl.class);
	SpannerMappingContext context = createSpannerMappingContextWith(mockEntity);

	context.createPersistentEntity(ClassTypeInformation.from(Object.class));

	verifyZeroInteractions(mockEntity);
}
 
Example 29
@Test
public void testTableName() {
	SpannerPersistentEntityImpl<TestEntity> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(TestEntity.class));

	assertThat(entity.tableName()).isEqualTo("custom_test_table");
}
 
Example 30
@Test
public void testRawTableName() {
	SpannerPersistentEntityImpl<EntityNoCustomName> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(EntityNoCustomName.class));

	assertThat(entity.tableName()).isEqualTo("entityNoCustomName");
}