Example usage for org.springframework.data.mapping PropertyHandler PropertyHandler

List of usage examples for org.springframework.data.mapping PropertyHandler PropertyHandler

Introduction

In this page you can find the example usage for org.springframework.data.mapping PropertyHandler PropertyHandler.

Prototype

PropertyHandler

Source Link

Usage

From source file:nivance.jpa.cassandra.prepare.convert.MappingCassandraConverter.java

public List<Clause> getKeyPart(final CassandraPersistentEntity<?> entity, final Object valueBean) {
    final List<Clause> result = new LinkedList<Clause>();
    entity.doWithProperties(new PropertyHandler<CassandraPersistentProperty>() {
        public void doWithPersistentProperty(CassandraPersistentProperty prop) {
            //TODO
            if (prop.getKeyPart() != null) {
                //keypart?
                Method method = ReflectionUtils.findMethod(entity.getType(),
                        "get" + StringUtils.capitalize(prop.getColumnName()));
                Object id = ReflectionUtils.invokeMethod(method, valueBean);
                result.add(QueryBuilder.eq(prop.getColumnName(), id));
            }/*w w w. j a  va2  s .  co m*/
        }
    });
    if (result.isEmpty()) {
        throw new MappingException(
                "Could not form a where clause for the primary key for an entity " + entity.getName());
    }
    return result;
}

From source file:com.joyveb.dbpimpl.cass.prepare.convert.MappingCassandraConverter.java

private void embeddedPrimaryKey(Class<?> idClass, Object id, final List<Clause> result,
        final boolean partitionPartsOnly) {

    final BeanWrapper<CassandraPersistentEntity<Object>, Object> wrapper = BeanWrapper.create(id,
            conversionService);/*from w  w w.  j a va2 s  .c o m*/

    final CassandraPersistentEntity<?> idEntity = mappingContext.getPersistentEntity(idClass);

    if (idEntity == null) {
        throw new MappingException("id entity not found for " + idClass);
    }

    // Write the properties
    doWithAllProperties(idEntity, new PropertyHandler<CassandraPersistentProperty>() {
        public void doWithPersistentProperty(CassandraPersistentProperty prop) {

            KeyPart keyPart = prop.getKeyPart();
            if (keyPart != null) {
                if (!partitionPartsOnly || keyPart == KeyPart.PARTITION) {
                    Object propertyObj = wrapper.getProperty(prop, prop.getType(), useFieldAccessOnly);

                    if (propertyObj == null) {
                        throw new MappingException("null primary key column " + prop.getColumnName()
                                + " in entity " + idEntity.getName());
                    }

                    result.add(QueryBuilder.eq(prop.getColumnName(), propertyObj));
                }
            }

        }
    });

}

From source file:com.joyveb.dbpimpl.cass.prepare.convert.MappingCassandraConverter.java

private void doWithAllProperties(final CassandraPersistentEntity<?> entity,
        final PropertyHandler<CassandraPersistentProperty> handler) {

    entity.doWithProperties(new PropertyHandler<CassandraPersistentProperty>() {
        public void doWithPersistentProperty(CassandraPersistentProperty prop) {

            if (prop.hasEmbeddableType()) {

                final CassandraPersistentEntity<?> pkEntity = mappingContext
                        .getPersistentEntity(prop.getRawType());

                if (pkEntity == null) {
                    throw new MappingException("entity not found for " + prop.getRawType());
                }//from   ww w. j av  a 2 s .com

                if (prop.isIdProperty()) {
                    validatePkEntity(pkEntity);
                }

                doWithAllProperties(pkEntity, handler);

            } else {

                handler.doWithPersistentProperty(prop);

            }

        }
    });

}

From source file:com.joyveb.dbpimpl.cass.prepare.convert.MappingCassandraConverter.java

private void validatePkEntity(final CassandraPersistentEntity<?> pkEntity) {

    pkEntity.doWithProperties(new PropertyHandler<CassandraPersistentProperty>() {
        public void doWithPersistentProperty(CassandraPersistentProperty pkProp) {

            if (pkProp.getKeyPart() == null) {
                throw new MappingException(
                        "all properties in composite private key must be annotated by a KeyColumn annotation "
                                + pkEntity.getType());
            }//from ww w  .  j  ava  2s.c  om

        }
    });

}

From source file:nivance.jpa.cassandra.prepare.convert.MappingCassandraConverter.java

private void doWithAllProperties(final CassandraPersistentEntity<?> entity,
        final PropertyHandler<CassandraPersistentProperty> handler) {

    entity.doWithProperties(new PropertyHandler<CassandraPersistentProperty>() {
        public void doWithPersistentProperty(CassandraPersistentProperty prop) {
            //TODO 
            if (prop.hasEmbeddableType()) {

                final CassandraPersistentEntity<?> pkEntity = mappingContext
                        .getPersistentEntity(prop.getRawType());

                if (pkEntity == null) {
                    throw new MappingException("entity not found for " + prop.getRawType());
                }/*from  w  w w.jav a2 s  .c o m*/

                if (prop.isIdProperty()) {
                    validatePkEntity(pkEntity);
                }

                doWithAllProperties(pkEntity, handler);

            } else {

                handler.doWithPersistentProperty(prop);

            }

        }
    });

}

From source file:org.springframework.data.document.mongodb.convert.MappingMongoConverter.java

private <S extends Object> S read(final MongoPersistentEntity<S> entity, final DBObject dbo) {

    final StandardEvaluationContext spelCtx = new StandardEvaluationContext();
    if (null != applicationContext) {
        spelCtx.setBeanResolver(new BeanFactoryResolver(applicationContext));
    }//from   w w  w  .  j av  a  2s  .  c  o m
    if (!(dbo instanceof BasicDBList)) {
        String[] keySet = dbo.keySet().toArray(new String[] {});
        for (String key : keySet) {
            spelCtx.setVariable(key, dbo.get(key));
        }
    }

    final List<String> ctorParamNames = new ArrayList<String>();
    final MongoPersistentProperty idProperty = entity.getIdProperty();
    final S instance = constructInstance(entity, new PreferredConstructor.ParameterValueProvider() {
        @SuppressWarnings("unchecked")
        public <T> T getParameterValue(PreferredConstructor.Parameter<T> parameter) {
            String name = parameter.getName();
            TypeInformation<T> type = parameter.getType();
            Class<T> rawType = parameter.getRawType();
            String key = idProperty == null ? name
                    : idProperty.getName().equals(name) ? idProperty.getKey() : name;
            Object obj = dbo.get(key);

            ctorParamNames.add(name);
            if (obj instanceof DBRef) {
                return read(type, ((DBRef) obj).fetch());
            } else if (obj instanceof BasicDBList) {
                BasicDBList objAsDbList = (BasicDBList) obj;
                List<?> l = unwrapList(objAsDbList, type);
                return conversionService.convert(l, rawType);
            } else if (obj instanceof DBObject) {
                return read(type, ((DBObject) obj));
            } else if (null != obj && obj.getClass().isAssignableFrom(rawType)) {
                return (T) obj;
            } else if (null != obj) {
                return conversionService.convert(obj, rawType);
            }

            return null;
        }
    }, spelCtx);

    // Set properties not already set in the constructor
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            boolean isConstructorProperty = ctorParamNames.contains(prop.getName());
            boolean hasValueForProperty = dbo.containsField(prop.getKey());

            if (!hasValueForProperty || isConstructorProperty) {
                return;
            }

            Object obj = getValueInternal(prop, dbo, spelCtx, prop.getSpelExpression());
            try {
                setProperty(instance, prop, obj, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    // Handle associations
    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Object obj = getValueInternal(inverseProp, dbo, spelCtx, inverseProp.getSpelExpression());
            try {
                setProperty(instance, inverseProp, obj);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    return instance;
}

From source file:org.springframework.data.document.mongodb.convert.MappingMongoConverter.java

protected void writeInternal(final Object obj, final DBObject dbo, MongoPersistentEntity<?> entity) {

    if (obj == null) {
        return;//from w w w  . ja v a2 s  .  c o m
    }

    if (null == entity) {
        throw new MappingException("No mapping metadata found for entity of type " + obj.getClass().getName());
    }

    // Write the ID
    final MongoPersistentProperty idProperty = entity.getIdProperty();
    if (!dbo.containsField("_id") && null != idProperty) {
        Object idObj;
        try {
            idObj = getProperty(obj, idProperty, Object.class, useFieldAccessOnly);
        } catch (IllegalAccessException e) {
            throw new MappingException(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new MappingException(e.getMessage(), e);
        }

        if (null != idObj) {
            dbo.put("_id", idObj);
        } else {
            if (!VALID_ID_TYPES.contains(idProperty.getType())) {
                throw new MappingException("Invalid data type " + idProperty.getType().getName()
                        + " for Id property. Should be one of " + VALID_ID_TYPES);
            }
        }
    }

    // Write the properties
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {
            String name = prop.getName();
            Class<?> type = prop.getType();
            Object propertyObj;
            try {
                propertyObj = getProperty(obj, prop, type, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
            if (null != propertyObj) {
                if (!isSimpleType(propertyObj.getClass())) {
                    writePropertyInternal(prop, propertyObj, dbo);
                } else {
                    dbo.put(name, propertyObj);
                }
            }
        }
    });

    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Class<?> type = inverseProp.getType();
            Object propertyObj;
            try {
                propertyObj = getProperty(obj, inverseProp, type, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
            if (null != propertyObj) {
                writePropertyInternal(inverseProp, propertyObj, dbo);
            }
        }
    });
}

From source file:org.springframework.data.document.mongodb.mapping.MongoPersistentEntityIndexCreator.java

protected void checkForIndexes(final MongoPersistentEntity<?> entity) {
    final Class<?> type = entity.getType();
    if (!classesSeen.contains(type)) {
        if (log.isDebugEnabled()) {
            log.debug("Analyzing class " + type + " for index information.");
        }/*from   ww w.  jav  a 2  s. c  om*/

        // Make sure indexes get created
        if (type.isAnnotationPresent(CompoundIndexes.class)) {
            CompoundIndexes indexes = type.getAnnotation(CompoundIndexes.class);
            for (CompoundIndex index : indexes.value()) {
                String indexColl = index.collection();
                if ("".equals(indexColl)) {
                    indexColl = entity.getCollection();
                }
                ensureIndex(indexColl, index.name(), index.def(), index.direction(), index.unique(),
                        index.dropDups(), index.sparse());
                if (log.isDebugEnabled()) {
                    log.debug("Created compound index " + index);
                }
            }
        }

        entity.doWithProperties(new PropertyHandler() {
            public void doWithPersistentProperty(PersistentProperty persistentProperty) {
                Field field = persistentProperty.getField();
                if (field.isAnnotationPresent(Indexed.class)) {
                    Indexed index = field.getAnnotation(Indexed.class);
                    String name = index.name();
                    if ("".equals(name)) {
                        name = field.getName();
                    } else {
                        if (!name.equals(field.getName()) && index.unique() && !index.sparse()) {
                            // Names don't match, and sparse is not true. This situation will generate an error on the server.
                            if (log.isWarnEnabled()) {
                                log.warn("The index name " + name + " doesn't match this property name: "
                                        + field.getName()
                                        + ". Setting sparse=true on this index will prevent errors when inserting documents.");
                            }
                        }
                    }
                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    ensureIndex(collection, name, null, index.direction(), index.unique(), index.dropDups(),
                            index.sparse());
                    if (log.isDebugEnabled()) {
                        log.debug("Created property index " + index);
                    }
                } else if (field.isAnnotationPresent(GeoSpatialIndexed.class)) {

                    GeoSpatialIndexed index = field.getAnnotation(GeoSpatialIndexed.class);

                    GeospatialIndex indexObject = new GeospatialIndex(
                            StringUtils.hasText(index.name()) ? index.name() : field.getName());
                    indexObject.withMin(index.min()).withMax(index.max());

                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    mongoTemplate.ensureIndex(collection, indexObject);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Created %s for entity %s in collection %s! ", indexObject,
                                entity.getType(), collection));
                    }
                }
            }
        });

        classesSeen.add(type);
    }

}

From source file:org.springframework.data.gemfire.mapping.MappingPdxSerializer.java

@Override
public Object fromData(final Class<?> type, final PdxReader reader) {
    final GemfirePersistentEntity<?> entity = getPersistentEntity(type);

    final Object instance = getInstantiatorFor(entity).createInstance(entity,
            new PersistentEntityParameterValueProvider<GemfirePersistentProperty>(entity,
                    new GemfirePropertyValueProvider(reader), null));

    final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(
            entity.getPropertyAccessor(instance), getConversionService());

    entity.doWithProperties(new PropertyHandler<GemfirePersistentProperty>() {
        public void doWithPersistentProperty(GemfirePersistentProperty persistentProperty) {
            if (!entity.isConstructorArgument(persistentProperty)) {
                PdxSerializer customSerializer = getCustomSerializer(persistentProperty.getType());

                Object value = null;

                try {
                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "setting property [%1$s] for entity [%2$s] of type [%3$s] from PDX%4$s",
                                persistentProperty.getName(), instance, type,
                                (customSerializer != null
                                        ? String.format(" using custom PdxSerializer [%1$s]", customSerializer)
                                        : "")));
                    }//from w  w  w. jav a 2s  .c  o  m

                    value = (customSerializer != null
                            ? customSerializer.fromData(persistentProperty.getType(), reader)
                            : reader.readField(persistentProperty.getName()));

                    if (log.isDebugEnabled()) {
                        log.debug(String.format("with value [%1$s]", value));
                    }

                    accessor.setProperty(persistentProperty, value);
                } catch (Exception e) {
                    throw new MappingException(String.format(
                            "while setting value [%1$s] of property [%2$s] for entity of type [%3$s] from PDX%4$s",
                            value, persistentProperty.getName(), type,
                            (customSerializer != null
                                    ? String.format(" using custom PdxSerializer [%14s]", customSerializer)
                                    : "")),
                            e);
                }
            }
        }
    });

    return accessor.getBean();
}

From source file:org.springframework.data.gemfire.mapping.MappingPdxSerializer.java

@Override
public boolean toData(final Object value, final PdxWriter writer) {
    GemfirePersistentEntity<?> entity = getPersistentEntity(value.getClass());

    final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(
            entity.getPropertyAccessor(value), getConversionService());

    entity.doWithProperties(new PropertyHandler<GemfirePersistentProperty>() {
        @Override// w  ww.j a  va 2 s .c  o m
        @SuppressWarnings("unchecked")
        public void doWithPersistentProperty(GemfirePersistentProperty persistentProperty) {
            PdxSerializer customSerializer = getCustomSerializer(persistentProperty.getType());

            Object propertyValue = null;

            try {
                propertyValue = accessor.getProperty(persistentProperty);

                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "serializing value [%1$s] of property [%2$s] for entity of type [%3$s] to PDX%4$s",
                            propertyValue, persistentProperty.getName(), value.getClass(),
                            (customSerializer != null
                                    ? String.format(" using custom PdxSerializer [%1$s]", customSerializer)
                                    : "")));
                }

                if (customSerializer != null) {
                    customSerializer.toData(propertyValue, writer);
                } else {
                    writer.writeField(persistentProperty.getName(), propertyValue,
                            (Class) persistentProperty.getType());
                }
            } catch (Exception e) {
                throw new MappingException(String.format(
                        "while serializing value [%1$s] of property [%2$s] for entity of type [%3$s] to PDX%4$s",
                        propertyValue, persistentProperty.getName(), value.getClass(),
                        (customSerializer != null
                                ? String.format(" using custom PdxSerializer [%1$s].",
                                        customSerializer.getClass().getName())
                                : ".")),
                        e);
            }
        }
    });

    GemfirePersistentProperty idProperty = entity.getIdProperty();

    if (idProperty != null) {
        writer.markIdentityField(idProperty.getName());
    }

    return true;
}