Search in sources :

Example 1 with NotWritablePropertyException

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;
}
Also used : BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PropertyDescriptor(java.beans.PropertyDescriptor) TypeMismatchException(org.springframework.beans.TypeMismatchException) ResultSetMetaData(java.sql.ResultSetMetaData) NotWritablePropertyException(org.springframework.beans.NotWritablePropertyException) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) HashSet(java.util.HashSet)

Example 2 with NotWritablePropertyException

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]);
    }
}
Also used : MutablePropertyValues(org.springframework.beans.MutablePropertyValues) NotWritablePropertyException(org.springframework.beans.NotWritablePropertyException) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) Test(org.junit.Test)

Example 3 with NotWritablePropertyException

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));
        }
    }
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) NotWritablePropertyException(org.springframework.beans.NotWritablePropertyException) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException)

Example 4 with NotWritablePropertyException

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);
}
Also used : TypeMismatchException(org.springframework.beans.TypeMismatchException) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) NotWritablePropertyException(org.springframework.beans.NotWritablePropertyException) ConstraintViolation(javax.validation.ConstraintViolation) InvalidPropertyException(ca.corefacility.bioinformatics.irida.exceptions.InvalidPropertyException) ConstraintViolationException(javax.validation.ConstraintViolationException) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with NotWritablePropertyException

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");
    });
}
Also used : MutablePropertyValues(org.springframework.beans.MutablePropertyValues) NotWritablePropertyException(org.springframework.beans.NotWritablePropertyException) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) Test(org.junit.jupiter.api.Test)

Aggregations

NotWritablePropertyException (org.springframework.beans.NotWritablePropertyException)5 HashSet (java.util.HashSet)2 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)2 TypeMismatchException (org.springframework.beans.TypeMismatchException)2 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)2 EntityNotFoundException (ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException)1 InvalidPropertyException (ca.corefacility.bioinformatics.irida.exceptions.InvalidPropertyException)1 PropertyDescriptor (java.beans.PropertyDescriptor)1 ResultSetMetaData (java.sql.ResultSetMetaData)1 ConstraintViolation (javax.validation.ConstraintViolation)1 ConstraintViolationException (javax.validation.ConstraintViolationException)1 Test (org.junit.Test)1 Test (org.junit.jupiter.api.Test)1 BeanWrapper (org.springframework.beans.BeanWrapper)1 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)1 ConversionNotSupportedException (org.springframework.beans.ConversionNotSupportedException)1 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)1 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)1 DataRetrievalFailureException (org.springframework.dao.DataRetrievalFailureException)1 InvalidDataAccessApiUsageException (org.springframework.dao.InvalidDataAccessApiUsageException)1