org.springframework.data.util.ClassTypeInformation Java Examples

The following examples show how to use org.springframework.data.util.ClassTypeInformation. 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: ReactiveNeo4jQueryMethod.java    From sdn-rx with 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 File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: DefaultPredicateArgumentResolver.java    From java-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: MybatisPersistentPropertyImpl.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
@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
Source File: DefaultArangoTypeMapper.java    From spring-data with 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 #6
Source File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testRawTableName() {
	SpannerPersistentEntityImpl<EntityNoCustomName> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(EntityNoCustomName.class));

	assertThat(entity.tableName()).isEqualTo("entityNoCustomName");
}
 
Example #7
Source File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpressionResolutionWithoutApplicationContext() {
	this.thrown.expect(SpannerDataException.class);
	this.thrown.expectMessage("Error getting table name for EntityWithExpression; " +
			"nested exception is org.springframework.expression.spel.SpelEvaluationException: " +
			"EL1007E: Property or field 'tablePostfix' cannot be found on null");
	SpannerPersistentEntityImpl<EntityWithExpression> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(EntityWithExpression.class));

	entity.tableName();
}
 
Example #8
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Object source, SecretDocument sink) {

	Class<?> entityType = ClassUtils.getUserClass(source.getClass());
	TypeInformation<? extends Object> type = ClassTypeInformation.from(entityType);

	SecretDocumentAccessor documentAccessor = new SecretDocumentAccessor(sink);

	writeInternal(source, documentAccessor, type);

	boolean handledByCustomConverter = this.conversions.hasCustomWriteTarget(entityType, SecretDocument.class);
	if (!handledByCustomConverter) {
		this.typeMapper.writeType(type, sink.getBody());
	}
}
 
Example #9
Source File: Neo4jQuerySupport.java    From sdn-rx with 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 #10
Source File: DefaultIdentifierGeneratorUnitTests.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@Test // DATAKV-136
public void shouldGenerateLongValueCorrectly() {

	Object value = generator.generateIdentifierOfType(ClassTypeInformation.from(Long.class));

	assertThat(value).isNotNull();
	assertThat(value).isInstanceOf(Long.class);
}
 
Example #11
Source File: DefaultIdentifierGeneratorUnitTests.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@Test // DATAKV-136
public void shouldGenerateStringValueCorrectly() {

	Object value = generator.generateIdentifierOfType(ClassTypeInformation.from(String.class));

	assertThat(value).isNotNull();
	assertThat(value).isInstanceOf(String.class);
}
 
Example #12
Source File: DefaultIdentifierGeneratorUnitTests.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@Test // DATAKV-136
public void shouldGenerateUUIDValueCorrectly() {

	Object value = generator.generateIdentifierOfType(ClassTypeInformation.from(UUID.class));

	assertThat(value).isNotNull();
	assertThat(value).isInstanceOf(UUID.class);
}
 
Example #13
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the given {@link Map} to the given {@link Map} considering the given
 * {@link TypeInformation}.
 * @param obj must not be {@literal null}.
 * @param bson must not be {@literal null}.
 * @param propertyType must not be {@literal null}.
 * @return the converted {@link Map}.
 */
protected Map<String, Object> writeMapInternal(Map<Object, Object> obj, Map<String, Object> bson,
		TypeInformation<?> propertyType) {

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

		Object key = entry.getKey();
		Object val = entry.getValue();

		if (this.conversions.isSimpleType(key.getClass())) {

			String simpleKey = key.toString();
			if (val == null || this.conversions.isSimpleType(val.getClass())) {
				bson.put(simpleKey, val);
			}
			else if (val instanceof Collection || val.getClass().isArray()) {

				bson.put(simpleKey, writeCollectionInternal(asCollection(val), propertyType.getMapValueType(),
						new ArrayList<>()));
			}
			else {
				SecretDocumentAccessor nested = new SecretDocumentAccessor(new SecretDocument());
				TypeInformation<?> valueTypeInfo = propertyType.isMap() ? propertyType.getMapValueType()
						: ClassTypeInformation.OBJECT;
				writeInternal(val, nested, valueTypeInfo);
				bson.put(simpleKey, nested.getBody());
			}
		}
		else {
			throw new MappingException("Cannot use a complex object as a key value.");
		}
	}

	return bson;
}
 
Example #14
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Internal write conversion method which should be used for nested invocations.
 * @param obj
 * @param sink
 * @param typeHint
 */
@SuppressWarnings("unchecked")
protected void writeInternal(Object obj, SecretDocumentAccessor sink, @Nullable TypeInformation<?> typeHint) {

	Class<?> entityType = obj.getClass();
	Optional<Class<?>> customTarget = this.conversions.getCustomWriteTarget(entityType, SecretDocument.class);

	if (customTarget.isPresent()) {

		SecretDocument result = this.conversionService.convert(obj, SecretDocument.class);

		if (result.getId() != null) {
			sink.setId(result.getId());
		}

		sink.getBody().putAll(result.getBody());
		return;
	}

	if (Map.class.isAssignableFrom(entityType)) {
		writeMapInternal((Map<Object, Object>) obj, sink.getBody(), ClassTypeInformation.MAP);
		return;
	}

	VaultPersistentEntity<?> entity = this.mappingContext.getRequiredPersistentEntity(entityType);
	writeInternal(obj, sink, entity);
	addCustomTypeKeyIfNecessary(typeHint, obj, sink);
}
 
Example #15
Source File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpressionResolutionFromApplicationContext() {
	SpannerPersistentEntityImpl<EntityWithExpression> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(EntityWithExpression.class));

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

	entity.setApplicationContext(applicationContext);
	assertThat(entity.tableName()).isEqualTo("table_something");
}
 
Example #16
Source File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidTableName() {
	this.thrown.expect(SpannerDataException.class);
	this.thrown.expectMessage(
			"Error getting table name for EntityBadName; nested exception is " +
					"org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException: Only " +
					"letters, numbers, and underscores are allowed in table names: ;DROP TABLE your_table;");

	SpannerPersistentEntityImpl<EntityBadName> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(EntityBadName.class));
	entity.tableName();
}
 
Example #17
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 #18
Source File: TwoStepsConversions.java    From spring-cloud-gcp with 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
Source File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testTableName() {
	SpannerPersistentEntityImpl<TestEntity> entity = new SpannerPersistentEntityImpl<>(
			ClassTypeInformation.from(TestEntity.class));

	assertThat(entity.tableName()).isEqualTo("custom_test_table");
}
 
Example #20
Source File: SpannerMappingContextTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationContextIsNotSet() {
	SpannerPersistentEntityImpl mockEntity = mock(SpannerPersistentEntityImpl.class);
	SpannerMappingContext context = createSpannerMappingContextWith(mockEntity);

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

	verifyZeroInteractions(mockEntity);
}
 
Example #21
Source File: SpannerMappingContextTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with 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 #23
Source File: DatastoreMappingContextTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationContextIsNotSet() {
	DatastorePersistentEntityImpl mockEntity = mock(
			DatastorePersistentEntityImpl.class);
	DatastoreMappingContext context = createDatastoreMappingContextWith(mockEntity);

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

	verifyZeroInteractions(mockEntity);
}
 
Example #24
Source File: DatastoreMappingContextTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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
Source File: DatastorePersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: DatastorePersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: DatastorePersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyCustomTableName() {
	DatastorePersistentEntityImpl<EntityEmptyCustomName> entity = new DatastorePersistentEntityImpl<>(
			ClassTypeInformation.from(EntityEmptyCustomName.class), null);

	assertThat(entity.kindName()).isEqualTo("entityEmptyCustomName");
}
 
Example #28
Source File: DatastorePersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testRawTableName() {
	DatastorePersistentEntityImpl<EntityNoCustomName> entity = new DatastorePersistentEntityImpl<>(
			ClassTypeInformation.from(EntityNoCustomName.class), null);

	assertThat(entity.kindName()).isEqualTo("entityNoCustomName");
}
 
Example #29
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(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 #30
Source File: DefaultIdentifierGeneratorUnitTests.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@Test // DATAKV-136
public void shouldGenerateIntValueCorrectly() {

	Object value = generator.generateIdentifierOfType(ClassTypeInformation.from(Integer.class));

	assertThat(value).isNotNull();
	assertThat(value).isInstanceOf(Integer.class);
}