use of org.springframework.beans.NotWritablePropertyException in project spring-framework by spring-projects.
the class BeanPropertyRowMapper method mapRow.
/**
* Extract the values for all columns in the current row.
* <p>Utilizes public setters and result set meta-data.
* @see java.sql.ResultSetMetaData
*/
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
BeanWrapperImpl bw = new BeanWrapperImpl();
initBeanWrapper(bw);
T mappedObject = constructMappedInstance(rs, bw);
bw.setBeanInstance(mappedObject);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<>() : null);
for (int index = 1; index <= columnCount; index++) {
String column = JdbcUtils.lookupColumnName(rsmd, index);
String field = lowerCaseName(StringUtils.delete(column, " "));
PropertyDescriptor pd = (this.mappedFields != null ? this.mappedFields.get(field) : null);
if (pd != null) {
try {
Object value = getColumnValue(rs, index, pd);
if (rowNumber == 0 && logger.isDebugEnabled()) {
logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type '" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "'");
}
try {
bw.setPropertyValue(pd.getName(), value);
} catch (TypeMismatchException ex) {
if (value == null && this.primitivesDefaultedForNullValue) {
if (logger.isDebugEnabled()) {
logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '" + column + "' with null value when setting property '" + pd.getName() + "' of type '" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "' on object: " + mappedObject, ex);
}
} else {
throw ex;
}
}
if (populatedProperties != null) {
populatedProperties.add(pd.getName());
}
} catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException("Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex);
}
} else {
// No PropertyDescriptor found
if (rowNumber == 0 && logger.isDebugEnabled()) {
logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'");
}
}
}
if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of " + this.mappedClass + ": " + this.mappedProperties);
}
return mappedObject;
}
use of org.springframework.beans.NotWritablePropertyException in project spring-framework by spring-projects.
the class DefaultListableBeanFactoryTests method testPossibleMatches.
@Test
public void testPossibleMatches() {
try {
DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("ag", "foobar");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("tb", bd);
lbf.getBean("tb");
fail("Should throw exception on invalid property");
} catch (BeanCreationException ex) {
assertTrue(ex.getCause() instanceof NotWritablePropertyException);
NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause();
// expected
assertEquals(1, cause.getPossibleMatches().length);
assertEquals("age", cause.getPossibleMatches()[0]);
}
}
use of org.springframework.beans.NotWritablePropertyException in project alien4cloud by alien4cloud.
the class AbstractTypeNodeParser method parseAndSetValue.
protected void parseAndSetValue(BeanWrapper target, String key, Node valueNode, ParsingContextExecution context, MappingTarget mappingTarget) {
// let's store the parent in the context for future use
context.setParent(target.getWrappedInstance());
if (mappingTarget.getPath().equals("null")) {
// if the path is null, we just to do nothing with the stuff
return;
}
Entry<BeanWrapper, String> entry = findWrapperPropertyByPath(context.getRoot(), target, mappingTarget.getPath());
BeanWrapper realTarget = entry.getKey();
String propertyName = entry.getValue();
Object value = ((INodeParser<?>) mappingTarget.getParser()).parse(valueNode, context);
ParsingContextExecution.setParent(target, value);
if (!propertyName.equals("void")) {
// property named 'void' means : process the parsing but do not set anything
try {
realTarget.setPropertyValue(propertyName, value);
} catch (ConversionNotSupportedException e) {
context.getParsingErrors().add(new ParsingError(ParsingErrorLevel.ERROR, ErrorCode.SYNTAX_ERROR, "Invalid yaml type for property", valueNode.getStartMark(), "", valueNode.getEndMark(), toscaType));
} catch (NotWritablePropertyException e) {
log.warn("Error while setting property for yaml parsing.", e);
context.getParsingErrors().add(new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.ALIEN_MAPPING_ERROR, "Invalid definition for type", valueNode.getStartMark(), e.getPropertyName(), valueNode.getEndMark(), toscaType));
}
}
if (mappingTarget instanceof KeyValueMappingTarget) {
KeyValueMappingTarget kvmt = (KeyValueMappingTarget) mappingTarget;
BeanWrapper keyBeanWrapper = realTarget;
try {
if (!(keyBeanWrapper.getPropertyValue(kvmt.getKeyPath()) != null && propertyName.equals(key))) {
keyBeanWrapper.setPropertyValue(kvmt.getKeyPath(), key);
}
} catch (ConversionNotSupportedException e) {
context.getParsingErrors().add(new ParsingError(ParsingErrorLevel.ERROR, ErrorCode.SYNTAX_ERROR, "Invalid yaml type for property", valueNode.getStartMark(), "", valueNode.getEndMark(), toscaType));
} catch (NotWritablePropertyException e) {
log.warn("Error while setting key to property for yaml parsing.", e);
context.getParsingErrors().add(new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.ALIEN_MAPPING_ERROR, "Invalid definition for type", valueNode.getStartMark(), e.getPropertyName(), valueNode.getEndMark(), toscaType));
}
}
}
use of org.springframework.beans.NotWritablePropertyException in project irida by phac-nml.
the class CRUDServiceImpl method updateFields.
/**
* {@inheritDoc}
*/
@Override
@Transactional
public ValueType updateFields(KeyType id, Map<String, Object> updatedFields) throws ConstraintViolationException, EntityExistsException, InvalidPropertyException {
// check if you can actually update the properties requested
ValueType instance = read(id);
for (String key : updatedFields.keySet()) {
Object value = updatedFields.get(key);
try {
// setProperty doesn't throw an exception if the field name
// can't be found, so we have to force an exception to be thrown
// by calling getProperty manually first.
DirectFieldAccessor dfa = new DirectFieldAccessor(instance);
dfa.setPropertyValue(key, value);
} catch (IllegalArgumentException | NotWritablePropertyException | TypeMismatchException e) {
throw new InvalidPropertyException("Unable to access field [" + key + "]", valueType, e);
}
}
// now that you know all of the requested methods exist, validate the
// supplied values
Set<ConstraintViolation<ValueType>> constraintViolations = new HashSet<>();
// updated.
for (String propertyName : updatedFields.keySet()) {
Set<ConstraintViolation<ValueType>> propertyViolations = validator.validateValue(valueType, propertyName, updatedFields.get(propertyName));
constraintViolations.addAll(propertyViolations);
}
// if any validations fail, throw a constraint violation exception.
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
// check if the entity exists in the database
if (!exists(id)) {
throw new EntityNotFoundException("Entity not found.");
}
// return repository.update(id, updatedFields);
return repository.save(instance);
}
use of org.springframework.beans.NotWritablePropertyException in project spring-framework by spring-projects.
the class DefaultListableBeanFactoryTests method possibleMatches.
@Test
void possibleMatches() {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("ag", "foobar");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
lbf.registerBeanDefinition("tb", bd);
assertThatExceptionOfType(BeanCreationException.class).as("invalid property").isThrownBy(() -> lbf.getBean("tb")).withCauseInstanceOf(NotWritablePropertyException.class).satisfies(ex -> {
NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause();
assertThat(cause.getPossibleMatches()).hasSize(1);
assertThat(cause.getPossibleMatches()[0]).isEqualTo("age");
});
}
Aggregations