org.springframework.data.mapping.model.MappingException Java Examples

The following examples show how to use org.springframework.data.mapping.model.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: SimpleSolrPersistentEntity.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public void doWithPersistentProperty(SolrPersistentProperty property) {

	if (property.isDynamicProperty()) {

		if (!property.isMap()) {
			throw new MappingException(
					String.format(DYNAMIC_PROPERTY_NOT_A_MAP, property.getName(), property.getFieldName()));
		}

		if (!property.containsWildcard()) {
			throw new MappingException(String.format(DYNAMIC_PROPERTY_NOT_CONTAINING_WILDCARD,
					property.getName(), property.getFieldName()));
		}
	}
}
 
Example #2
Source File: SimpleCratePersistentProperty.java    From spring-data-crate with Apache License 2.0 6 votes vote down vote up
public SimpleCratePersistentProperty(Field field, PropertyDescriptor propertyDescriptor, 
									 PersistentEntity<?, CratePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
	super(field, propertyDescriptor, owner, simpleTypeHolder);
	
	this.fieldNamingStrategy = INSTANCE;

	String fieldName = getFieldName();
	
	if(RESERVED_ID_FIELD_NAME.equals(fieldName)) {				
		throw new MappingException(format(RESERVED_ID, fieldName, owner.getType()));
	}
	
	if(RESERVED_VESRION_FIELD_NAME.equals(fieldName)) {				
		throw new MappingException(format(RESERVED_VERSION, fieldName, owner.getType()));
	}
	
	if(startsWithIgnoreCase(fieldName, "_")) {
		throw new MappingException(format(STARTS_WITH_UNDERSCORE, fieldName, owner.getType()));
	}
}
 
Example #3
Source File: CrateTemplate.java    From spring-data-crate with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T findById(Object id, Class<T> entityClass, String tableName) {
	
	notNull(id);
	
	if(!isIdPropertyDefined(entityClass)) {
		throw new MappingException(format("Entity '%s' has no id property defined", entityClass.getName()));
	}
	
	List<T> dbEntity = execute(new SelectAction(entityClass, tableName, id),
   						 	   new ReadDbHandler<T>(entityClass));
	if(dbEntity.isEmpty()) {
		logger.info("No row found with id '{}'", id);
		return null;
	}else {
		return dbEntity.iterator().next();
	}
}
 
Example #4
Source File: MappingCrateConverterTest.java    From spring-data-crate with Apache License 2.0 6 votes vote down vote up
@Test(expected=MappingException.class)
public void shouldNotWriteForMapWithComplexKeys() {
	
	String[][] nested = new String[1][1];
	nested[0] = new String[]{"STRING"};
	
	NestedArrays compleKey = new NestedArrays();
	compleKey.nested = nested;
	
	Map<NestedArrays, String> map = new HashMap<MappingCrateConverterTest.NestedArrays, String>();
	map.put(compleKey, "ComplexKey");
	
	MapWithComplexKey entity = new MapWithComplexKey();
	entity.map = map;
	
	converter.write(entity, new CrateDocument());
}
 
Example #5
Source File: DynamoDBPersistentEntityImpl.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the given property if it is a better candidate for the id
 * property than the current id property.
 * 
 * @param property
 *            the new id property candidate, will never be {@literal null}.
 * @return the given id property or {@literal null} if the given property is
 *         not an id property.
 */
protected DynamoDBPersistentProperty returnPropertyIfBetterIdPropertyCandidateOrNull(DynamoDBPersistentProperty property) {

	if (!property.isIdProperty()) {
		return null;
	}

	if (getIdProperty() != null) {

		if (getIdProperty().isCompositeIdProperty() && property.isHashKeyProperty()) {
			// Do nothing - favour id annotated properties over hashkey
			return null;
		} else if (getIdProperty().isHashKeyProperty() && property.isCompositeIdProperty()) {
			return property;
		} else {
			throw new MappingException(String.format("Attempt to add id property %s but already have property %s registered "
					+ "as id. Check your mapping configuration!", property.getField(), getIdProperty().getField()));
		}
	}

	return property;
}
 
Example #6
Source File: MetadataParser.java    From spring-data-simpledb with MIT License 6 votes vote down vote up
public static Field getIdField(Class<?> clazz) {
	Field idField = null;

	for(Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) {
		// named id or annotated with Id
		if(f.getName().equals(FIELD_NAME_DEFAULT_ID) || f.getAnnotation(Id.class) != null) {
			if(idField != null) {
				throw new MappingException("Multiple id fields detected for class " + clazz.getName());
			}
			idField = f;
		}

	}

	return idField;
}
 
Example #7
Source File: MappingCrateConverterTest.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
@Test(expected=MappingException.class)
public void shouldNotWriteForComplexNestedCollectionTypeId() {
	
	Set<List<String>> nested = new HashSet<List<String>>(1);
	nested.add(asList("STRING"));
	
	NestedCollections nestedEntity = new NestedCollections();
	nestedEntity.nested = nested;
	
	ComplexNestedCollectionTypeId entity = new ComplexNestedCollectionTypeId();
	entity.nestedId = nestedEntity;
	
	converter.write(entity, new CrateDocument());
}
 
Example #8
Source File: SimpleDbExceptionTranslatorTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test
public void translateExceptionIfPossible_should_not_interpret_non_translated_exception_like_mapping_exceptions() {
	MappingException mappingException = new MappingException("Invalid Query");

	DataAccessException dataAccessException = translator.translateExceptionIfPossible(mappingException);

	assertThat(dataAccessException, is(nullValue()));
}
 
Example #9
Source File: MappingCrateConverterTest.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
@Test(expected=MappingException.class)
public void shouldNotConvertForComplexNestedCollectionTypeId() {
	
	Set<List<String>> nested = new HashSet<List<String>>(1);
	nested.add(asList("STRING"));
	
	NestedCollections nestedEntity = new NestedCollections();
	nestedEntity.nested = nested;
	
	ComplexNestedCollectionTypeId entity = new ComplexNestedCollectionTypeId();
	entity.nestedId = nestedEntity;
	
	converter.convertToCrateType(entity, null);
}
 
Example #10
Source File: MetadataParser.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public static String getItemName(Object object) {
	Field idField = getIdField(object);

	if(idField != null) {
		try {
			idField.setAccessible(true);
			return (String) idField.get(object);
		} catch(IllegalAccessException e) {
			throw new MappingException("Could not read simpleDb id field", e);
		}
	}

	return null;
}
 
Example #11
Source File: QueryUtils.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public static void validateBindParametersCount(Parameters parameters,
		Object... parameterValues) {
	int numOfParameters = parameters.getNumberOfParameters();

	if (numOfParameters != parameterValues.length) {
		throw new MappingException(
				"Wrong Number of Parameters to bind in Query! Parameter Values size="
						+ parameterValues.length
						+ ", Method Bind Parameters size="
						+ numOfParameters);
	}
}
 
Example #12
Source File: AmazonSimpleDBUtil.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
/**
 * Unsed to encode a Not Integer {@link Number}.
 */
public static String encodeAsRealNumber(Object ob) {
	if(AmazonSimpleDBUtil.isNaN(ob) || AmazonSimpleDBUtil.isInfinite(ob)) {
		throw new MappingException("Could not serialize NaN or Infinity values");
	}

	BigDecimal realBigDecimal = AmazonSimpleDBUtil.tryToStoreAsRealBigDecimal(ob);
	if(realBigDecimal != null) {
		return AmazonSimpleDBUtil.encodeRealNumberRange(realBigDecimal, AmazonSimpleDBUtil.LONG_DIGITS,
				AmazonSimpleDBUtil.LONG_DIGITS, OFFSET_VALUE);
	}

	return null;
}
 
Example #13
Source File: AmazonSimpleDBUtil.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public static BigDecimal decodeRealNumber(String value) {
	if(value.matches(".*Infinity|NaN")) {
		throw new MappingException("Could not serialize NaN or Infinity values");
	}

	return AmazonSimpleDBUtil.decodeRealNumberRange(value, AmazonSimpleDBUtil.LONG_DIGITS, OFFSET_VALUE);
}
 
Example #14
Source File: AmazonSimpleDBUtil.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
/**
 * Encodes byteArray value into a base64-encoded string.
 * 
 * @return string representation of the date value
 */
public static String encodeByteArray(byte[] byteArray) {
	try {
		return new String(Base64.encodeBase64(byteArray), UTF8_ENCODING);
	} catch(UnsupportedEncodingException e) {
		throw new MappingException("Could not encode byteArray to UTF8 encoding", e);
	}
}
 
Example #15
Source File: AmazonSimpleDBUtil.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
/**
 * Decodes byte[] value from the string representation created using encodeDate(..) function.
 * 
 * @param value
 *            string representation of the date value
 * @return original byte[] value
 */
public static byte[] decodeByteArray(String value) throws ParseException {
	try {
		return Base64.decodeBase64(value.getBytes(UTF8_ENCODING));
	} catch(UnsupportedEncodingException e) {
		throw new MappingException("Could not decode byteArray to UTF8 encoding", e);
	}

}
 
Example #16
Source File: JsonMarshaller.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public <T> T unmarshall(String jsonString, Class<?> objectType) {
	Assert.notNull(jsonString);
	try {
		return (T) jsonMapper.readValue(jsonString, objectType);
	} catch(IOException e) {
		throw new MappingException("Could not unmarshall object : " + jsonString, e);
	}
}
 
Example #17
Source File: JsonMarshaller.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public <T> String marshall(T input) {
	Assert.notNull(input);
	jsonMapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
	jsonMapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, "@class");
	try {
		return jsonMapper.writeValueAsString(input);
	} catch(Exception e) {
		throw new MappingException(e.getMessage(), e);
	}
}
 
Example #18
Source File: SimpleDbResultConverterTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test(expected = MappingException.class)
public void filterNamedAttributesAsList_should_not_return_list_of_named_attributes_for_wrong_att() throws Exception {
	List<SampleEntity> entities = new ArrayList<SampleEntity>();
	SampleEntity entity = new SampleEntity();
	entities.add(entity);

	SimpleDbResultConverter.filterNamedAttributesAsList(entities, "wrongAttribute");
}
 
Example #19
Source File: PartTreeConverterTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test(expected = MappingException.class) 
public void shoud_fail_for_unsupported_operator() {
	final String methodName = "readByAgeEndsWith";
	final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
	
	PartTreeConverter.toIndexedQuery(tree);
}
 
Example #20
Source File: QueryUtilsIndexByQueryTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
/**
 * This test shows that if there is a String containing a '?' character, this character will be recognised as a
 * index parameter
 */

@Ignore
@Test(expected = MappingException.class)
public void buildQueryConditionsWithParameters_should_fail_for_wrong_string() {
	final String bind_query = "select * from customer_all WHERE name = 'where?' and age=?";
	final Parameters parameters = getMockParameters("?");
	System.out.println(QueryUtils.buildQuery(bind_query, parameters, 23));
}
 
Example #21
Source File: SimpleSolrPersistentEntity.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void assertUniqueness(SolrPersistentProperty property) {

			if (property.isScoreProperty()) {

				if (scoreProperty != null) {
					throw new MappingException(String.format(AMBIGUOUS_FIELD_MAPPING, property.getFieldName(),
							scoreProperty.getFieldName()));
				}

				scoreProperty = property;
			}
		}
 
Example #22
Source File: MappingCrateConverterTest.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
@Test(expected=MappingException.class)
public void shouldNotWriteForNestedCollectionTypeId() {
	
	Set<List<String>> nested = new HashSet<List<String>>(1);
	nested.add(asList("STRING"));
	
	NestedCollectionId entity = new NestedCollectionId();
	entity.nested = nested;
	
	converter.write(entity, new CrateDocument());
}
 
Example #23
Source File: SimpleCratePersistentEntity.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
@Override
public void addPersistentProperty(CratePersistentProperty property) {
	
	super.addPersistentProperty(property);
	
	if(property.isVersionProperty() && !isLongType(property.getType())) {
		throw new MappingException(format(VERSION_TYPE, property.getFieldName()));
	}
}
 
Example #24
Source File: SimpleCratePersistentProperty.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the key to be used to store the value of the property inside a Crate {@link CrateDBObject}.
 * 
 * @return name of field
 */
@Override
public String getFieldName() {
	
	String fieldName = fieldNamingStrategy.getFieldName(this);
	
	if (!hasText(fieldName)) {
		throw new MappingException(format("Invalid (null or empty) field name returned for property %s by %s!",
										  this, fieldNamingStrategy.getClass()));
	}
	
	return fieldName;
}
 
Example #25
Source File: CrateTemplate.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
private void validateIdValue(Object entity) {
	
	Object idValue = getIdPropertyValue(entity);
	
	if(idValue == null) {
		throw new MappingException(PRIMARY_KEY);
	}
}
 
Example #26
Source File: CrateTemplate.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
private void validateEntity() {
	
	if(!persistentEntity.hasIdProperty()) {
		throw new MappingException(format(ID_COLUMN, entity.getClass().getName()));
	}
	
	validateIdValue(entity);
}
 
Example #27
Source File: CrateTemplate.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
private void validateEntity(Class<?> entityClass) {
	
	CratePersistentProperty idProperty = getIdPropertyFor(entityClass);
	
	if (idProperty == null) {
		throw new MappingException("No id property found for object of type " + entityClass);
	}
}
 
Example #28
Source File: CrateTemplate.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
public void validateEntity(Class<?> entityClass) {
	
	CratePersistentEntity<?> persistentEntity = getPersistentEntityFor(entityClass);
	
	if(!persistentEntity.hasIdProperty()) {
		throw new MappingException(format(ID_COLUMN, entityClass.getName()));
	}
}
 
Example #29
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 #30
Source File: MappingCrateConverter.java    From spring-data-crate with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to write the map into the crate document.
 * 
 * @param source the source object.
 * @param sink the target document.
 * @param type the type information for the document.
 * @return the written crate document.
 */
private CrateDocument writeMapInternal(final Map<Object, Object> source, final CrateDocument sink, final TypeInformation<?> type) {

	for(Map.Entry<Object, Object> entry : source.entrySet()) {
		
		Object key = entry.getKey();
		Object val = entry.getValue();
		
		if(conversions.isSimpleType(key.getClass())) {
			
			String simpleKey = key.toString();
			
			if(val == null || (conversions.isSimpleType(val.getClass()) && !val.getClass().isArray())) {
				writeSimpleInternal(val, sink, simpleKey);
			}else if(val instanceof Collection || val.getClass().isArray()) {
				sink.put(simpleKey, writeCollectionInternal(asCollection(val), new CrateArray(), type.getMapValueType()));
			}else {
				CrateDocument document = new CrateDocument();
				TypeInformation<?> valueTypeInfo = type.isMap() ? type.getMapValueType() : OBJECT;
				writeInternal(val, document, valueTypeInfo);
				sink.put(simpleKey, document);
			}
		} else {
			throw new MappingException("Cannot use a complex object as a key value.");
		}
	}
	
	return sink;
}