Search in sources :

Example 21 with Type

use of com.yahoo.elide.core.type.Type in project elide by yahoo.

the class DataStoreTransaction method loadObject.

/**
 * Loads an object by ID.  The reason we support both load by ID and load by filter is that
 * some legacy stores are optimized to load by ID.
 *
 * @param entityProjection the collection to load.
 * @param id - the ID of the object to load.
 * @param scope - the current request scope
 * @param <T> The model type being loaded.
 * It is optional for the data store to attempt evaluation.
 * @return the loaded object if it exists AND any provided security filters pass.
 */
default <T> T loadObject(EntityProjection entityProjection, Serializable id, RequestScope scope) {
    Type<?> entityClass = entityProjection.getType();
    FilterExpression filterExpression = entityProjection.getFilterExpression();
    EntityDictionary dictionary = scope.getDictionary();
    Type idType = dictionary.getIdType(entityClass);
    String idField = dictionary.getIdFieldName(entityClass);
    FilterExpression idFilter = new InPredicate(new Path.PathElement(entityClass, idType, idField), id);
    FilterExpression joinedFilterExpression = (filterExpression != null) ? new AndFilterExpression(idFilter, filterExpression) : idFilter;
    Iterable<T> results = loadObjects(entityProjection.copyOf().filterExpression(joinedFilterExpression).build(), scope);
    Iterator<T> it = results == null ? null : results.iterator();
    if (it != null && it.hasNext()) {
        T obj = it.next();
        if (!it.hasNext()) {
            return obj;
        }
        // Multiple objects with the same ID.
        throw new InvalidObjectIdentifierException(id.toString(), dictionary.getJsonAliasFor(entityClass));
    }
    return null;
}
Also used : Path(com.yahoo.elide.core.Path) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) Type(com.yahoo.elide.core.type.Type) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression)

Example 22 with Type

use of com.yahoo.elide.core.type.Type in project elide by yahoo.

the class HashMapStoreTransaction method createObject.

@Override
public void createObject(Object entity, RequestScope scope) {
    Type entityClass = EntityDictionary.getType(entity);
    String idFieldName = dictionary.getIdFieldName(entityClass);
    String id;
    if (containsObject(entity)) {
        throw new TransactionException(new IllegalStateException("Duplicate key"));
    }
    // GeneratedValue means the DB needs to assign the ID.
    if (dictionary.getAttributeOrRelationAnnotation(entityClass, GeneratedValue.class, idFieldName) != null) {
        // TODO: Id's are not necessarily numeric.
        AtomicLong nextId;
        synchronized (dataStore) {
            nextId = getId(entityClass);
        }
        id = String.valueOf(nextId.getAndIncrement());
        setId(entity, id);
    } else {
        id = dictionary.getId(entity);
    }
    replicateOperationToParent(entity, Operation.OpType.CREATE);
    operations.add(new Operation(id, entity, EntityDictionary.getType(entity), Operation.OpType.CREATE));
}
Also used : GeneratedValue(javax.persistence.GeneratedValue) Type(com.yahoo.elide.core.type.Type) AtomicLong(java.util.concurrent.atomic.AtomicLong) TransactionException(com.yahoo.elide.core.exceptions.TransactionException)

Example 23 with Type

use of com.yahoo.elide.core.type.Type in project elide by yahoo.

the class DefaultFilterDialect method parseGlobalExpression.

@Override
public FilterExpression parseGlobalExpression(String path, MultivaluedMap<String, String> filterParams, String apiVersion) throws ParseException {
    List<FilterPredicate> filterPredicates;
    filterPredicates = extractPredicates(filterParams, apiVersion);
    /* Extract the first collection in the URL */
    String normalizedPath = JsonApiParser.normalizePath(path);
    String[] pathComponents = normalizedPath.split("/");
    String firstPathComponent = "";
    if (pathComponents.length > 0) {
        firstPathComponent = pathComponents[0];
    }
    /* Comma separated filter parameters are joined with logical AND. */
    FilterExpression joinedExpression = null;
    for (FilterPredicate filterPredicate : filterPredicates) {
        Type firstClass = filterPredicate.getPath().getPathElements().get(0).getType();
        /* The first type in the predicate must match the first collection in the URL */
        if (!dictionary.getJsonAliasFor(firstClass).equals(firstPathComponent)) {
            throw new ParseException(String.format("Invalid predicate: %s", filterPredicate));
        }
        if ((filterPredicate.getOperator().equals(Operator.HASMEMBER) || filterPredicate.getOperator().equals(Operator.HASNOMEMBER)) && !FilterPredicate.isLastPathElementAssignableFrom(dictionary, filterPredicate.getPath(), COLLECTION_TYPE)) {
            throw new ParseException("Invalid Path: Last Path Element has to be a collection type");
        }
        if (joinedExpression == null) {
            joinedExpression = filterPredicate;
        } else {
            joinedExpression = new AndFilterExpression(joinedExpression, filterPredicate);
        }
    }
    return joinedExpression;
}
Also used : Type(com.yahoo.elide.core.type.Type) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) ParseException(com.yahoo.elide.core.filter.dialect.ParseException) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression)

Example 24 with Type

use of com.yahoo.elide.core.type.Type in project elide by yahoo.

the class AggregationDataStore method populateEntityDictionary.

/**
 * Populate an {@link EntityDictionary} and use this dictionary to construct a {@link QueryEngine}.
 * @param dictionary the dictionary
 */
@Override
public void populateEntityDictionary(EntityDictionary dictionary) {
    if (dynamicCompiledClasses != null && dynamicCompiledClasses.size() != 0) {
        dynamicCompiledClasses.stream().filter((type) -> !IS_TYPE_HIDDEN.test(type)).forEach(dynamicLoadedClass -> {
            dictionary.bindEntity(dynamicLoadedClass, IS_FIELD_HIDDEN);
            validateModelExpressionChecks(dictionary, dynamicLoadedClass);
            dictionary.bindPermissionExecutor(dynamicLoadedClass, aggPermissionExecutor);
        });
    }
    dictionary.getScanner().getAnnotatedClasses(AGGREGATION_STORE_CLASSES).stream().filter((type) -> !IS_TYPE_HIDDEN.test(ClassType.of(type))).forEach(cls -> {
        dictionary.bindEntity(cls, IS_FIELD_HIDDEN);
        validateModelExpressionChecks(dictionary, ClassType.of(cls));
        dictionary.bindPermissionExecutor(cls, aggPermissionExecutor);
    });
    for (Table table : queryEngine.getMetaDataStore().getMetaData(ClassType.of(Table.class))) {
        /* Add 'grain' argument to each TimeDimensionColumn */
        for (TimeDimension timeDim : table.getAllTimeDimensions()) {
            dictionary.addArgumentToAttribute(dictionary.getEntityClass(table.getName(), table.getVersion()), timeDim.getName(), new ArgumentType("grain", ClassType.STRING_TYPE, timeDim.getDefaultGrain().getGrain()));
        }
        /* Add argument to each Column */
        for (Column col : table.getAllColumns()) {
            for (ArgumentDefinition arg : col.getArgumentDefinitions()) {
                dictionary.addArgumentToAttribute(dictionary.getEntityClass(table.getName(), table.getVersion()), col.getName(), new ArgumentType(arg.getName(), ValueType.getType(arg.getType()), arg.getDefaultValue()));
            }
        }
        /* Add argument to each Table */
        for (ArgumentDefinition arg : table.getArgumentDefinitions()) {
            dictionary.addArgumentToEntity(dictionary.getEntityClass(table.getName(), table.getVersion()), new ArgumentType(arg.getName(), ValueType.getType(arg.getType()), arg.getDefaultValue()));
        }
    }
}
Also used : ColumnMeta(com.yahoo.elide.datastores.aggregation.annotation.ColumnMeta) Arrays(java.util.Arrays) ArgumentType(com.yahoo.elide.core.dictionary.ArgumentType) Join(com.yahoo.elide.datastores.aggregation.annotation.Join) AccessibleObject(com.yahoo.elide.core.type.AccessibleObject) TableMeta(com.yahoo.elide.datastores.aggregation.annotation.TableMeta) UserCheck(com.yahoo.elide.core.security.checks.UserCheck) PermissionExecutor(com.yahoo.elide.core.security.PermissionExecutor) Function(java.util.function.Function) ClassType(com.yahoo.elide.core.type.ClassType) Column(com.yahoo.elide.datastores.aggregation.metadata.models.Column) ToString(lombok.ToString) ParseTree(org.antlr.v4.runtime.tree.ParseTree) FilterExpressionCheck(com.yahoo.elide.core.security.checks.FilterExpressionCheck) RequestScope(com.yahoo.elide.core.RequestScope) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) Check(com.yahoo.elide.core.security.checks.Check) Cache(com.yahoo.elide.datastores.aggregation.cache.Cache) FromSubquery(com.yahoo.elide.datastores.aggregation.queryengines.sql.annotation.FromSubquery) PermissionExpressionVisitor(com.yahoo.elide.modelconfig.validator.PermissionExpressionVisitor) NonNull(lombok.NonNull) Predicate(java.util.function.Predicate) ValueType(com.yahoo.elide.datastores.aggregation.metadata.enums.ValueType) ArgumentDefinition(com.yahoo.elide.datastores.aggregation.metadata.models.ArgumentDefinition) Set(java.util.Set) FromTable(com.yahoo.elide.datastores.aggregation.queryengines.sql.annotation.FromTable) AggregationStorePermissionExecutor(com.yahoo.elide.core.security.executors.AggregationStorePermissionExecutor) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Objects(java.util.Objects) List(java.util.List) ReadPermission(com.yahoo.elide.annotation.ReadPermission) Builder(lombok.Builder) DataStore(com.yahoo.elide.core.datastore.DataStore) Type(com.yahoo.elide.core.type.Type) TimeDimension(com.yahoo.elide.datastores.aggregation.metadata.models.TimeDimension) Annotation(java.lang.annotation.Annotation) Table(com.yahoo.elide.datastores.aggregation.metadata.models.Table) QueryLogger(com.yahoo.elide.datastores.aggregation.core.QueryLogger) FromTable(com.yahoo.elide.datastores.aggregation.queryengines.sql.annotation.FromTable) Table(com.yahoo.elide.datastores.aggregation.metadata.models.Table) Column(com.yahoo.elide.datastores.aggregation.metadata.models.Column) ArgumentDefinition(com.yahoo.elide.datastores.aggregation.metadata.models.ArgumentDefinition) TimeDimension(com.yahoo.elide.datastores.aggregation.metadata.models.TimeDimension) ArgumentType(com.yahoo.elide.core.dictionary.ArgumentType)

Example 25 with Type

use of com.yahoo.elide.core.type.Type in project elide by yahoo.

the class MetaDataStore method getNamespace.

/**
 * Get a namespace object.
 *
 * @param modelType the model type
 * @return the namespace
 */
public Namespace getNamespace(Type<?> modelType) {
    String apiVersionName = EntityDictionary.getModelVersion(modelType);
    Include include = (Include) EntityDictionary.getFirstPackageAnnotation(modelType, Arrays.asList(Include.class));
    String namespaceName;
    if (include != null && !include.name().isEmpty()) {
        namespaceName = include.name();
    } else {
        namespaceName = DEFAULT;
    }
    return namespaces.stream().filter(namespace -> namespace.getName().equals(namespaceName)).filter(namespace -> namespace.getVersion().equals(apiVersionName)).findFirst().orElse(null);
}
Also used : HashMapDataStore(com.yahoo.elide.core.datastore.inmemory.HashMapDataStore) Arrays(java.util.Arrays) Path(com.yahoo.elide.core.Path) Getter(lombok.Getter) IS_FIELD_HIDDEN(com.yahoo.elide.datastores.aggregation.AggregationDataStore.IS_FIELD_HIDDEN) Include(com.yahoo.elide.annotation.Include) Dimension(com.yahoo.elide.datastores.aggregation.metadata.models.Dimension) HashMap(java.util.HashMap) Function(java.util.function.Function) HashSet(java.util.HashSet) DuplicateMappingException(com.yahoo.elide.core.exceptions.DuplicateMappingException) NamespacePackage(com.yahoo.elide.datastores.aggregation.dynamic.NamespacePackage) Pair(org.apache.commons.lang3.tuple.Pair) DEFAULT_NAMESPACE(com.yahoo.elide.datastores.aggregation.dynamic.NamespacePackage.DEFAULT_NAMESPACE) TableType(com.yahoo.elide.datastores.aggregation.dynamic.TableType) Namespace(com.yahoo.elide.datastores.aggregation.metadata.models.Namespace) ClassScanner(com.yahoo.elide.core.utils.ClassScanner) Map(java.util.Map) Column(com.yahoo.elide.datastores.aggregation.metadata.models.Column) NO_VERSION(com.yahoo.elide.core.dictionary.EntityDictionary.NO_VERSION) InternalServerErrorException(com.yahoo.elide.core.exceptions.InternalServerErrorException) AggregationDataStore(com.yahoo.elide.datastores.aggregation.AggregationDataStore) Entity(javax.persistence.Entity) ApiVersion(com.yahoo.elide.annotation.ApiVersion) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) TableSource(com.yahoo.elide.datastores.aggregation.metadata.models.TableSource) DEFAULT(com.yahoo.elide.datastores.aggregation.dynamic.NamespacePackage.DEFAULT) FromSubquery(com.yahoo.elide.datastores.aggregation.queryengines.sql.annotation.FromSubquery) Collection(java.util.Collection) ArgumentDefinition(com.yahoo.elide.datastores.aggregation.metadata.models.ArgumentDefinition) TimeDimensionGrain(com.yahoo.elide.datastores.aggregation.metadata.models.TimeDimensionGrain) Set(java.util.Set) FromTable(com.yahoo.elide.datastores.aggregation.queryengines.sql.annotation.FromTable) Subselect(org.hibernate.annotations.Subselect) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) List(java.util.List) Versioned(com.yahoo.elide.datastores.aggregation.metadata.models.Versioned) TypeHelper.getClassType(com.yahoo.elide.core.utils.TypeHelper.getClassType) DataStore(com.yahoo.elide.core.datastore.DataStore) Type(com.yahoo.elide.core.type.Type) TimeDimension(com.yahoo.elide.datastores.aggregation.metadata.models.TimeDimension) Annotation(java.lang.annotation.Annotation) Table(com.yahoo.elide.datastores.aggregation.metadata.models.Table) EMPTY(com.yahoo.elide.datastores.aggregation.dynamic.NamespacePackage.EMPTY) MetricFormula(com.yahoo.elide.datastores.aggregation.annotation.MetricFormula) Metric(com.yahoo.elide.datastores.aggregation.metadata.models.Metric) Include(com.yahoo.elide.annotation.Include)

Aggregations

Type (com.yahoo.elide.core.type.Type)35 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)22 Set (java.util.Set)17 List (java.util.List)16 Map (java.util.Map)16 ClassType (com.yahoo.elide.core.type.ClassType)15 Function (java.util.function.Function)14 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)13 Annotation (java.lang.annotation.Annotation)12 Collectors (java.util.stream.Collectors)12 Collection (java.util.Collection)11 ReadPermission (com.yahoo.elide.annotation.ReadPermission)10 ArrayList (java.util.ArrayList)10 HashSet (java.util.HashSet)10 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)9 Optional (java.util.Optional)9 RequestScope (com.yahoo.elide.core.RequestScope)8 Objects (java.util.Objects)8 Path (com.yahoo.elide.core.Path)7 RelationshipType (com.yahoo.elide.core.dictionary.RelationshipType)7