Example usage for org.springframework.data.mapping PersistentPropertyAccessor getProperty

List of usage examples for org.springframework.data.mapping PersistentPropertyAccessor getProperty

Introduction

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

Prototype

@Nullable
default Object getProperty(PersistentPropertyPath<? extends PersistentProperty<?>> path) 

Source Link

Document

Return the value pointed to by the given PersistentPropertyPath .

Usage

From source file:org.springframework.data.rest.webmvc.json.Jackson2DatatypeHelperIntegrationTests.java

/**
 * @see DATAREST-500/* w  w  w .  java 2s  .  c om*/
 */
@Test
public void configuresHIbernate4ModuleToLoadLazyLoadingProxies() throws Exception {

    PersistentEntity<?, ?> entity = entities.getPersistentEntity(Order.class);
    PersistentProperty<?> property = entity.getPersistentProperty("creator");
    PersistentPropertyAccessor accessor = entity.getPropertyAccessor(orders.findOne(this.order.getId()));

    assertThat(objectMapper.writeValueAsString(accessor.getProperty(property)), is(not("null")));
}

From source file:com._4dconcept.springframework.data.marklogic.core.mapping.MarklogicMappingContextTest.java

private List<Criteria> doWith(BasicMarklogicPersistentEntity<?> entity, Object bean) {
    ArrayList<Criteria> criteriaList = new ArrayList<>();
    PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(bean);

    entity.doWithProperties((PropertyHandler<MarklogicPersistentProperty>) property -> {
        Object value = propertyAccessor.getProperty(property);
        if (value != null) {
            Criteria criteria = new Criteria();
            criteria.setQname(property.getQName());

            if (property.getPersistentEntityTypes() != null) {
                for (TypeInformation<?> typeInformation : property.getPersistentEntityTypes()) {
                    MarklogicMappingContext mappingContext = new MarklogicMappingContext();
                    BasicMarklogicPersistentEntity<?> subEntity = mappingContext
                            .getPersistentEntity(typeInformation);
                    value = doWith(subEntity, value);
                }//w  w w  .  j  a  va 2  s.c o m

                criteria.setCriteriaObject(value);
            }

            criteriaList.add(criteria);
        }
    });

    return criteriaList;
}

From source file:org.springframework.data.rest.webmvc.json.DomainObjectReader.java

/**
 * Merges the given {@link ObjectNode} onto the given object.
 * /*from   w  ww . j av a2  s .  c o m*/
 * @param root must not be {@literal null}.
 * @param target must not be {@literal null}.
 * @param mapper must not be {@literal null}.
 * @return
 * @throws Exception
 */
private <T> T doMerge(ObjectNode root, T target, ObjectMapper mapper) throws Exception {

    Assert.notNull(root, "Root ObjectNode must not be null!");
    Assert.notNull(target, "Target object instance must not be null!");
    Assert.notNull(mapper, "ObjectMapper must not be null!");

    PersistentEntity<?, ?> entity = entities.getPersistentEntity(target.getClass());

    if (entity == null) {
        return mapper.readerForUpdating(target).readValue(root);
    }

    MappedProperties mappedProperties = getJacksonProperties(entity, mapper);

    for (Iterator<Entry<String, JsonNode>> i = root.fields(); i.hasNext();) {

        Entry<String, JsonNode> entry = i.next();
        JsonNode child = entry.getValue();

        if (child.isArray()) {
            continue;
        }

        String fieldName = entry.getKey();

        if (!mappedProperties.hasPersistentPropertyForField(fieldName)) {
            i.remove();
            continue;
        }

        if (child.isObject()) {

            PersistentProperty<?> property = mappedProperties.getPersistentProperty(fieldName);

            if (associationLinks.isLinkableAssociation(property)) {
                continue;
            }

            PersistentPropertyAccessor accessor = entity.getPropertyAccessor(target);
            Object nested = accessor.getProperty(property);

            ObjectNode objectNode = (ObjectNode) child;

            if (property.isMap()) {

                // Keep empty Map to wipe it as expected
                if (!objectNode.fieldNames().hasNext()) {
                    continue;
                }

                doMergeNestedMap((Map<String, Object>) nested, objectNode, mapper);

                // Remove potentially emptied Map as values have been handled recursively
                if (!objectNode.fieldNames().hasNext()) {
                    i.remove();
                }

                continue;
            }

            if (nested != null && property.isEntity()) {
                doMerge(objectNode, nested, mapper);
            }
        }
    }

    return mapper.readerForUpdating(target).readValue(root);
}

From source file:com._4dconcept.springframework.data.marklogic.core.query.QueryBuilder.java

@Nullable
private Criteria buildCriteria(Object bean, MarklogicPersistentEntity<?> entity) {
    Stack<Criteria> stack = new Stack<>();
    PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(bean);

    entity.doWithProperties((PropertyHandler<MarklogicPersistentProperty>) property -> {
        Object value = propertyAccessor.getProperty(property);
        if (hasContent(value)) {
            if (stack.empty()) {
                stack.push(buildCriteria(property, value));
            } else {
                Criteria criteria = stack.peek();
                if (criteria.getOperator() == null) {
                    Criteria andCriteria = new Criteria(Criteria.Operator.and,
                            new ArrayList<>(Arrays.asList(criteria, buildCriteria(property, value))));
                    stack.pop();//from  www  . j  a  v a 2 s.c  o  m
                    stack.push(andCriteria);
                } else {
                    Criteria subCriteria = buildCriteria(property, value);
                    if (subCriteria != null) {
                        criteria.add(subCriteria);
                    }
                }
            }
        }
    });

    return stack.empty() ? null : stack.peek();
}

From source file:com._4dconcept.springframework.data.marklogic.core.MarklogicTemplate.java

/**
 * Populates the id property of the saved object, if it's not set already.
 *
 * @param objectToSave The object currently saved
 *//* w  ww.j  a va 2  s.  c om*/
private void generateIdIfNecessary(Object objectToSave) {
    MarklogicPersistentProperty property = getIdPropertyFor(objectToSave.getClass());

    if (property == null) {
        return;
    }

    MarklogicPersistentEntity<?> entity = retrievePersistentEntity(objectToSave.getClass());
    PersistentPropertyAccessor accessor = entity.getPropertyAccessor(objectToSave);

    if (accessor.getProperty(property) != null) {
        return;
    }

    ConversionService conversionService = marklogicConverter.getConversionService();
    new ConvertingPropertyAccessor(accessor, conversionService).setProperty(property, UUID.randomUUID());
}

From source file:com.frank.search.solr.core.convert.MappingSolrConverter.java

@SuppressWarnings("rawtypes")
protected void write(Object source, final Map target, SolrPersistentEntity<?> entity) {

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

    entity.doWithProperties(new PropertyHandler<SolrPersistentProperty>() {

        @SuppressWarnings("unchecked")
        @Override/*from   w  w w  . j a  va 2 s.com*/
        public void doWithPersistentProperty(SolrPersistentProperty persistentProperty) {

            Object value = accessor.getProperty(persistentProperty);
            if (value == null || persistentProperty.isReadonly()) {
                return;
            }

            if (persistentProperty.containsWildcard() && !persistentProperty.isMap()) {
                throw new IllegalArgumentException("Field '" + persistentProperty.getFieldName()
                        + "' must not contain wildcards. Consider excluding Field from beeing indexed.");
            }

            Collection<SolrInputField> fields;
            if (persistentProperty.isMap() && persistentProperty.containsWildcard()) {
                fields = writeWildcardMapPropertyToTarget(target, persistentProperty, (Map<?, ?>) value);
            } else {
                fields = writeRegularPropertyToTarget(target, persistentProperty, value);
            }

            if (persistentProperty.isBoosted()) {
                for (SolrInputField field : fields) {
                    field.setBoost(persistentProperty.getBoost());
                }
            }
        }
    });

    if (entity.isBoosted() && target instanceof SolrInputDocument) {
        ((SolrInputDocument) target).setDocumentBoost(entity.getBoost());
    }

}

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//from  w  w  w. j  ava 2s .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;
}

From source file:org.springframework.data.solr.core.convert.MappingSolrConverter.java

@SuppressWarnings("rawtypes")
protected void write(Object source, final Map target, SolrPersistentEntity<?> entity) {

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

    entity.doWithProperties(new PropertyHandler<SolrPersistentProperty>() {

        @SuppressWarnings({ "unchecked" })
        @Override//from   ww w  .ja  v  a 2s . c om
        public void doWithPersistentProperty(SolrPersistentProperty persistentProperty) {

            Object value = accessor.getProperty(persistentProperty);
            if (value == null || persistentProperty.isReadonly()) {
                return;
            }

            if (persistentProperty.containsWildcard() && !persistentProperty.isMap()) {
                throw new IllegalArgumentException("Field '" + persistentProperty.getFieldName()
                        + "' must not contain wildcards. Consider excluding Field from beeing indexed.");
            }

            Object fieldValue = value;
            if (persistentProperty.isMap() && persistentProperty.containsWildcard()) {
                TypeInformation<?> mapTypeInformation = persistentProperty.getTypeInformation()
                        .getMapValueType();
                Class<?> rawMapType = mapTypeInformation.getType();

                Map<?, ?> map = (Map<?, ?>) fieldValue;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    String mappedFieldName = entry.getKey().toString();
                    SolrInputField field = new SolrInputField(mappedFieldName);
                    if (entry.getValue() instanceof Iterable) {
                        for (Object o : (Iterable<?>) entry.getValue()) {
                            field.addValue(convertToSolrType(rawMapType, o), 1f);
                        }
                    } else {
                        if (rawMapType.isArray()) {
                            for (Object o : (Object[]) entry.getValue()) {
                                field.addValue(convertToSolrType(rawMapType, o), 1f);
                            }
                        } else {
                            field.addValue(convertToSolrType(rawMapType, entry.getValue()), 1f);
                        }
                    }
                    target.put(mappedFieldName, field);
                }
                return;
            }

            SolrInputField field = new SolrInputField(persistentProperty.getFieldName());
            if (persistentProperty.isCollectionLike()) {
                Collection<?> collection = asCollection(fieldValue);
                for (Object o : collection) {
                    if (o != null) {
                        field.addValue(convertToSolrType(persistentProperty.getType(), o), 1f);
                    }
                }
            } else {
                field.setValue(convertToSolrType(persistentProperty.getType(), fieldValue), 1f);
            }
            target.put(persistentProperty.getFieldName(), field);

            if (persistentProperty.isBoosted()) {
                field.setBoost(persistentProperty.getBoost());
            }

        }
    });

    if (entity.isBoosted() && target instanceof SolrInputDocument) {
        ((SolrInputDocument) target).setDocumentBoost(entity.getBoost());
    }

}