/** * Get the id of the entity. * @return the optional id */ public Optional<String> getId() { EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); return this.attributes.stream() .filter(entry -> idFieldName.equalsIgnoreCase(entry.name)) .map(e -> (String) e.value) .findFirst(); }
/** * Get the id of the entity. * @return the optional id */ public Optional<String> getId() { EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); return this.attributes.stream() .filter(entry -> idFieldName.equalsIgnoreCase(entry.name)) .map(e -> (String) e.value) .findFirst(); }
/** * Set the id of the entity if it doesn't have one already. */ public void setId() { if (!getId().isPresent()) { EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); String uuid = UUID.randomUUID().toString(); this.attributes.add(new Attribute(idFieldName, uuid)); } }
/** * Set the id of the entity if it doesn't have one already. */ public void setId() { if (!getId().isPresent()) { EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); String uuid = UUID.randomUUID().toString(); this.attributes.add(new Attribute(idFieldName, uuid)); } }
/** * Extract the attributes of the entity. */ private void setAttributes() { if (this.data != null) { this.attributes = new LinkedHashSet<>(); EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); for (Map.Entry<String, Object> entry : this.data.entrySet()) { if (dictionary.isAttribute(this.entityClass, entry.getKey())) { this.attributes.add(new Attribute(entry.getKey(), entry.getValue())); } if (Objects.equals(entry.getKey(), idFieldName)) { this.attributes.add(new Attribute(entry.getKey(), entry.getValue())); } } } }
/** * Set resource ID. * * @param id resource id */ public void setId(String id) { this.setValue(dictionary.getIdFieldName(getResourceClass()), id); }
/** * Set resource ID. * * @param id resource id */ public void setId(String id) { this.setValue(dictionary.getIdFieldName(getResourceClass()), id); }
/** * Extract the attributes of the entity. */ private void setAttributes() { if (this.data != null) { this.attributes = new LinkedHashSet<>(); EntityDictionary dictionary = this.requestScope.getDictionary(); String idFieldName = dictionary.getIdFieldName(this.entityClass); for (Map.Entry<String, Object> entry : this.data.entrySet()) { if (dictionary.isAttribute(this.entityClass, entry.getKey())) { this.attributes.add(new Attribute(entry.getKey(), entry.getValue())); } if (Objects.equals(entry.getKey(), idFieldName)) { this.attributes.add(new Attribute(entry.getKey(), entry.getValue())); } } } }
@Override public Object loadObject(Class<?> entityClass, Serializable id, Optional<FilterExpression> filterExpression, RequestScope scope) { Class idType = dictionary.getIdType(entityClass); String idField = dictionary.getIdFieldName(entityClass); FilterExpression idFilter = new InPredicate( new Path.PathElement(entityClass, idType, idField), id ); FilterExpression joinedFilterExpression = filterExpression .map(fe -> (FilterExpression) new AndFilterExpression(idFilter, fe)) .orElse(idFilter); Iterable<Object> results = loadObjects(entityClass, Optional.of(joinedFilterExpression), Optional.empty(), Optional.empty(), scope); Iterator<Object> it = results == null ? null : results.iterator(); if (it != null && it.hasNext()) { return it.next(); } return null; }
@Override public Object loadObject(Class<?> entityClass, Serializable id, Optional<FilterExpression> filterExpression, RequestScope scope) { Class idType = dictionary.getIdType(entityClass); String idField = dictionary.getIdFieldName(entityClass); FilterExpression idFilter = new InPredicate( new Path.PathElement(entityClass, idType, idField), id ); FilterExpression joinedFilterExpression = filterExpression .map(fe -> (FilterExpression) new AndFilterExpression(idFilter, fe)) .orElse(idFilter); Iterable<Object> results = loadObjects(entityClass, Optional.of(joinedFilterExpression), Optional.empty(), Optional.empty(), scope); Iterator<Object> it = results == null ? null : results.iterator(); if (it != null && it.hasNext()) { return it.next(); } return null; }
/** * Given the sorting rules validate sorting rules against the entities bound to the entityClass. * @param entityClass The root class for sorting (eg. /book?sort=-title this would be package.Book) * @param dictionary The elide entity dictionary * @param <T> The entityClass * @return The valid sorting rules - validated through the entity dictionary, or empty dictionary * @throws InvalidValueException when sorting values are not valid for the jpa entity */ public <T> Map<Path, SortOrder> getValidSortingRules(final Class<T> entityClass, final EntityDictionary dictionary) throws InvalidValueException { Map<Path, SortOrder> returnMap = new LinkedHashMap<>(); for (Map.Entry<String, SortOrder> entry : replaceIdRule(dictionary.getIdFieldName(entityClass)).entrySet()) { String dotSeparatedPath = entry.getKey(); SortOrder order = entry.getValue(); //Creating a path validates that the dot separated path is valid. Path path = new Path(entityClass, dictionary, dotSeparatedPath); if (! isValidSortRulePath(path, dictionary)) { throw new InvalidValueException("Cannot sort across a to-many relationship: " + path.getFieldPath()); } returnMap.put(path, order); } return returnMap; }
/** * Given the sorting rules validate sorting rules against the entities bound to the entityClass. * @param entityClass The root class for sorting (eg. /book?sort=-title this would be package.Book) * @param dictionary The elide entity dictionary * @param <T> The entityClass * @return The valid sorting rules - validated through the entity dictionary, or empty dictionary * @throws InvalidValueException when sorting values are not valid for the jpa entity */ public <T> Map<Path, SortOrder> getValidSortingRules(final Class<T> entityClass, final EntityDictionary dictionary) throws InvalidValueException { Map<Path, SortOrder> returnMap = new LinkedHashMap<>(); for (Map.Entry<String, SortOrder> entry : replaceIdRule(dictionary.getIdFieldName(entityClass)).entrySet()) { String dotSeparatedPath = entry.getKey(); SortOrder order = entry.getValue(); //Creating a path validates that the dot separated path is valid. Path path = new Path(entityClass, dictionary, dotSeparatedPath); if (! isValidSortRulePath(path, dictionary)) { throw new InvalidValueException("Cannot sort across a to-many relationship: " + path.getFieldPath()); } returnMap.put(path, order); } return returnMap; }
public Path(Class<?> entityClass, EntityDictionary dictionary, String dotSeparatedPath) { List<PathElement> elements = new ArrayList<>(); String[] fieldNames = dotSeparatedPath.split("\\."); Class<?> currentClass = entityClass; for (String fieldName : fieldNames) { if (dictionary.isRelation(currentClass, fieldName)) { Class<?> relationClass = dictionary.getParameterizedType(currentClass, fieldName); elements.add(new PathElement(currentClass, relationClass, fieldName)); currentClass = relationClass; } else if (dictionary.isAttribute(currentClass, fieldName) || fieldName.equals(dictionary.getIdFieldName(entityClass))) { Class<?> attributeClass = dictionary.getType(currentClass, fieldName); elements.add(new PathElement(currentClass, attributeClass, fieldName)); } else if ("this".equals(fieldName)) { elements.add(new PathElement(currentClass, null, fieldName)); } else { String alias = dictionary.getJsonAliasFor(currentClass); throw new InvalidValueException(alias + " doesn't contain the field " + fieldName); } } pathElements = ImmutableList.copyOf(elements); }
public Path(Class<?> entityClass, EntityDictionary dictionary, String dotSeparatedPath) { List<PathElement> elements = new ArrayList<>(); String[] fieldNames = dotSeparatedPath.split("\\."); Class<?> currentClass = entityClass; for (String fieldName : fieldNames) { if (dictionary.isRelation(currentClass, fieldName)) { Class<?> relationClass = dictionary.getParameterizedType(currentClass, fieldName); elements.add(new PathElement(currentClass, relationClass, fieldName)); currentClass = relationClass; } else if (dictionary.isAttribute(currentClass, fieldName) || fieldName.equals(dictionary.getIdFieldName(entityClass))) { Class<?> attributeClass = dictionary.getType(currentClass, fieldName); elements.add(new PathElement(currentClass, attributeClass, fieldName)); } else if ("this".equals(fieldName)) { elements.add(new PathElement(currentClass, null, fieldName)); } else { String alias = dictionary.getJsonAliasFor(currentClass); throw new InvalidValueException(alias + " doesn't contain the field " + fieldName); } } pathElements = ImmutableList.copyOf(elements); }
/** * Build an id filter expression for a particular entity type. * * @param ids Ids to include in the filter expression * @param entityType Type of entity * @return Filter expression for given ids and type. */ private static FilterExpression buildIdFilterExpression(List<String> ids, Class entityType, EntityDictionary dictionary, RequestScope scope) { Class<?> idType = dictionary.getIdType(entityType); String idField = dictionary.getIdFieldName(entityType); String typeAlias = dictionary.getJsonAliasFor(entityType); List<Object> coercedIds = ids.stream() .filter(id -> scope.getObjectById(typeAlias, id) == null) // these don't exist yet .map(id -> CoerceUtil.coerce(id, idType)) .collect(Collectors.toList()); /* construct a new SQL like filter expression, eg: book.id IN [1,2] */ FilterExpression idFilter = new InPredicate( new Path.PathElement( entityType, idType, idField), coercedIds); return idFilter; }
/** * Build an id filter expression for a particular entity type. * * @param ids Ids to include in the filter expression * @param entityType Type of entity * @return Filter expression for given ids and type. */ private static FilterExpression buildIdFilterExpression(List<String> ids, Class entityType, EntityDictionary dictionary, RequestScope scope) { Class<?> idType = dictionary.getIdType(entityType); String idField = dictionary.getIdFieldName(entityType); String typeAlias = dictionary.getJsonAliasFor(entityType); List<Object> coercedIds = ids.stream() .filter(id -> scope.getObjectById(typeAlias, id) == null) // these don't exist yet .map(id -> CoerceUtil.coerce(id, idType)) .collect(Collectors.toList()); /* construct a new SQL like filter expression, eg: book.id IN [1,2] */ FilterExpression idFilter = new InPredicate( new Path.PathElement( entityType, idType, idField), coercedIds); return idFilter; }
@Override public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { EntityDictionary dictionary = context.requestScope.getDictionary(); Class parentClass = context.parentResource.getResourceClass(); String fieldName = context.field.getName(); String idFieldName = dictionary.getIdFieldName(parentClass); if (dictionary.isAttribute(parentClass, fieldName)) { /* fetch attribute properties */ Object attribute = context.parentResource.getAttribute(fieldName); if (attribute instanceof Map) { return ((Map<Object, Object>) attribute).entrySet().stream() .map(MapEntryContainer::new) .collect(Collectors.toList()); } return attribute; } if (dictionary.isRelation(parentClass, fieldName)) { /* fetch relationship properties */ boolean generateTotals = requestContainsPageInfo(context.field); return fetcher.fetchRelationship(context, context.parentResource, fieldName, context.ids, context.offset, context.first, context.sort, context.filters, generateTotals); } if (Objects.equals(idFieldName, fieldName)) { return new DeferredId(context.parentResource); } throw new BadRequestException("Unrecognized object: " + fieldName + " for: " + parentClass.getName() + " in node"); } }
@Override public Object processFetch(Environment context, PersistentResourceFetcher fetcher) { EntityDictionary dictionary = context.requestScope.getDictionary(); Class parentClass = context.parentResource.getResourceClass(); String fieldName = context.field.getName(); String idFieldName = dictionary.getIdFieldName(parentClass); if (dictionary.isAttribute(parentClass, fieldName)) { /* fetch attribute properties */ Object attribute = context.parentResource.getAttribute(fieldName); if (attribute instanceof Map) { return ((Map<Object, Object>) attribute).entrySet().stream() .map(MapEntryContainer::new) .collect(Collectors.toList()); } return attribute; } if (dictionary.isRelation(parentClass, fieldName)) { /* fetch relationship properties */ boolean generateTotals = requestContainsPageInfo(context.field); return fetcher.fetchRelationship(context, context.parentResource, fieldName, context.ids, context.offset, context.first, context.sort, context.filters, generateTotals); } if (Objects.equals(idFieldName, fieldName)) { return new DeferredId(context.parentResource); } throw new BadRequestException("Unrecognized object: " + fieldName + " for: " + parentClass.getName() + " in node"); } }
/** * Updates an object * @param toUpdate Entities to update * @param entity Resource entity * @param attributes Set of entity attributes * @return Persistence Resource object */ private PersistentResource updateAttributes(PersistentResource toUpdate, Entity entity, Set<Entity.Attribute> attributes) { EntityDictionary dictionary = entity.getRequestScope().getDictionary(); Class<?> entityClass = entity.getEntityClass(); String idFieldName = dictionary.getIdFieldName(entityClass); /* iterate through each attribute provided */ for (Entity.Attribute attribute : attributes) { if (dictionary.isAttribute(entityClass, attribute.getName())) { toUpdate.updateAttribute(attribute.getName(), attribute.getValue()); } else if (!Objects.equals(attribute.getName(), idFieldName)) { throw new IllegalStateException("Unrecognized attribute passed to 'data': " + attribute.getName()); } } return toUpdate; }
/** * Updates an object * @param toUpdate Entities to update * @param entity Resource entity * @param attributes Set of entity attributes * @return Persistence Resource object */ private PersistentResource updateAttributes(PersistentResource toUpdate, Entity entity, Set<Entity.Attribute> attributes) { EntityDictionary dictionary = entity.getRequestScope().getDictionary(); Class<?> entityClass = entity.getEntityClass(); String idFieldName = dictionary.getIdFieldName(entityClass); /* iterate through each attribute provided */ for (Entity.Attribute attribute : attributes) { if (dictionary.isAttribute(entityClass, attribute.getName())) { toUpdate.updateAttribute(attribute.getName(), attribute.getValue()); } else if (!Objects.equals(attribute.getName(), idFieldName)) { throw new IllegalStateException("Unrecognized attribute passed to 'data': " + attribute.getName()); } } return toUpdate; }