Search in sources :

Example 6 with Property

use of org.qi4j.api.property.Property in project qi4j-sdk by Qi4j.

the class AbstractSQLQuerying method modifyFromClauseAndWhereClauseToGetValue.

// TODO refactor this monster of a method to something more understandable
protected Integer modifyFromClauseAndWhereClauseToGetValue(final QualifiedName qName, Object value, final Specification<Composite> predicate, final Boolean negationActive, final Integer currentTableIndex, final ModifiableInt maxTableIndex, final String columnName, final String collectionPath, final SQLVendor vendor, final BooleanBuilder whereClause, final BooleanBuilder afterWhere, final TableReferenceBuilder fromClause, final GroupByBuilder groupBy, final BooleanBuilder having, final List<QNameJoin> qNameJoins, Map<String, Object> variables, final List<Object> values, final List<Integer> valueSQLTypes) {
    if (value instanceof Variable) {
        value = variables.get(((Variable) value).variableName());
    }
    final String schemaName = this._state.schemaName().get();
    Integer result = 1;
    final BooleanFactory b = vendor.getBooleanFactory();
    final LiteralFactory l = vendor.getLiteralFactory();
    final ColumnsFactory c = vendor.getColumnsFactory();
    final QueryFactory q = vendor.getQueryFactory();
    final TableReferenceFactory t = vendor.getTableReferenceFactory();
    if (value instanceof Collection<?>) {
        // Collection
        Integer collectionIndex = 0;
        Boolean collectionIsSet = value instanceof Set<?>;
        Boolean topLevel = collectionPath.equals(DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME);
        String collTable = TABLE_NAME_PREFIX + currentTableIndex;
        String collCol = DBNames.QNAME_TABLE_COLLECTION_PATH_COLUMN_NAME;
        ColumnReferenceByName collColExp = c.colName(collTable, collCol);
        BooleanBuilder collectionCondition = b.booleanBuilder();
        if (topLevel && negationActive) {
            afterWhere.and(b.booleanBuilder(b.neq(collColExp, l.s(DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME))).or(b.isNull(collColExp)).createExpression());
        }
        Integer totalItemsProcessed = 0;
        for (Object item : (Collection<?>) value) {
            String path = collectionPath + DBNames.QNAME_TABLE_COLLECTION_PATH_SEPARATOR + (collectionIsSet ? "*{1,}" : collectionIndex);
            Boolean isCollection = (item instanceof Collection<?>);
            BooleanBuilder newWhere = b.booleanBuilder();
            if (!isCollection) {
                newWhere.reset(b.regexp(collColExp, l.s(path)));
            }
            totalItemsProcessed = totalItemsProcessed + modifyFromClauseAndWhereClauseToGetValue(qName, item, predicate, negationActive, currentTableIndex, maxTableIndex, columnName, path, vendor, newWhere, afterWhere, fromClause, groupBy, having, qNameJoins, variables, values, valueSQLTypes);
            ++collectionIndex;
            collectionCondition.or(newWhere.createExpression());
        }
        result = totalItemsProcessed;
        if (topLevel) {
            if (totalItemsProcessed == 0) {
                collectionCondition.and(b.isNotNull(collColExp)).and(b.eq(collColExp, l.l(DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME)));
            } else if (!negationActive) {
                groupBy.addGroupingElements(q.groupingElement(c.colName(TABLE_NAME_PREFIX + currentTableIndex, DBNames.ENTITY_TABLE_PK_COLUMN_NAME)));
                having.and(b.eq(l.func(SQLFunctions.COUNT, c.colName(TABLE_NAME_PREFIX + currentTableIndex, DBNames.QNAME_TABLE_VALUE_COLUMN_NAME)), l.n(totalItemsProcessed)));
            }
        }
        whereClause.and(collectionCondition.createExpression());
    } else if (value instanceof ValueComposite) {
        // @formatter:off
        for (Property<?> property : Qi4j.FUNCTION_COMPOSITE_INSTANCE_OF.map((ValueComposite) value).state().properties()) {
            Boolean qNameJoinDone = false;
            Integer sourceIndex = maxTableIndex.getInt();
            Integer targetIndex = sourceIndex + 1;
            for (QNameJoin join : qNameJoins) {
                if (join.getSourceQName().equals(qName)) {
                    sourceIndex = join.getSourceTableIndex();
                    if (join.getTargetQName().equals(spi.propertyDescriptorFor(property).qualifiedName())) {
                        // This join has already been done once
                        qNameJoinDone = true;
                        targetIndex = join.getTargetTableIndex();
                        break;
                    }
                }
            }
            if (!qNameJoinDone) {
                // @formatter:off
                QNameInfo info = _state.qNameInfos().get().get(spi.propertyDescriptorFor(property).qualifiedName());
                String prevTableName = TABLE_NAME_PREFIX + sourceIndex;
                String nextTableName = TABLE_NAME_PREFIX + targetIndex;
                fromClause.addQualifiedJoin(JoinType.LEFT_OUTER, t.table(t.tableName(schemaName, info.getTableName()), t.tableAlias(TABLE_NAME_PREFIX + targetIndex)), t.jc(b.booleanBuilder(b.eq(c.colName(prevTableName, DBNames.ALL_QNAMES_TABLE_PK_COLUMN_NAME), c.colName(nextTableName, DBNames.QNAME_TABLE_PARENT_QNAME_COLUMN_NAME))).and(b.eq(c.colName(prevTableName, DBNames.ENTITY_TABLE_PK_COLUMN_NAME), c.colName(nextTableName, DBNames.ENTITY_TABLE_PK_COLUMN_NAME))).createExpression()));
                // @formatter:on
                qNameJoins.add(new QNameJoin(qName, spi.propertyDescriptorFor(property).qualifiedName(), sourceIndex, targetIndex));
                maxTableIndex.setInt(maxTableIndex.getInt() + 1);
            }
            modifyFromClauseAndWhereClauseToGetValue(spi.propertyDescriptorFor(property).qualifiedName(), property.get(), predicate, negationActive, targetIndex, maxTableIndex, columnName, collectionPath, vendor, whereClause, afterWhere, fromClause, groupBy, having, qNameJoins, variables, values, valueSQLTypes);
        }
    // @formatter:on
    } else {
        // Primitive
        ColumnReferenceByName valueCol = c.colName(TABLE_NAME_PREFIX + currentTableIndex, columnName);
        if (value == null) {
            whereClause.and(b.isNull(valueCol));
        } else {
            Object dbValue = value;
            if (Enum.class.isAssignableFrom(value.getClass())) {
                dbValue = this._state.enumPKs().get().get(value.getClass().getName());
            }
            whereClause.and(b.and(b.isNotNull(valueCol), this.getOperator(predicate).getExpression(b, valueCol, l.param())));
            values.add(dbValue);
            valueSQLTypes.add(_typeHelper.getSQLType(value));
            LOGGER.info(TABLE_NAME_PREFIX + currentTableIndex + "." + columnName + " is " + dbValue);
        }
    }
    return result;
}
Also used : QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) Variable(org.qi4j.api.query.grammar.Variable) ResultSet(java.sql.ResultSet) Set(java.util.Set) ColumnsFactory(org.sql.generation.api.grammar.factories.ColumnsFactory) ValueComposite(org.qi4j.api.value.ValueComposite) BooleanFactory(org.sql.generation.api.grammar.factories.BooleanFactory) LiteralFactory(org.sql.generation.api.grammar.factories.LiteralFactory) TableReferenceFactory(org.sql.generation.api.grammar.factories.TableReferenceFactory) ColumnReferenceByName(org.sql.generation.api.grammar.query.ColumnReferenceByName) BooleanBuilder(org.sql.generation.api.grammar.builders.booleans.BooleanBuilder) Collection(java.util.Collection) AccessibleObject(java.lang.reflect.AccessibleObject) QNameInfo(org.qi4j.index.sql.support.common.QNameInfo) Property(org.qi4j.api.property.Property)

Example 7 with Property

use of org.qi4j.api.property.Property in project qi4j-sdk by Qi4j.

the class Qi4jPropertyAccessor method setProperty.

@Override
@SuppressWarnings("unchecked")
public final void setProperty(Map aContext, Object aTarget, Object aPropertyName, Object aPropertyValue) throws OgnlException {
    String fieldName = aPropertyName.toString();
    Object qi4jField = getQi4jField(aContext, aTarget, fieldName);
    if (qi4jField != null) {
        Class<?> memberClass = qi4jField.getClass();
        if (Property.class.isAssignableFrom(memberClass)) {
            Property property = (Property) qi4jField;
            OgnlContext ognlContext = (OgnlContext) aContext;
            Class<?> propertyType = (Class) api.propertyDescriptorFor(property).type();
            Object convertedValue = getConvertedType(ognlContext, aTarget, null, fieldName, aPropertyValue, propertyType);
            try {
                property.set(convertedValue);
            } catch (ConstraintViolationException e) {
                Collection<ConstraintViolation> violations = e.constraintViolations();
                handleConstraintViolation(aContext, aTarget, fieldName, convertedValue, violations);
            }
            return;
        } else if (Association.class.isAssignableFrom(memberClass)) {
            Association association = (Association) qi4jField;
            OgnlContext ognlContext = (OgnlContext) aContext;
            Class<?> associationType = (Class) api.associationDescriptorFor(association).type();
            Object convertedValue = getConvertedType(ognlContext, aTarget, null, fieldName, aPropertyValue, associationType);
            if (convertedValue == OgnlRuntime.NoConversionPossible) {
                throw new OgnlException("Could not convert value to association type");
            }
            try {
                association.set(convertedValue);
            } catch (ConstraintViolationException e) {
                Collection<ConstraintViolation> violations = e.constraintViolations();
                handleConstraintViolation(aContext, aTarget, fieldName, aPropertyValue, violations);
            }
            return;
        } else if (ManyAssociation.class.isAssignableFrom(memberClass)) {
            throw new OgnlException("Setting many association [" + fieldName + "] is impossible.");
        } else if (NamedAssociation.class.isAssignableFrom(memberClass)) {
            throw new OgnlException("Setting named association [" + fieldName + "] is impossible.");
        }
    }
    super.setProperty(aContext, aTarget, aPropertyName, aPropertyValue);
}
Also used : NamedAssociation(org.qi4j.api.association.NamedAssociation) OgnlContext(ognl.OgnlContext) OgnlException(ognl.OgnlException) ManyAssociation(org.qi4j.api.association.ManyAssociation) Association(org.qi4j.api.association.Association) NamedAssociation(org.qi4j.api.association.NamedAssociation) ConstraintViolation(org.qi4j.api.constraint.ConstraintViolation) ConstraintViolationException(org.qi4j.api.constraint.ConstraintViolationException) Collection(java.util.Collection) Property(org.qi4j.api.property.Property)

Example 8 with Property

use of org.qi4j.api.property.Property in project qi4j-sdk by Qi4j.

the class StateInvocationHandler method use.

public void use(T actualData) {
    for (Map.Entry<Method, BoundProperty> entry : properties.entrySet()) {
        BoundProperty bound = entry.getValue();
        Property actualProperty = null;
        if (actualData != null) {
            Method method = entry.getKey();
            try {
                actualProperty = (Property) method.invoke(actualData);
            } catch (IllegalAccessException | InvocationTargetException e) {
                //TODO: Auto-generated, need attention.
                e.printStackTrace();
            }
        }
        bound.use(actualProperty);
    }
}
Also used : Method(java.lang.reflect.Method) Map(java.util.Map) HashMap(java.util.HashMap) Property(org.qi4j.api.property.Property) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 9 with Property

use of org.qi4j.api.property.Property in project qi4j-sdk by Qi4j.

the class StateFinder method doFilter.

/**
     * Do the filter for method return type (Property, Association, ManyAssociation, NamedAssociation)
     * by removing the entry from the list if not the above.
     *
     * @param list list of CompositeMethodDetailDescriptor
     */
private void doFilter(List<CompositeMethodDetailDescriptor> list) {
    if (list.isEmpty()) {
        return;
    }
    Iterator<CompositeMethodDetailDescriptor> iter = list.iterator();
    while (iter.hasNext()) {
        CompositeMethodDetailDescriptor descriptor = iter.next();
        Method method = descriptor.descriptor().method();
        if (Property.class.isAssignableFrom(method.getReturnType()) || Association.class.isAssignableFrom(method.getReturnType()) || ManyAssociation.class.isAssignableFrom(method.getReturnType()) || NamedAssociation.class.isAssignableFrom(method.getReturnType())) {
            continue;
        }
        iter.remove();
    }
}
Also used : Association(org.qi4j.api.association.Association) ManyAssociation(org.qi4j.api.association.ManyAssociation) NamedAssociation(org.qi4j.api.association.NamedAssociation) CompositeMethodDetailDescriptor(org.qi4j.tools.model.descriptor.CompositeMethodDetailDescriptor) NamedAssociation(org.qi4j.api.association.NamedAssociation) Method(java.lang.reflect.Method) Property(org.qi4j.api.property.Property)

Example 10 with Property

use of org.qi4j.api.property.Property in project qi4j-sdk by Qi4j.

the class ServiceModel method newInstance.

public ServiceInstance newInstance(final ModuleInstance module) {
    Object[] mixins = mixinsModel.newMixinHolder();
    Map<AccessibleObject, Property<?>> properties = new HashMap<>();
    for (PropertyModel propertyModel : stateModel.properties()) {
        Object initialValue = propertyModel.initialValue(module);
        if (propertyModel.accessor().equals(identityMethod)) {
            initialValue = identity;
        }
        Property<?> property = new PropertyInstance<>(propertyModel, initialValue);
        properties.put(propertyModel.accessor(), property);
    }
    TransientStateInstance state = new TransientStateInstance(properties);
    ServiceInstance compositeInstance = new ServiceInstance(this, module, mixins, state);
    // Instantiate all mixins
    int i = 0;
    UsesInstance uses = UsesInstance.EMPTY_USES.use(this);
    InjectionContext injectionContext = new InjectionContext(compositeInstance, uses, state);
    for (MixinModel mixinModel : mixinsModel.mixinModels()) {
        mixins[i++] = mixinModel.newInstance(injectionContext);
    }
    return compositeInstance;
}
Also used : UsesInstance(org.qi4j.runtime.composite.UsesInstance) MixinModel(org.qi4j.runtime.composite.MixinModel) HashMap(java.util.HashMap) PropertyModel(org.qi4j.runtime.property.PropertyModel) PropertyInstance(org.qi4j.runtime.property.PropertyInstance) InjectionContext(org.qi4j.runtime.injection.InjectionContext) TransientStateInstance(org.qi4j.runtime.composite.TransientStateInstance) AccessibleObject(java.lang.reflect.AccessibleObject) AccessibleObject(java.lang.reflect.AccessibleObject) Property(org.qi4j.api.property.Property)

Aggregations

Property (org.qi4j.api.property.Property)11 AccessibleObject (java.lang.reflect.AccessibleObject)5 Method (java.lang.reflect.Method)4 HashMap (java.util.HashMap)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Association (org.qi4j.api.association.Association)3 ManyAssociation (org.qi4j.api.association.ManyAssociation)3 NamedAssociation (org.qi4j.api.association.NamedAssociation)3 PropertyModel (org.qi4j.runtime.property.PropertyModel)3 Collection (java.util.Collection)2 Map (java.util.Map)2 TransientStateInstance (org.qi4j.runtime.composite.TransientStateInstance)2 PropertyInstance (org.qi4j.runtime.property.PropertyInstance)2 BuilderEntityState (org.qi4j.runtime.unitofwork.BuilderEntityState)2 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 ResultSet (java.sql.ResultSet)1 Properties (java.util.Properties)1 Set (java.util.Set)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1