org.springframework.data.mapping.MappingException Java Examples

The following examples show how to use org.springframework.data.mapping.MappingException. 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: MybatisPersistentPropertyImpl.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public Class<? extends TypeHandler<?>> getSpecifiedTypeHandler() {
	if (isAnnotationPresent(
			org.springframework.data.mybatis.annotation.TypeHandler.class)) {
		String value = getRequiredAnnotation(
				org.springframework.data.mybatis.annotation.TypeHandler.class)
						.value();
		try {
			Class<?> clz = ClassUtils.forName(value,
					ClassUtils.getDefaultClassLoader());

			if (!TypeHandler.class.isAssignableFrom(clz)) {
				throw new MappingException("The specified type handler with value: "
						+ value
						+ " must implement from org.apache.ibatis.type.TypeHandler");
			}
			return (Class<? extends TypeHandler<?>>) clz;
		}
		catch (ClassNotFoundException e) {
			throw new MappingException("The specified type handler with value: "
					+ value + " not found.");
		}
	}
	return null;
}
 
Example #2
Source File: SpannerPersistentPropertyImpl.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the name of the column in the Cloud Spanner table mapped to this property. The
 * column name is resolved using the {@link FieldNamingStrategy} passed in to the
 * {@link SpannerPersistentPropertyImpl#SpannerPersistentPropertyImpl(Property, PersistentEntity,
 * SimpleTypeHolder, FieldNamingStrategy)}
 * constructor. This is by default the by default
 *
 * @return the name of the column.
 * @throws MappingException if the resolution fails
 */
@Override
public String getColumnName() {
	if (StringUtils.hasText(getAnnotatedColumnName())) {
		return getAnnotatedColumnName();
	}

	String fieldName = this.fieldNamingStrategy.getFieldName(this);

	if (!StringUtils.hasText(fieldName)) {
		throw new MappingException(String.format(
				"Invalid (null or empty) field name returned for property %s by %s!",
				this, this.fieldNamingStrategy.getClass()));
	}

	return fieldName;
}
 
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: 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 #5
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 6 votes vote down vote up
private Object readArray(final TypeInformation<?> type, final VPackSlice source) {
	if (!source.isArray()) {
		throw new MappingException(
				String.format("Can't read array type %s from VPack type %s!", type, source.getType()));
	}

	final TypeInformation<?> componentType = getNonNullComponentType(type);
	final int length = source.getLength();
	final Object array = Array.newInstance(componentType.getType(), length);

	for (int i = 0; i < length; ++i) {
		Array.set(array, i, readInternal(componentType, source.get(i)));
	}

	return array;
}
 
Example #6
Source File: DefaultArangoConverter.java    From spring-data with 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 #7
Source File: MappingVaultEntityInformation.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
/**
 * @param entity
 */
public MappingVaultEntityInformation(VaultPersistentEntity<T> entity) {

	super(entity);

	if (!entity.hasIdProperty()) {

		throw new MappingException(String.format(
				"Entity %s requires to have an explicit id field. Did you forget to provide one using @Id?",
				entity.getName()));
	}
}
 
Example #8
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 #9
Source File: SpannerPersistentPropertyImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullColumnName() {
	this.expectedEx.expect(MappingException.class);
	// The expectMessage calls below operate as `contains` and seperate calls are used
	// because the printed order of some components can change randomly.
	this.expectedEx.expectMessage("Invalid (null or empty) field name returned for " +
			"property @org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey");
	this.expectedEx.expectMessage("keyOrder=1");
	this.expectedEx.expectMessage("value=1");
	this.expectedEx.expectMessage(
			"java.lang.String org.springframework.cloud.gcp.data.spanner.core.mapping." +
			"SpannerPersistentPropertyImplTests$TestEntity.id by class " +
			"org.springframework.data.mapping.model.FieldNamingStrategy$MockitoMock$");
	SpannerMappingContext context = new SpannerMappingContext();
	FieldNamingStrategy namingStrat = mock(FieldNamingStrategy.class);
	when(namingStrat.getFieldName(any())).thenReturn(null);
	context.setFieldNamingStrategy(namingStrat);
	SpannerPersistentEntity entity = context.getPersistentEntity(TestEntity.class);

	for (Object col : entity.columns()) {
		SpannerPersistentPropertyImpl prop = (SpannerPersistentPropertyImpl) entity
				.getPersistentProperty((String) col);

		// Getting the column name will throw an exception because of the mock naming
		// strategy.
		prop.getColumnName();
	}
}
 
Example #10
Source File: SpannerRepositoryFactoryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void getEntityInformationNotAvailableTest() {
	this.expectedEx.expect(MappingException.class);
	this.expectedEx.expectMessage("Could not lookup mapping metadata for domain " +
			"class org.springframework.cloud.gcp.data.spanner.repository.support." +
			"SpannerRepositoryFactoryTests$TestEntity!");
	SpannerRepositoryFactory factory = new SpannerRepositoryFactory(
			mock(SpannerMappingContext.class), this.spannerTemplate);
	factory.getEntityInformation(TestEntity.class);
}
 
Example #11
Source File: SpannerRepositoryFactory.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T, ID> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
	SpannerPersistentEntity<T> entity = (SpannerPersistentEntity<T>) this.spannerMappingContext
			.getPersistentEntity(domainClass);

	if (entity == null) {
		throw new MappingException(String.format(
				"Could not lookup mapping metadata for domain class %s!",
				domainClass.getName()));
	}

	return (EntityInformation<T, ID>) new SpannerPersistentEntityInformation<>(
			entity);
}
 
Example #12
Source File: DatastoreRepositoryFactoryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void getEntityInformationNotAvailableTest() {
	this.expectedException.expect(MappingException.class);
	this.expectedException.expectMessage("Could not lookup mapping metadata for domain class: " +
			"org.springframework.cloud.gcp.data.datastore.repository.support." +
			"DatastoreRepositoryFactoryTests$TestEntity");
	DatastoreRepositoryFactory factory = new DatastoreRepositoryFactory(
			mock(DatastoreMappingContext.class), this.datastoreTemplate);
	factory.getEntityInformation(TestEntity.class);
}
 
Example #13
Source File: DatastoreRepositoryFactory.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T, ID> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
	DatastorePersistentEntity entity = this.datastoreMappingContext
			.getPersistentEntity(domainClass);

	if (entity == null) {
		throw new MappingException(
				"Could not lookup mapping metadata for domain class: "
						+ domainClass.getName());
	}

	return new DatastorePersistentEntityInformation<>(entity);
}
 
Example #14
Source File: MappingCosmosConverter.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
public CosmosItemProperties writeCosmosItemProperties(Object sourceEntity) {
    if (sourceEntity == null) {
        return null;
    }

    final CosmosPersistentEntity<?> persistentEntity =
        mappingContext.getPersistentEntity(sourceEntity.getClass());

    if (persistentEntity == null) {
        throw new MappingException("no mapping metadata for entity type: " + sourceEntity.getClass().getName());
    }

    final ConvertingPropertyAccessor accessor = getPropertyAccessor(sourceEntity);
    final CosmosPersistentProperty idProperty = persistentEntity.getIdProperty();
    final CosmosItemProperties cosmosItemProperties;

    try {
        cosmosItemProperties =
            new CosmosItemProperties(objectMapper.writeValueAsString(sourceEntity));
    } catch (JsonProcessingException e) {
        throw new CosmosDBAccessException("Failed to map document value.", e);
    }

    if (idProperty != null) {
        final Object value = accessor.getProperty(idProperty);
        final String id = value == null ? null : value.toString();
        cosmosItemProperties.id(id);
    }

    return cosmosItemProperties;
}
 
Example #15
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 5 votes vote down vote up
private Date parseDate(final String source) {
	try {
		return DateUtil.parse(source);
	} catch (final ParseException e) {
		throw new MappingException(String.format("Can't parse java.util.Date from String %s!", source), e);
	}
}
 
Example #16
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 5 votes vote down vote up
@Override
public String convertId(final Object id) {
	if (!isValidId(id)) {
		throw new MappingException(
				String.format("Type %s is not a valid id type!", id != null ? id.getClass() : "null"));
	}
	if (id instanceof String) {
		return id.toString();
	}
	final boolean hasCustomConverter = conversions.hasCustomWriteTarget(id.getClass(), String.class);
	return hasCustomConverter ? conversionService.convert(id, String.class) : id.toString();
}
 
Example #17
Source File: DefaultArangoConverter.java    From spring-data with 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 #18
Source File: RepositoryQueryTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldDetectInvalidAnnotation() {

	Neo4jQueryMethod method = neo4jQueryMethod("annotatedQueryWithoutTemplate");
	assertThatExceptionOfType(MappingException.class)
		.isThrownBy(
			() -> StringBasedNeo4jQuery.create(mock(Neo4jOperations.class), mock(Neo4jMappingContext.class),
				QueryMethodEvaluationContextProvider.DEFAULT, method))
		.withMessage("Expected @Query annotation to have a value, but it did not.");
}
 
Example #19
Source File: TypeConversionIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void thereShallBeNoDefaultValuesForNonExistingAttributes(@Autowired NonExistingPrimitivesRepository repository) {

	assertThatExceptionOfType(MappingException.class)
		.isThrownBy(() -> repository.findById(ID_OF_NON_EXISTING_PRIMITIVES_NODE))
		.withMessageMatching("Error mapping Record<\\{n: \\{__internalNeo4jId__: \\d+, someBoolean: NULL, __nodeLabels__: \\[\"NonExistingPrimitives\"\\]\\}\\}>")
		.withStackTraceContaining(
			"org.springframework.dao.TypeMismatchDataAccessException: Could not convert NULL into boolean; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [boolean] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type")
		.withRootCauseInstanceOf(IllegalArgumentException.class);
}
 
Example #20
Source File: Schema.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
default NodeDescription<?> getRequiredNodeDescription(String primaryLabel) {
	NodeDescription<?> nodeDescription = getNodeDescription(primaryLabel);
	if (nodeDescription == null) {
		throw new MappingException(
			String.format("Required node description not found with primary label '%s'", primaryLabel));
	}
	return nodeDescription;
}
 
Example #21
Source File: DefaultNeo4jPersistentProperty.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public String getPropertyName() {

	String propertyName = this.graphPropertyName.getNullable();
	if (propertyName == null) {
		throw new MappingException("This property is not mapped to a Graph property!");
	}

	return propertyName;
}
 
Example #22
Source File: HazelcastEntityInformation.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * @param entity must not be {@literal null}.
 */
HazelcastEntityInformation(PersistentEntity<T, ?> entity) {
    super(entity);
    if (!entity.hasIdProperty()) {
        throw new MappingException(
                String.format("Entity %s requires a field annotated with %s", entity.getName(), Id.class.getName()));
    }
}
 
Example #23
Source File: StringBasedNeo4jQuery.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link StringBasedNeo4jQuery} for a query method that is annotated with {@link Query @Query}. The annotation
 * is expected to have a value.
 *
 * @param neo4jOperations the Neo4j operations
 * @param mappingContext a Neo4jMappingContext instance
 * @param evaluationContextProvider a QueryMethodEvaluationContextProvider instance
 * @param queryMethod the query method
 * @return A new instance of a String based Neo4j query.
 */
static StringBasedNeo4jQuery create(Neo4jOperations neo4jOperations, Neo4jMappingContext mappingContext,
	QueryMethodEvaluationContextProvider evaluationContextProvider,
	Neo4jQueryMethod queryMethod) {

	Query queryAnnotation = queryMethod.getQueryAnnotation()
		.orElseThrow(() -> new MappingException("Expected @Query annotation on the query method!"));

	String cypherTemplate = Optional.ofNullable(queryAnnotation.value())
		.filter(StringUtils::hasText)
		.orElseThrow(() -> new MappingException("Expected @Query annotation to have a value, but it did not."));

	return new StringBasedNeo4jQuery(neo4jOperations, mappingContext, evaluationContextProvider, queryMethod,
		cypherTemplate, Neo4jQueryType.fromDefinition(queryAnnotation));
}
 
Example #24
Source File: ReactiveStringBasedNeo4jQuery.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ReactiveStringBasedNeo4jQuery} for a query method that is annotated with {@link Query @Query}. The annotation
 * is expected to have a value.
 *
 * @param neo4jOperations reactive Neo4j operations
 * @param mappingContext a Neo4jMappingContext instance
 * @param evaluationContextProvider a QueryMethodEvaluationContextProvider instance
 * @param queryMethod the query method
 * @return A new instance of a String based Neo4j query.
 */
static ReactiveStringBasedNeo4jQuery create(ReactiveNeo4jOperations neo4jOperations, Neo4jMappingContext mappingContext,
	QueryMethodEvaluationContextProvider evaluationContextProvider,
	Neo4jQueryMethod queryMethod) {

	Query queryAnnotation = queryMethod.getQueryAnnotation()
		.orElseThrow(() -> new MappingException("Expected @Query annotation on the query method!"));

	String cypherTemplate = Optional.ofNullable(queryAnnotation.value())
		.filter(StringUtils::hasText)
		.orElseThrow(() -> new MappingException("Expected @Query annotation to have a value, but it did not."));

	return new ReactiveStringBasedNeo4jQuery(neo4jOperations, mappingContext, evaluationContextProvider, queryMethod,
		cypherTemplate, Neo4jQueryType.fromDefinition(queryAnnotation));
}
 
Example #25
Source File: IdentityColumnSupportImpl.java    From spring-data-mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public String getIdentityColumnString(int type) throws MappingException {
	return null;
}
 
Example #26
Source File: IdentityColumnSupportImpl.java    From spring-data-mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public String getIdentitySelectString(String table, String column, int type) throws MappingException {
	return null;
}
 
Example #27
Source File: HazelcastEntityInformationTest.java    From spring-data-hazelcast with Apache License 2.0 4 votes vote down vote up
@Test(expected = MappingException.class)
public void throwsMappingExceptionWhenNoIdPropertyPresent() {
    PersistentEntity<?, ?> persistentEntity = operations.getMappingContext().getPersistentEntity(NoIdEntity.class);
    new HazelcastEntityInformation<>(persistentEntity);
}
 
Example #28
Source File: AbstractTransactSQLIdentityColumnSupport.java    From spring-data-mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public String getIdentityColumnString(int type) throws MappingException {
	// starts with 1, implicitly
	return "identity not null";
}
 
Example #29
Source File: AbstractTransactSQLIdentityColumnSupport.java    From spring-data-mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public String getIdentitySelectString(String table, String column, int type) throws MappingException {
	return "select @@identity";
}
 
Example #30
Source File: MybatisBasicMapperBuilder.java    From spring-data-mybatis with Apache License 2.0 4 votes vote down vote up
private String buildCondition() {

		final StringBuilder builder = new StringBuilder();

		entity.doWithProperties((PropertyHandler<MybatisPersistentProperty>) p -> {

			Set<Condition> set = new HashSet<>();

			Conditions conditions = p.findAnnotation(Conditions.class);
			if (null != conditions && conditions.value().length > 0) {
				set.addAll(Stream.of(conditions.value()).collect(Collectors.toSet()));
			}
			Condition condition = p.findAnnotation(Condition.class);
			if (null != condition) {
				set.add(condition);
			}

			builder.append(set.stream().map(c -> {

				String[] properties = c.properties();
				if (null == properties || properties.length == 0) {
					properties = new String[] { p.getName() };
				}
				Type type = Type.valueOf(c.type().name());
				if (type.getNumberOfArguments() > 0
						&& type.getNumberOfArguments() != properties.length) {
					throw new MappingException("@Condition with type " + type + " needs "
							+ type.getNumberOfArguments() + " arguments, but only find "
							+ properties.length + " properties in this @Condition.");
				}

				StringBuilder sb = new StringBuilder();
				sb.append("<if test=\"");
				sb.append(Stream.of(properties).map(
						property -> String.format("__condition.%s != null", property))
						.collect(Collectors.joining(" and ")));

				sb.append("\">");

				sb.append(" and ")
						.append(queryConditionLeft(
								StringUtils.hasText(c.column()) ? c.column()
										: p.getColumnName(),
								IgnoreCaseType.valueOf(c.ignoreCaseType().name())))
						.append(calculateOperation(type));

				sb.append(queryConditionRight(type,
						IgnoreCaseType.valueOf(c.ignoreCaseType().name()),
						Stream.of(properties).map(p1 -> "__condition." + p1)
								.toArray(String[]::new)));

				sb.append("</if>");
				return sb;
			}).collect(Collectors.joining(" ")));

		});

		return builder.toString();
	}