Search in sources :

Example 31 with SiddhiAppCreationException

use of io.siddhi.core.exception.SiddhiAppCreationException in project siddhi by wso2.

the class ExpressionParser method parseExpression.

/**
 * Parse the given expression and create the appropriate Executor by recursively traversing the expression
 *
 * @param expression                 Expression to be parsed
 * @param metaEvent                  Meta Event
 * @param currentState               Current state number
 * @param tableMap                   Event Table Map
 * @param executorList               List to hold VariableExpressionExecutors to update after query parsing
 * @param groupBy                    is for groupBy expression
 * @param defaultStreamEventIndex    Default StreamEvent Index
 * @param processingMode             processing mode of the query
 * @param outputExpectsExpiredEvents is expired events sent as output
 * @param siddhiQueryContext         current siddhi query context
 * @return ExpressionExecutor
 */
public static ExpressionExecutor parseExpression(Expression expression, MetaComplexEvent metaEvent, int currentState, Map<String, Table> tableMap, List<VariableExpressionExecutor> executorList, boolean groupBy, int defaultStreamEventIndex, ProcessingMode processingMode, boolean outputExpectsExpiredEvents, SiddhiQueryContext siddhiQueryContext) {
    try {
        if (expression instanceof And) {
            return new AndConditionExpressionExecutor(parseExpression(((And) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((And) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        } else if (expression instanceof Or) {
            return new OrConditionExpressionExecutor(parseExpression(((Or) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Or) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        } else if (expression instanceof Not) {
            return new NotConditionExpressionExecutor(parseExpression(((Not) expression).getExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        } else if (expression instanceof Compare) {
            if (((Compare) expression).getOperator() == Compare.Operator.EQUAL) {
                Expression leftExpression = ((Compare) expression).getLeftExpression();
                Expression rightExpression = ((Compare) expression).getRightExpression();
                ExpressionExecutor leftExpressionExecutor = parseExpression(leftExpression, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                ExpressionExecutor rightExpressionExecutor = parseExpression(rightExpression, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                return parseEqualCompare(leftExpressionExecutor, rightExpressionExecutor);
            } else if (((Compare) expression).getOperator() == Compare.Operator.NOT_EQUAL) {
                return parseNotEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.GREATER_THAN) {
                return parseGreaterThanCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.GREATER_THAN_EQUAL) {
                return parseGreaterThanEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.LESS_THAN) {
                return parseLessThanCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.LESS_THAN_EQUAL) {
                return parseLessThanEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            }
        } else if (expression instanceof Constant) {
            if (expression instanceof BoolConstant) {
                return new ConstantExpressionExecutor(((BoolConstant) expression).getValue(), Attribute.Type.BOOL);
            } else if (expression instanceof StringConstant) {
                return new ConstantExpressionExecutor(((StringConstant) expression).getValue(), Attribute.Type.STRING);
            } else if (expression instanceof IntConstant) {
                return new ConstantExpressionExecutor(((IntConstant) expression).getValue(), Attribute.Type.INT);
            } else if (expression instanceof LongConstant) {
                return new ConstantExpressionExecutor(((LongConstant) expression).getValue(), Attribute.Type.LONG);
            } else if (expression instanceof FloatConstant) {
                return new ConstantExpressionExecutor(((FloatConstant) expression).getValue(), Attribute.Type.FLOAT);
            } else if (expression instanceof DoubleConstant) {
                return new ConstantExpressionExecutor(((DoubleConstant) expression).getValue(), Attribute.Type.DOUBLE);
            }
        } else if (expression instanceof Variable) {
            return parseVariable((Variable) expression, metaEvent, currentState, executorList, defaultStreamEventIndex, siddhiQueryContext);
        } else if (expression instanceof Multiply) {
            ExpressionExecutor left = parseExpression(((Multiply) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Multiply) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new MultiplyExpressionExecutorInt(left, right);
                case LONG:
                    return new MultiplyExpressionExecutorLong(left, right);
                case FLOAT:
                    return new MultiplyExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new MultiplyExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Add) {
            ExpressionExecutor left = parseExpression(((Add) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Add) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new AddExpressionExecutorInt(left, right);
                case LONG:
                    return new AddExpressionExecutorLong(left, right);
                case FLOAT:
                    return new AddExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new AddExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Subtract) {
            ExpressionExecutor left = parseExpression(((Subtract) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Subtract) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new SubtractExpressionExecutorInt(left, right);
                case LONG:
                    return new SubtractExpressionExecutorLong(left, right);
                case FLOAT:
                    return new SubtractExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new SubtractExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Mod) {
            ExpressionExecutor left = parseExpression(((Mod) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Mod) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new ModExpressionExecutorInt(left, right);
                case LONG:
                    return new ModExpressionExecutorLong(left, right);
                case FLOAT:
                    return new ModExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new ModExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Divide) {
            ExpressionExecutor left = parseExpression(((Divide) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Divide) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new DivideExpressionExecutorInt(left, right);
                case LONG:
                    return new DivideExpressionExecutorLong(left, right);
                case FLOAT:
                    return new DivideExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new DivideExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof AttributeFunction) {
            // extensions
            Object executor;
            try {
                if ((siddhiQueryContext.getSiddhiAppContext().isFunctionExist(((AttributeFunction) expression).getName())) && (((AttributeFunction) expression).getNamespace()).isEmpty()) {
                    executor = new ScriptFunctionExecutor(((AttributeFunction) expression).getName());
                } else {
                    executor = SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, FunctionExecutorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                }
            } catch (SiddhiAppCreationException ex) {
                try {
                    executor = SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, AttributeAggregatorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                } catch (SiddhiAppCreationException e) {
                    throw new ExtensionNotFoundException("'" + ((AttributeFunction) expression).getName() + "' is" + " neither a function extension nor an aggregated attribute extension", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                }
            }
            ConfigReader configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader(((AttributeFunction) expression).getNamespace(), ((AttributeFunction) expression).getName());
            if (executor instanceof FunctionExecutor) {
                FunctionExecutor expressionExecutor = (FunctionExecutor) executor;
                Expression[] innerExpressions = ((AttributeFunction) expression).getParameters();
                ExpressionExecutor[] innerExpressionExecutors = parseInnerExpression(innerExpressions, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                expressionExecutor.initExecutor(innerExpressionExecutors, processingMode, configReader, groupBy, siddhiQueryContext);
                if (expressionExecutor.getReturnType() == Attribute.Type.BOOL) {
                    return new BoolConditionExpressionExecutor(expressionExecutor);
                }
                return expressionExecutor;
            } else {
                AttributeAggregatorExecutor attributeAggregatorExecutor = (AttributeAggregatorExecutor) executor;
                Expression[] innerExpressions = ((AttributeFunction) expression).getParameters();
                ExpressionExecutor[] innerExpressionExecutors = parseInnerExpression(innerExpressions, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                attributeAggregatorExecutor.initAggregator(innerExpressionExecutors, processingMode, outputExpectsExpiredEvents, configReader, groupBy, siddhiQueryContext);
                // AbstractAggregationAttributeExecutor aggregationAttributeProcessor;
                // if (groupBy) {
                // aggregationAttributeProcessor = new GroupByAggregationAttributeExecutor(attributeAggregatorExecutor,
                // innerExpressionExecutors, configReader, siddhiQueryContext);
                // } else {
                // aggregationAttributeProcessor = new AggregationAttributeExecutor(attributeAggregatorExecutor,
                // innerExpressionExecutors, siddhiQueryContext);
                // }
                SelectorParser.getContainsAggregatorThreadLocal().set("true");
                return attributeAggregatorExecutor;
            }
        } else if (expression instanceof In) {
            Table table = tableMap.get(((In) expression).getSourceId());
            MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(metaEvent, defaultStreamEventIndex, table.getTableDefinition(), defaultStreamEventIndex);
            CompiledCondition compiledCondition = table.compileCondition(((In) expression).getExpression(), matchingMetaInfoHolder, executorList, tableMap, siddhiQueryContext);
            return new InConditionExpressionExecutor(table, compiledCondition, matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents().length, metaEvent instanceof StateEvent, 0);
        } else if (expression instanceof IsNull) {
            IsNull isNull = (IsNull) expression;
            if (isNull.getExpression() != null) {
                ExpressionExecutor innerExpressionExecutor = parseExpression(isNull.getExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                return new IsNullConditionExpressionExecutor(innerExpressionExecutor);
            } else {
                String streamId = isNull.getStreamId();
                Integer streamIndex = isNull.getStreamIndex();
                if (metaEvent instanceof MetaStateEvent) {
                    int[] eventPosition = new int[2];
                    if (streamIndex != null) {
                        if (streamIndex <= SiddhiConstants.LAST) {
                            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex + 1;
                        } else {
                            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex;
                        }
                    } else {
                        eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = defaultStreamEventIndex;
                    }
                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = SiddhiConstants.UNKNOWN_STATE;
                    MetaStateEvent metaStateEvent = (MetaStateEvent) metaEvent;
                    if (streamId == null) {
                        throw new SiddhiAppCreationException("IsNull does not support streamId being null", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                    } else {
                        MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
                        for (int i = 0, metaStreamEventsLength = metaStreamEvents.length; i < metaStreamEventsLength; i++) {
                            MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                            AbstractDefinition definition = metaStreamEvent.getLastInputDefinition();
                            if (metaStreamEvent.getInputReferenceId() == null) {
                                if (definition.getId().equals(streamId)) {
                                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                                    break;
                                }
                            } else {
                                if (metaStreamEvent.getInputReferenceId().equals(streamId)) {
                                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                                    if (currentState > -1 && metaStreamEvents[currentState].getInputReferenceId() != null && streamIndex != null && streamIndex <= SiddhiConstants.LAST) {
                                        if (streamId.equals(metaStreamEvents[currentState].getInputReferenceId())) {
                                            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    return new IsNullStreamConditionExpressionExecutor(eventPosition);
                } else {
                    return new IsNullStreamConditionExpressionExecutor(null);
                }
            }
        }
        throw new UnsupportedOperationException(expression.toString() + " not supported!");
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, expression, siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext);
        throw t;
    }
}
Also used : Add(io.siddhi.query.api.expression.math.Add) Or(io.siddhi.query.api.expression.condition.Or) DivideExpressionExecutorFloat(io.siddhi.core.executor.math.divide.DivideExpressionExecutorFloat) ModExpressionExecutorDouble(io.siddhi.core.executor.math.mod.ModExpressionExecutorDouble) ModExpressionExecutorInt(io.siddhi.core.executor.math.mod.ModExpressionExecutorInt) EqualCompareConditionExpressionExecutorStringString(io.siddhi.core.executor.condition.compare.equal.EqualCompareConditionExpressionExecutorStringString) NotEqualCompareConditionExpressionExecutorStringString(io.siddhi.core.executor.condition.compare.notequal.NotEqualCompareConditionExpressionExecutorStringString) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) Divide(io.siddhi.query.api.expression.math.Divide) MultiplyExpressionExecutorLong(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorLong) AddExpressionExecutorLong(io.siddhi.core.executor.math.add.AddExpressionExecutorLong) Multiply(io.siddhi.query.api.expression.math.Multiply) AddExpressionExecutorInt(io.siddhi.core.executor.math.add.AddExpressionExecutorInt) Compare(io.siddhi.query.api.expression.condition.Compare) DivideExpressionExecutorDouble(io.siddhi.core.executor.math.divide.DivideExpressionExecutorDouble) ExtensionNotFoundException(io.siddhi.core.exception.ExtensionNotFoundException) FunctionExecutor(io.siddhi.core.executor.function.FunctionExecutor) EventVariableFunctionExecutor(io.siddhi.core.executor.EventVariableFunctionExecutor) MultiValueVariableFunctionExecutor(io.siddhi.core.executor.MultiValueVariableFunctionExecutor) ScriptFunctionExecutor(io.siddhi.core.executor.function.ScriptFunctionExecutor) AddExpressionExecutorFloat(io.siddhi.core.executor.math.add.AddExpressionExecutorFloat) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) Not(io.siddhi.query.api.expression.condition.Not) MultiplyExpressionExecutorFloat(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorFloat) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) And(io.siddhi.query.api.expression.condition.And) MatchingMetaInfoHolder(io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) SubtractExpressionExecutorLong(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorLong) IsNullStreamConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) Subtract(io.siddhi.query.api.expression.math.Subtract) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) Variable(io.siddhi.query.api.expression.Variable) MultiplyExpressionExecutorDouble(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorDouble) Attribute(io.siddhi.query.api.definition.Attribute) In(io.siddhi.query.api.expression.condition.In) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) Constant(io.siddhi.query.api.expression.constant.Constant) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) ModExpressionExecutorLong(io.siddhi.core.executor.math.mod.ModExpressionExecutorLong) ScriptFunctionExecutor(io.siddhi.core.executor.function.ScriptFunctionExecutor) InConditionExpressionExecutor(io.siddhi.core.executor.condition.InConditionExpressionExecutor) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) AddExpressionExecutorDouble(io.siddhi.core.executor.math.add.AddExpressionExecutorDouble) AndConditionExpressionExecutor(io.siddhi.core.executor.condition.AndConditionExpressionExecutor) MultiplyExpressionExecutorInt(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorInt) IsNullConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) SubtractExpressionExecutorInt(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorInt) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) SubtractExpressionExecutorDouble(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorDouble) AttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.AttributeAggregatorExecutor) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Mod(io.siddhi.query.api.expression.math.Mod) Table(io.siddhi.core.table.Table) IsNullConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) NotConditionExpressionExecutor(io.siddhi.core.executor.condition.NotConditionExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) ConditionExpressionExecutor(io.siddhi.core.executor.condition.ConditionExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) OrConditionExpressionExecutor(io.siddhi.core.executor.condition.OrConditionExpressionExecutor) BoolConditionExpressionExecutor(io.siddhi.core.executor.condition.BoolConditionExpressionExecutor) InConditionExpressionExecutor(io.siddhi.core.executor.condition.InConditionExpressionExecutor) AndConditionExpressionExecutor(io.siddhi.core.executor.condition.AndConditionExpressionExecutor) IsNullStreamConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) ConfigReader(io.siddhi.core.util.config.ConfigReader) OrConditionExpressionExecutor(io.siddhi.core.executor.condition.OrConditionExpressionExecutor) DivideExpressionExecutorLong(io.siddhi.core.executor.math.divide.DivideExpressionExecutorLong) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) DivideExpressionExecutorInt(io.siddhi.core.executor.math.divide.DivideExpressionExecutorInt) SubtractExpressionExecutorFloat(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorFloat) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) Expression(io.siddhi.query.api.expression.Expression) NotConditionExpressionExecutor(io.siddhi.core.executor.condition.NotConditionExpressionExecutor) ModExpressionExecutorFloat(io.siddhi.core.executor.math.mod.ModExpressionExecutorFloat) StateEvent(io.siddhi.core.event.state.StateEvent) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) IsNull(io.siddhi.query.api.expression.condition.IsNull) BoolConditionExpressionExecutor(io.siddhi.core.executor.condition.BoolConditionExpressionExecutor)

Example 32 with SiddhiAppCreationException

use of io.siddhi.core.exception.SiddhiAppCreationException in project siddhi by wso2.

the class ExpressionParser method parseVariable.

/**
 * Parse and validate the given Siddhi variable and return a VariableExpressionExecutor
 *
 * @param variable           Variable to be parsed
 * @param metaEvent          Meta event used to collect execution info of stream associated with query
 * @param currentState       Current State Number
 * @param executorList       List to hold VariableExpressionExecutors to update after query parsing @return
 * @param siddhiQueryContext Siddhi Query Context
 * @return VariableExpressionExecutor representing given variable
 */
private static ExpressionExecutor parseVariable(Variable variable, MetaComplexEvent metaEvent, int currentState, List<VariableExpressionExecutor> executorList, int defaultStreamEventIndex, SiddhiQueryContext siddhiQueryContext) {
    String attributeName = variable.getAttributeName();
    int[] eventPosition = new int[2];
    if (variable.getStreamIndex() != null) {
        if (variable.getStreamIndex() <= SiddhiConstants.LAST) {
            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = variable.getStreamIndex() + 1;
        } else {
            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = variable.getStreamIndex();
        }
    } else {
        eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = defaultStreamEventIndex;
    }
    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = SiddhiConstants.UNKNOWN_STATE;
    if (metaEvent instanceof MetaStreamEvent) {
        MetaStreamEvent metaStreamEvent = (MetaStreamEvent) metaEvent;
        AbstractDefinition abstractDefinition;
        Attribute.Type type;
        if (currentState == SiddhiConstants.HAVING_STATE) {
            abstractDefinition = metaStreamEvent.getOutputStreamDefinition();
            type = abstractDefinition.getAttributeType(attributeName);
            eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = SiddhiConstants.HAVING_STATE;
        } else {
            abstractDefinition = metaStreamEvent.getLastInputDefinition();
            type = abstractDefinition.getAttributeType(attributeName);
            ((MetaStreamEvent) metaEvent).addData(new Attribute(attributeName, type));
        }
        if (variable.getStreamId() != null && !variable.getStreamId().equals(abstractDefinition.getId())) {
            throw new SiddhiAppCreationException("Id '" + variable.getStreamId() + "' not defined within the " + "current scope", variable, siddhiQueryContext.getSiddhiAppContext());
        }
        VariableExpressionExecutor variableExpressionExecutor = new VariableExpressionExecutor(new Attribute(attributeName, type), eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX], eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN]);
        if (((MetaStreamEvent) metaEvent).getEventType() != MetaStreamEvent.EventType.DEFAULT) {
            variableExpressionExecutor.getPosition()[SiddhiConstants.STREAM_ATTRIBUTE_TYPE_INDEX] = SiddhiConstants.OUTPUT_DATA_INDEX;
            variableExpressionExecutor.getPosition()[SiddhiConstants.STREAM_ATTRIBUTE_INDEX_IN_TYPE] = abstractDefinition.getAttributePosition(variableExpressionExecutor.getAttribute().getName());
        }
        if (executorList != null) {
            executorList.add(variableExpressionExecutor);
        }
        return variableExpressionExecutor;
    } else {
        MetaStateEvent metaStateEvent = (MetaStateEvent) metaEvent;
        Attribute.Type type = null;
        AbstractDefinition definition = null;
        String firstInput = null;
        boolean multiValue = false;
        if (variable.getStreamId() == null) {
            MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
            if (currentState == SiddhiConstants.HAVING_STATE) {
                definition = metaStateEvent.getOutputStreamDefinition();
                try {
                    type = definition.getAttributeType(attributeName);
                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = SiddhiConstants.HAVING_STATE;
                } catch (AttributeNotExistException e) {
                    currentState = SiddhiConstants.UNKNOWN_STATE;
                }
            }
            if (currentState == SiddhiConstants.UNKNOWN_STATE) {
                for (int i = 0; i < metaStreamEvents.length; i++) {
                    MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                    definition = metaStreamEvent.getLastInputDefinition();
                    if (type == null) {
                        try {
                            type = definition.getAttributeType(attributeName);
                            firstInput = "Input Stream: " + definition.getId() + " with " + "reference: " + metaStreamEvent.getInputReferenceId();
                            eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                        } catch (AttributeNotExistException e) {
                        // do nothing
                        }
                    } else {
                        try {
                            definition.getAttributeType(attributeName);
                            throw new SiddhiAppValidationException(firstInput + " and Input Stream: " + definition.getId() + " with " + "reference: " + metaStreamEvent.getInputReferenceId() + " contains attribute " + "with same" + " name '" + attributeName + "'");
                        } catch (AttributeNotExistException e) {
                        // do nothing as its expected
                        }
                    }
                }
            } else if (currentState >= 0) {
                MetaStreamEvent metaStreamEvent = metaStreamEvents[currentState];
                definition = metaStreamEvent.getLastInputDefinition();
                try {
                    type = definition.getAttributeType(attributeName);
                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = currentState;
                } catch (AttributeNotExistException e) {
                    ExpressionExecutor functionExecutor = constructEventExpressionExecutor(variable, currentState, siddhiQueryContext, eventPosition, metaStateEvent);
                    if (functionExecutor != null) {
                        return functionExecutor;
                    }
                    throw new SiddhiAppValidationException(e.getMessageWithOutContext() + " Input stream '" + definition.getId() + "' with reference '" + metaStreamEvent.getInputReferenceId() + "' for attribute '" + variable.getAttributeName() + "'", e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex());
                }
            }
        } else {
            MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
            for (int i = 0, metaStreamEventsLength = metaStreamEvents.length; i < metaStreamEventsLength; i++) {
                MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                definition = metaStreamEvent.getLastInputDefinition();
                if (metaStreamEvent.getInputReferenceId() == null) {
                    if (definition.getId().equals(variable.getStreamId())) {
                        type = definition.getAttributeType(attributeName);
                        eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                        break;
                    }
                } else {
                    if (metaStreamEvent.getInputReferenceId().equals(variable.getStreamId())) {
                        type = definition.getAttributeType(attributeName);
                        eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                        if (currentState > -1 && metaStreamEvents[currentState].getInputReferenceId() != null && variable.getStreamIndex() != null && variable.getStreamIndex() <= SiddhiConstants.LAST) {
                            if (variable.getStreamId().equals(metaStreamEvents[currentState].getInputReferenceId())) {
                                eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = variable.getStreamIndex();
                            }
                        } else if (currentState == SiddhiConstants.UNKNOWN_STATE && variable.getStreamIndex() == null) {
                            multiValue = metaStreamEvent.isMultiValue();
                        }
                        break;
                    }
                }
            }
        }
        if (eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] == SiddhiConstants.UNKNOWN_STATE) {
            if (variable.getStreamId() == null) {
                ExpressionExecutor functionExecutor = constructEventExpressionExecutor(variable, currentState, siddhiQueryContext, eventPosition, metaStateEvent);
                if (functionExecutor != null) {
                    return functionExecutor;
                }
                throw new SiddhiAppValidationException("No matching stream reference found for attribute '" + variable.getAttributeName() + "'");
            } else {
                throw new SiddhiAppValidationException("Stream with reference '" + variable.getStreamId() + "' not found for attribute '" + variable.getAttributeName() + "'");
            }
        }
        VariableExpressionExecutor variableExpressionExecutor = new VariableExpressionExecutor(new Attribute(attributeName, type), eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX], eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN]);
        if (eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] != SiddhiConstants.HAVING_STATE) {
            MetaStreamEvent metaStreamEvent = ((MetaStateEvent) metaEvent).getMetaStreamEvent(eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX]);
            if (metaStreamEvent.getEventType() != MetaStreamEvent.EventType.DEFAULT) {
                variableExpressionExecutor.getPosition()[SiddhiConstants.STREAM_ATTRIBUTE_TYPE_INDEX] = SiddhiConstants.OUTPUT_DATA_INDEX;
                variableExpressionExecutor.getPosition()[SiddhiConstants.STREAM_ATTRIBUTE_INDEX_IN_TYPE] = metaStreamEvent.getLastInputDefinition().getAttributePosition(variableExpressionExecutor.getAttribute().getName());
                for (Attribute attribute : metaStreamEvent.getLastInputDefinition().getAttributeList()) {
                    metaStreamEvent.addOutputData(new Attribute(attribute.getName(), attribute.getType()));
                }
            }
            metaStreamEvent.addData(new Attribute(attributeName, type));
        }
        if (executorList != null) {
            executorList.add(variableExpressionExecutor);
        }
        if (multiValue) {
            FunctionExecutor functionExecutor = new MultiValueVariableFunctionExecutor();
            ExpressionExecutor[] innerExpressionExecutors = new ExpressionExecutor[] { variableExpressionExecutor };
            functionExecutor.initExecutor(innerExpressionExecutors, ProcessingMode.BATCH, null, false, siddhiQueryContext);
            return functionExecutor;
        }
        return variableExpressionExecutor;
    }
}
Also used : IsNullConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) NotConditionExpressionExecutor(io.siddhi.core.executor.condition.NotConditionExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) ConditionExpressionExecutor(io.siddhi.core.executor.condition.ConditionExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) OrConditionExpressionExecutor(io.siddhi.core.executor.condition.OrConditionExpressionExecutor) BoolConditionExpressionExecutor(io.siddhi.core.executor.condition.BoolConditionExpressionExecutor) InConditionExpressionExecutor(io.siddhi.core.executor.condition.InConditionExpressionExecutor) AndConditionExpressionExecutor(io.siddhi.core.executor.condition.AndConditionExpressionExecutor) IsNullStreamConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) Attribute(io.siddhi.query.api.definition.Attribute) FunctionExecutor(io.siddhi.core.executor.function.FunctionExecutor) EventVariableFunctionExecutor(io.siddhi.core.executor.EventVariableFunctionExecutor) MultiValueVariableFunctionExecutor(io.siddhi.core.executor.MultiValueVariableFunctionExecutor) ScriptFunctionExecutor(io.siddhi.core.executor.function.ScriptFunctionExecutor) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) EqualCompareConditionExpressionExecutorStringString(io.siddhi.core.executor.condition.compare.equal.EqualCompareConditionExpressionExecutorStringString) NotEqualCompareConditionExpressionExecutorStringString(io.siddhi.core.executor.condition.compare.notequal.NotEqualCompareConditionExpressionExecutorStringString) MultiValueVariableFunctionExecutor(io.siddhi.core.executor.MultiValueVariableFunctionExecutor) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) AttributeNotExistException(io.siddhi.query.api.exception.AttributeNotExistException) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 33 with SiddhiAppCreationException

use of io.siddhi.core.exception.SiddhiAppCreationException in project siddhi by wso2.

the class AggregationParser method parse.

public static AggregationRuntime parse(AggregationDefinition aggregationDefinition, SiddhiAppContext siddhiAppContext, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, Map<String, Window> windowMap, Map<String, AggregationRuntime> aggregationMap, SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder) {
    // set timeZone for aggregation
    String timeZone = getTimeZone(siddhiAppContext);
    boolean isDebugEnabled = log.isDebugEnabled();
    boolean isPersistedAggregation = false;
    boolean isReadOnly = false;
    if (!validateTimeZone(timeZone)) {
        throw new SiddhiAppCreationException("Given timeZone '" + timeZone + "' for aggregations is invalid. Please provide a valid time zone.");
    }
    // get aggregation name
    String aggregatorName = aggregationDefinition.getId();
    if (isDebugEnabled) {
        log.debug("Incremental aggregation initialization process started for aggregation " + aggregatorName);
    }
    Annotation aggregationProperties = AnnotationHelper.getAnnotation(ANNOTATION_PERSISTED_AGGREGATION, aggregationDefinition.getAnnotations());
    if (aggregationProperties != null) {
        String persistedAggregationMode = aggregationProperties.getElement(ANNOTATION_ELEMENT_ENABLE);
        isPersistedAggregation = persistedAggregationMode == null || Boolean.parseBoolean(persistedAggregationMode);
        String readOnlyMode = aggregationProperties.getElement(ANNOTATION_ELEMENT_IS_READ_ONLY);
        isReadOnly = Boolean.parseBoolean(readOnlyMode);
    }
    if (isPersistedAggregation) {
        aggregationDefinition.getSelector().getSelectionList().stream().forEach(outputAttribute -> {
            if (outputAttribute.getExpression() instanceof AttributeFunction && ((AttributeFunction) outputAttribute.getExpression()).getName().equals("distinctCount")) {
                throw new SiddhiAppCreationException("Aggregation function 'distinctCount' does not supported " + "with persisted aggregation type please use default incremental aggregation");
            }
        });
    }
    if (isDebugEnabled) {
        log.debug("Aggregation mode is defined as " + (isPersistedAggregation ? "persisted" : "inMemory") + " for aggregation " + aggregatorName);
    }
    if (aggregationDefinition.getTimePeriod() == null) {
        throw new SiddhiAppCreationException("Aggregation Definition '" + aggregationDefinition.getId() + "'s timePeriod is null. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'", aggregationDefinition.getQueryContextStartIndex(), aggregationDefinition.getQueryContextEndIndex());
    }
    if (aggregationDefinition.getSelector() == null) {
        throw new SiddhiAppCreationException("Aggregation Definition '" + aggregationDefinition.getId() + "'s selection is not defined. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'", aggregationDefinition.getQueryContextStartIndex(), aggregationDefinition.getQueryContextEndIndex());
    }
    if (streamDefinitionMap.get(aggregationDefinition.getBasicSingleInputStream().getStreamId()) == null) {
        throw new SiddhiAppCreationException("Stream " + aggregationDefinition.getBasicSingleInputStream().getStreamId() + " has not been defined");
    }
    // Check if the user defined primary keys exists for @store annotation on aggregation if yes, an error is
    // is thrown
    Element userDefinedPrimaryKey = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_PRIMARY_KEY, null, aggregationDefinition.getAnnotations());
    if (userDefinedPrimaryKey != null) {
        throw new SiddhiAppCreationException("Aggregation Tables have predefined primary key, but found '" + userDefinedPrimaryKey.getValue() + "' primary key defined though annotation.");
    }
    try {
        List<VariableExpressionExecutor> incomingVariableExpressionExecutors = new ArrayList<>();
        SiddhiQueryContext siddhiQueryContext = new SiddhiQueryContext(siddhiAppContext, aggregatorName);
        StreamRuntime streamRuntime = InputStreamParser.parse(aggregationDefinition.getBasicSingleInputStream(), null, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, incomingVariableExpressionExecutors, false, siddhiQueryContext);
        // Get original meta for later use.
        MetaStreamEvent incomingMetaStreamEvent = (MetaStreamEvent) streamRuntime.getMetaComplexEvent();
        // Create new meta stream event.
        // This must hold the timestamp, group by attributes (if given) and the incremental attributes, in
        // onAfterWindowData array
        // Example format: AGG_TIMESTAMP, groupByAttribute1, groupByAttribute2, AGG_incAttribute1, AGG_incAttribute2
        // AGG_incAttribute1, AGG_incAttribute2 would have the same attribute names as in
        // finalListOfIncrementalAttributes
        // To enter data as onAfterWindowData
        incomingMetaStreamEvent.initializeOnAfterWindowData();
        // List of all aggregationDurations
        List<TimePeriod.Duration> aggregationDurations = getSortedPeriods(aggregationDefinition.getTimePeriod(), isPersistedAggregation);
        // Incoming executors will be executors for timestamp, externalTimestamp(if used),
        List<ExpressionExecutor> incomingExpressionExecutors = new ArrayList<>();
        List<IncrementalAttributeAggregator> incrementalAttributeAggregators = new ArrayList<>();
        // group by attributes (if given) and the incremental attributes expression executors
        List<Variable> groupByVariableList = aggregationDefinition.getSelector().getGroupByList();
        // Expressions to get final aggregate outputs. e.g for avg the expression is Divide expression with
        // AGG_SUM/ AGG_COUNT
        List<Expression> outputExpressions = new ArrayList<>();
        boolean isProcessingOnExternalTime = aggregationDefinition.getAggregateAttribute() != null;
        boolean isGroupBy = aggregationDefinition.getSelector().getGroupByList().size() != 0;
        final boolean isDistributed;
        ConfigManager configManager = siddhiAppContext.getSiddhiContext().getConfigManager();
        final String shardId = configManager.extractProperty("shardId");
        boolean enablePartitioning = false;
        // check if the setup is Active Active(distributed deployment) by checking availability of partitionById
        // config
        Annotation partitionById = AnnotationHelper.getAnnotation(ANNOTATION_PARTITION_BY_ID, aggregationDefinition.getAnnotations());
        if (partitionById != null) {
            String enableElement = partitionById.getElement(ANNOTATION_ELEMENT_ENABLE);
            enablePartitioning = enableElement == null || Boolean.parseBoolean(enableElement);
        }
        boolean shouldPartitionById = Boolean.parseBoolean(configManager.extractProperty("partitionById"));
        if (enablePartitioning || shouldPartitionById) {
            if (shardId == null) {
                throw new SiddhiAppCreationException("Configuration 'shardId' not provided for @partitionById " + "annotation");
            }
            isDistributed = true;
        } else {
            isDistributed = false;
        }
        if (isDebugEnabled) {
            log.debug("Distributed aggregation processing is " + (isDistributed ? "enabled" : "disabled") + " in " + aggregatorName + " aggregation ");
        }
        populateIncomingAggregatorsAndExecutors(aggregationDefinition, siddhiQueryContext, tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, groupByVariableList, outputExpressions, isProcessingOnExternalTime, isDistributed, shardId);
        // check if the populateIncomingAggregatorsAndExecutors process has been completed successfully
        boolean isLatestEventColAdded = incomingMetaStreamEvent.getOutputData().get(incomingMetaStreamEvent.getOutputData().size() - 1).getName().equals(AGG_LAST_TIMESTAMP_COL);
        int baseAggregatorBeginIndex = incomingMetaStreamEvent.getOutputData().size();
        List<Expression> finalBaseExpressions = new ArrayList<>();
        boolean isOptimisedLookup = populateFinalBaseAggregators(tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, siddhiQueryContext, finalBaseExpressions);
        if (isDebugEnabled) {
            log.debug("Optimised lookup mode is " + (isOptimisedLookup ? "enabled" : "disabled") + " for " + "aggregation " + aggregatorName);
        }
        // Creating an intermediate stream with aggregated stream and above extracted output variables
        StreamDefinition incomingOutputStreamDefinition = StreamDefinition.id(aggregatorName + "_intermediate");
        incomingOutputStreamDefinition.setQueryContextStartIndex(aggregationDefinition.getQueryContextStartIndex());
        incomingOutputStreamDefinition.setQueryContextEndIndex(aggregationDefinition.getQueryContextEndIndex());
        MetaStreamEvent processedMetaStreamEvent = new MetaStreamEvent();
        for (Attribute attribute : incomingMetaStreamEvent.getOutputData()) {
            incomingOutputStreamDefinition.attribute(attribute.getName(), attribute.getType());
            processedMetaStreamEvent.addOutputData(attribute);
        }
        incomingMetaStreamEvent.setOutputDefinition(incomingOutputStreamDefinition);
        processedMetaStreamEvent.addInputDefinition(incomingOutputStreamDefinition);
        processedMetaStreamEvent.setOutputDefinition(incomingOutputStreamDefinition);
        // Executors of processing meta
        List<VariableExpressionExecutor> processVariableExpressionExecutors = new ArrayList<>();
        Map<TimePeriod.Duration, List<ExpressionExecutor>> processExpressionExecutorsMap = new HashMap<>();
        Map<TimePeriod.Duration, List<ExpressionExecutor>> processExpressionExecutorsMapForFind = new HashMap<>();
        aggregationDurations.forEach(incrementalDuration -> {
            processExpressionExecutorsMap.put(incrementalDuration, constructProcessExpressionExecutors(siddhiQueryContext, tableMap, baseAggregatorBeginIndex, finalBaseExpressions, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, isProcessingOnExternalTime, incrementalDuration, isDistributed, shardId, isLatestEventColAdded));
            processExpressionExecutorsMapForFind.put(incrementalDuration, constructProcessExpressionExecutors(siddhiQueryContext, tableMap, baseAggregatorBeginIndex, finalBaseExpressions, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, isProcessingOnExternalTime, incrementalDuration, isDistributed, shardId, isLatestEventColAdded));
        });
        ExpressionExecutor shouldUpdateTimestamp = null;
        if (isLatestEventColAdded) {
            Expression shouldUpdateTimestampExp = new Variable(AGG_LAST_TIMESTAMP_COL);
            shouldUpdateTimestamp = ExpressionParser.parseExpression(shouldUpdateTimestampExp, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        }
        List<ExpressionExecutor> outputExpressionExecutors = outputExpressions.stream().map(expression -> ExpressionParser.parseExpression(expression, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, isGroupBy, 0, ProcessingMode.BATCH, false, siddhiQueryContext)).collect(Collectors.toList());
        // Create group by key generator
        Map<TimePeriod.Duration, GroupByKeyGenerator> groupByKeyGeneratorMap = new HashMap<>();
        aggregationDurations.forEach(incrementalDuration -> {
            GroupByKeyGenerator groupByKeyGenerator = null;
            if (isProcessingOnExternalTime || isGroupBy) {
                List<Expression> groupByExpressionList = new ArrayList<>();
                if (isProcessingOnExternalTime) {
                    Expression externalTimestampExpression = AttributeFunction.function("incrementalAggregator", "getAggregationStartTime", new Variable(AGG_EXTERNAL_TIMESTAMP_COL), new StringConstant(incrementalDuration.name()));
                    groupByExpressionList.add(externalTimestampExpression);
                }
                groupByExpressionList.addAll(groupByVariableList.stream().map(groupByVariable -> (Expression) groupByVariable).collect(Collectors.toList()));
                groupByKeyGenerator = new GroupByKeyGenerator(groupByExpressionList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiQueryContext);
            }
            groupByKeyGeneratorMap.put(incrementalDuration, groupByKeyGenerator);
        });
        // GroupBy for reading
        Map<TimePeriod.Duration, GroupByKeyGenerator> groupByKeyGeneratorMapForReading = new HashMap<>();
        if (isDistributed && !isProcessingOnExternalTime) {
            aggregationDurations.forEach(incrementalDuration -> {
                List<Expression> groupByExpressionList = new ArrayList<>();
                Expression timestampExpression = AttributeFunction.function("incrementalAggregator", "getAggregationStartTime", new Variable(AGG_START_TIMESTAMP_COL), new StringConstant(incrementalDuration.name()));
                groupByExpressionList.add(timestampExpression);
                if (isGroupBy) {
                    groupByExpressionList.addAll(groupByVariableList.stream().map(groupByVariable -> (Expression) groupByVariable).collect(Collectors.toList()));
                }
                GroupByKeyGenerator groupByKeyGenerator = new GroupByKeyGenerator(groupByExpressionList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiQueryContext);
                groupByKeyGeneratorMapForReading.put(incrementalDuration, groupByKeyGenerator);
            });
        } else {
            groupByKeyGeneratorMapForReading.putAll(groupByKeyGeneratorMap);
        }
        // Create new scheduler
        EntryValveExecutor entryValveExecutor = new EntryValveExecutor(siddhiAppContext);
        LockWrapper lockWrapper = new LockWrapper(aggregatorName);
        lockWrapper.setLock(new ReentrantLock());
        Scheduler scheduler = SchedulerParser.parse(entryValveExecutor, siddhiQueryContext);
        scheduler.init(lockWrapper, aggregatorName);
        scheduler.setStreamEventFactory(new StreamEventFactory(processedMetaStreamEvent));
        QueryParserHelper.reduceMetaComplexEvent(incomingMetaStreamEvent);
        QueryParserHelper.reduceMetaComplexEvent(processedMetaStreamEvent);
        QueryParserHelper.updateVariablePosition(incomingMetaStreamEvent, incomingVariableExpressionExecutors);
        QueryParserHelper.updateVariablePosition(processedMetaStreamEvent, processVariableExpressionExecutors);
        Map<TimePeriod.Duration, Table> aggregationTables = initDefaultTables(aggregatorName, aggregationDurations, processedMetaStreamEvent.getOutputStreamDefinition(), siddhiAppRuntimeBuilder, aggregationDefinition.getAnnotations(), groupByVariableList, isProcessingOnExternalTime, isDistributed);
        Map<TimePeriod.Duration, Executor> incrementalExecutorMap = buildIncrementalExecutors(processedMetaStreamEvent, processExpressionExecutorsMap, groupByKeyGeneratorMap, aggregationDurations, aggregationTables, siddhiQueryContext, aggregatorName, shouldUpdateTimestamp, timeZone, isPersistedAggregation, incomingOutputStreamDefinition, isDistributed, shardId, isProcessingOnExternalTime, aggregationDefinition, configManager, groupByVariableList, isReadOnly);
        isOptimisedLookup = isOptimisedLookup && aggregationTables.get(aggregationDurations.get(0)) instanceof QueryableProcessor;
        List<String> groupByVariablesList = groupByVariableList.stream().map(Variable::getAttributeName).collect(Collectors.toList());
        List<OutputAttribute> defaultSelectorList = new ArrayList<>();
        if (isOptimisedLookup) {
            defaultSelectorList = incomingOutputStreamDefinition.getAttributeList().stream().map((attribute) -> new OutputAttribute(new Variable(attribute.getName()))).collect(Collectors.toList());
        }
        IncrementalDataPurger incrementalDataPurger = new IncrementalDataPurger();
        incrementalDataPurger.init(aggregationDefinition, new StreamEventFactory(processedMetaStreamEvent), aggregationTables, isProcessingOnExternalTime, siddhiQueryContext, aggregationDurations, timeZone, windowMap, aggregationMap);
        // Recreate in-memory data from tables
        IncrementalExecutorsInitialiser incrementalExecutorsInitialiser = new IncrementalExecutorsInitialiser(aggregationDurations, aggregationTables, incrementalExecutorMap, isDistributed, shardId, siddhiAppContext, processedMetaStreamEvent, tableMap, windowMap, aggregationMap, timeZone, isReadOnly, isPersistedAggregation);
        IncrementalExecutor rootIncrementalExecutor = (IncrementalExecutor) incrementalExecutorMap.get(aggregationDurations.get(0));
        rootIncrementalExecutor.setScheduler(scheduler);
        // Connect entry valve to root incremental executor
        entryValveExecutor.setNextExecutor(rootIncrementalExecutor);
        QueryParserHelper.initStreamRuntime(streamRuntime, incomingMetaStreamEvent, lockWrapper, aggregatorName);
        LatencyTracker latencyTrackerFind = null;
        LatencyTracker latencyTrackerInsert = null;
        ThroughputTracker throughputTrackerFind = null;
        ThroughputTracker throughputTrackerInsert = null;
        if (siddhiAppContext.getStatisticsManager() != null) {
            latencyTrackerFind = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_FIND);
            latencyTrackerInsert = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_INSERT);
            throughputTrackerFind = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_FIND);
            throughputTrackerInsert = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_INSERT);
        }
        AggregationRuntime aggregationRuntime = new AggregationRuntime(aggregationDefinition, isProcessingOnExternalTime, isDistributed, aggregationDurations, incrementalExecutorMap, aggregationTables, outputExpressionExecutors, processExpressionExecutorsMapForFind, shouldUpdateTimestamp, groupByKeyGeneratorMapForReading, isOptimisedLookup, defaultSelectorList, groupByVariablesList, isLatestEventColAdded, baseAggregatorBeginIndex, finalBaseExpressions, incrementalDataPurger, incrementalExecutorsInitialiser, ((SingleStreamRuntime) streamRuntime), processedMetaStreamEvent, latencyTrackerFind, throughputTrackerFind, timeZone);
        streamRuntime.setCommonProcessor(new IncrementalAggregationProcessor(aggregationRuntime, incomingExpressionExecutors, processedMetaStreamEvent, latencyTrackerInsert, throughputTrackerInsert, siddhiAppContext));
        return aggregationRuntime;
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, aggregationDefinition, siddhiAppContext);
        throw t;
    }
}
Also used : AnnotationHelper(io.siddhi.query.api.util.AnnotationHelper) Arrays(java.util.Arrays) PersistedAggregationResultsProcessor(io.siddhi.core.aggregation.persistedaggregation.config.PersistedAggregationResultsProcessor) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) METRIC_TYPE_FIND(io.siddhi.core.util.SiddhiConstants.METRIC_TYPE_FIND) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SiddhiContext(io.siddhi.core.config.SiddhiContext) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) Expression(io.siddhi.query.api.expression.Expression) SUB_SELECT_QUERY_REF_T2(io.siddhi.core.util.SiddhiConstants.SUB_SELECT_QUERY_REF_T2) SUB_SELECT_QUERY_REF_T1(io.siddhi.core.util.SiddhiConstants.SUB_SELECT_QUERY_REF_T1) AbstractStreamProcessor(io.siddhi.core.query.processor.stream.AbstractStreamProcessor) Map(java.util.Map) METRIC_INFIX_AGGREGATIONS(io.siddhi.core.util.SiddhiConstants.METRIC_INFIX_AGGREGATIONS) IncrementalExecutorsInitialiser(io.siddhi.core.aggregation.IncrementalExecutorsInitialiser) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) TableDefinition(io.siddhi.query.api.definition.TableDefinition) ProcessingMode(io.siddhi.core.query.processor.ProcessingMode) DBAggregationQueryConfigurationEntry(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationQueryConfigurationEntry) LockWrapper(io.siddhi.core.util.lock.LockWrapper) SQL_NOT_NULL(io.siddhi.core.util.SiddhiConstants.SQL_NOT_NULL) ComplexEvent(io.siddhi.core.event.ComplexEvent) Set(java.util.Set) ConfigReader(io.siddhi.core.util.config.ConfigReader) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) Element(io.siddhi.query.api.annotation.Element) FunctionExecutorExtensionHolder(io.siddhi.core.util.extension.holder.FunctionExecutorExtensionHolder) MaxAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MaxAttributeAggregatorExecutor) Logger(org.apache.logging.log4j.Logger) Window(io.siddhi.core.window.Window) AGG_EXTERNAL_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_EXTERNAL_TIMESTAMP_COL) INNER_SELECT_QUERY_REF_T3(io.siddhi.core.util.SiddhiConstants.INNER_SELECT_QUERY_REF_T3) StreamHandler(io.siddhi.query.api.execution.query.input.handler.StreamHandler) FUNCTION_NAME_CUD(io.siddhi.core.util.SiddhiConstants.FUNCTION_NAME_CUD) Variable(io.siddhi.query.api.expression.Variable) DBAggregationSelectFunctionTemplate(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationSelectFunctionTemplate) ArrayList(java.util.ArrayList) StreamRuntime(io.siddhi.core.query.input.stream.StreamRuntime) LinkedHashMap(java.util.LinkedHashMap) StreamProcessorExtensionHolder(io.siddhi.core.util.extension.holder.StreamProcessorExtensionHolder) Extension(io.siddhi.query.api.extension.Extension) ANNOTATION_ELEMENT_IS_READ_ONLY(io.siddhi.core.util.SiddhiConstants.ANNOTATION_ELEMENT_IS_READ_ONLY) DBAggregationQueryUtil(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationQueryUtil) IncrementalAggregateBaseTimeFunctionExecutor(io.siddhi.core.executor.incremental.IncrementalAggregateBaseTimeFunctionExecutor) ConfigManager(io.siddhi.core.util.config.ConfigManager) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) DBAggregationTimeConversionDurationMapping(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationTimeConversionDurationMapping) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) AGG_LAST_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_LAST_TIMESTAMP_COL) QueuedCudStreamProcessor(io.siddhi.core.aggregation.persistedaggregation.QueuedCudStreamProcessor) PLACEHOLDER_TABLE_NAME(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_TABLE_NAME) IncrementalAttributeAggregator(io.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) ANNOTATION_PARTITION_BY_ID(io.siddhi.core.util.SiddhiConstants.ANNOTATION_PARTITION_BY_ID) PLACEHOLDER_DURATION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_DURATION) EQUALS(io.siddhi.core.util.SiddhiConstants.EQUALS) SQL_AND(io.siddhi.core.util.SiddhiConstants.SQL_AND) QueryParserHelper(io.siddhi.core.util.parser.helper.QueryParserHelper) PLACEHOLDER_COLUMN(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_COLUMN) AGG_SHARD_ID_COL(io.siddhi.core.util.SiddhiConstants.AGG_SHARD_ID_COL) Scheduler(io.siddhi.core.util.Scheduler) AggregationDefinition(io.siddhi.query.api.definition.AggregationDefinition) SiddhiAppRuntimeBuilder(io.siddhi.core.util.SiddhiAppRuntimeBuilder) PLACEHOLDER_FROM_CONDITION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_FROM_CONDITION) SiddhiAppContext(io.siddhi.core.config.SiddhiAppContext) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) PLACEHOLDER_SELECTORS(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_SELECTORS) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) SiddhiConstants(io.siddhi.core.util.SiddhiConstants) SQL_WHERE(io.siddhi.core.util.SiddhiConstants.SQL_WHERE) Annotation(io.siddhi.query.api.annotation.Annotation) IncrementalDataPurger(io.siddhi.core.aggregation.IncrementalDataPurger) StreamEvent(io.siddhi.core.event.stream.StreamEvent) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) PLACEHOLDER_COLUMNS(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_COLUMNS) Table(io.siddhi.core.table.Table) NAMESPACE_RDBMS(io.siddhi.core.util.SiddhiConstants.NAMESPACE_RDBMS) AggregationRuntime(io.siddhi.core.aggregation.AggregationRuntime) StreamEventFactory(io.siddhi.core.event.stream.StreamEventFactory) TimeZone(java.util.TimeZone) AGG_START_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_START_TIMESTAMP_COL) ExceptionUtil(io.siddhi.core.util.ExceptionUtil) SumAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.SumAttributeAggregatorExecutor) PLACEHOLDER_ON_CONDITION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_ON_CONDITION) StreamProcessor(io.siddhi.core.query.processor.stream.StreamProcessor) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) TO_TIMESTAMP(io.siddhi.core.util.SiddhiConstants.TO_TIMESTAMP) List(java.util.List) SQL_SELECT(io.siddhi.core.util.SiddhiConstants.SQL_SELECT) CudStreamProcessorQueueManager(io.siddhi.core.aggregation.persistedaggregation.CudStreamProcessorQueueManager) Processor(io.siddhi.core.query.processor.Processor) ThroughputTracker(io.siddhi.core.util.statistics.ThroughputTracker) PLACEHOLDER_INNER_QUERY_1(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_INNER_QUERY_1) PLACEHOLDER_INNER_QUERY_2(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_INNER_QUERY_2) ANNOTATION_ELEMENT_ENABLE(io.siddhi.core.util.SiddhiConstants.ANNOTATION_ELEMENT_ENABLE) METRIC_TYPE_INSERT(io.siddhi.core.util.SiddhiConstants.METRIC_TYPE_INSERT) Executor(io.siddhi.core.aggregation.Executor) ANNOTATION_PERSISTED_AGGREGATION(io.siddhi.core.util.SiddhiConstants.ANNOTATION_PERSISTED_AGGREGATION) IncrementalExecutor(io.siddhi.core.aggregation.IncrementalExecutor) SiddhiClassLoader(io.siddhi.core.util.SiddhiClassLoader) IncrementalAttributeAggregatorExtensionHolder(io.siddhi.core.util.extension.holder.IncrementalAttributeAggregatorExtensionHolder) HashMap(java.util.HashMap) HashSet(java.util.HashSet) CannotLoadConfigurationException(io.siddhi.core.exception.CannotLoadConfigurationException) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) DBAggregationSelectQueryTemplate(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationSelectQueryTemplate) EntryValveExecutor(io.siddhi.core.query.input.stream.single.EntryValveExecutor) PLACEHOLDER_CONDITION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_CONDITION) StreamFunction(io.siddhi.query.api.execution.query.input.handler.StreamFunction) ReentrantLock(java.util.concurrent.locks.ReentrantLock) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) Attribute(io.siddhi.query.api.definition.Attribute) IncrementalAggregationProcessor(io.siddhi.core.aggregation.IncrementalAggregationProcessor) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) SQL_FROM(io.siddhi.core.util.SiddhiConstants.SQL_FROM) FROM_TIMESTAMP(io.siddhi.core.util.SiddhiConstants.FROM_TIMESTAMP) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) MinAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MinAttributeAggregatorExecutor) StringJoiner(java.util.StringJoiner) Comparator(java.util.Comparator) SQL_AS(io.siddhi.core.util.SiddhiConstants.SQL_AS) LogManager(org.apache.logging.log4j.LogManager) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) AggregationRuntime(io.siddhi.core.aggregation.AggregationRuntime) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ThroughputTracker(io.siddhi.core.util.statistics.ThroughputTracker) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) StreamEventFactory(io.siddhi.core.event.stream.StreamEventFactory) IncrementalAttributeAggregator(io.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) Variable(io.siddhi.query.api.expression.Variable) IncrementalDataPurger(io.siddhi.core.aggregation.IncrementalDataPurger) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) Scheduler(io.siddhi.core.util.Scheduler) Element(io.siddhi.query.api.annotation.Element) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) IncrementalExecutorsInitialiser(io.siddhi.core.aggregation.IncrementalExecutorsInitialiser) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) IncrementalExecutor(io.siddhi.core.aggregation.IncrementalExecutor) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) MaxAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MaxAttributeAggregatorExecutor) IncrementalAggregateBaseTimeFunctionExecutor(io.siddhi.core.executor.incremental.IncrementalAggregateBaseTimeFunctionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) SumAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.SumAttributeAggregatorExecutor) Executor(io.siddhi.core.aggregation.Executor) IncrementalExecutor(io.siddhi.core.aggregation.IncrementalExecutor) EntryValveExecutor(io.siddhi.core.query.input.stream.single.EntryValveExecutor) MinAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MinAttributeAggregatorExecutor) StreamRuntime(io.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) IncrementalAggregationProcessor(io.siddhi.core.aggregation.IncrementalAggregationProcessor) Table(io.siddhi.core.table.Table) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) EntryValveExecutor(io.siddhi.core.query.input.stream.single.EntryValveExecutor) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) LockWrapper(io.siddhi.core.util.lock.LockWrapper) Annotation(io.siddhi.query.api.annotation.Annotation) ConfigManager(io.siddhi.core.util.config.ConfigManager) Expression(io.siddhi.query.api.expression.Expression)

Example 34 with SiddhiAppCreationException

use of io.siddhi.core.exception.SiddhiAppCreationException in project siddhi by wso2.

the class CollectionExpressionParser method buildMultiPrimaryKeyExpressionExecutors.

private static Map<String, ExpressionExecutor> buildMultiPrimaryKeyExpressionExecutors(CollectionExpression collectionExpression, MatchingMetaInfoHolder matchingMetaInfoHolder, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, ProcessingMode processingMode, boolean outputExpectsExpiredEvents, SiddhiQueryContext siddhiQueryContext) {
    if (collectionExpression instanceof AndMultiPrimaryKeyCollectionExpression) {
        CollectionExpression leftCollectionExpression = ((AndMultiPrimaryKeyCollectionExpression) collectionExpression).getLeftCollectionExpression();
        CollectionExpression rightCollectionExpression = ((AndMultiPrimaryKeyCollectionExpression) collectionExpression).getRightCollectionExpression();
        Map<String, ExpressionExecutor> expressionExecutors = buildMultiPrimaryKeyExpressionExecutors(leftCollectionExpression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
        expressionExecutors.putAll(buildMultiPrimaryKeyExpressionExecutors(rightCollectionExpression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        return expressionExecutors;
    } else if (collectionExpression instanceof AndCollectionExpression) {
        CollectionExpression leftCollectionExpression = ((AndCollectionExpression) collectionExpression).getLeftCollectionExpression();
        CollectionExpression rightCollectionExpression = ((AndCollectionExpression) collectionExpression).getRightCollectionExpression();
        Map<String, ExpressionExecutor> expressionExecutors = buildMultiPrimaryKeyExpressionExecutors(leftCollectionExpression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
        expressionExecutors.putAll(buildMultiPrimaryKeyExpressionExecutors(rightCollectionExpression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        return expressionExecutors;
    } else if (collectionExpression instanceof CompareCollectionExpression) {
        if (((CompareCollectionExpression) collectionExpression).getOperator() == Compare.Operator.EQUAL) {
            CollectionExpression attributeCollectionExpression = ((CompareCollectionExpression) collectionExpression).getAttributeCollectionExpression();
            if (attributeCollectionExpression instanceof AttributeCollectionExpression) {
                String attribue = ((AttributeCollectionExpression) attributeCollectionExpression).getAttribute();
                CollectionExpression valueCollectionExpression = ((CompareCollectionExpression) collectionExpression).getValueCollectionExpression();
                ExpressionExecutor valueExpressionExecutor = ExpressionParser.parseExpression(valueCollectionExpression.getExpression(), matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                Map<String, ExpressionExecutor> expressionExecutors = new HashMap<String, ExpressionExecutor>();
                expressionExecutors.put(attribue, valueExpressionExecutor);
                return expressionExecutors;
            } else {
                throw new SiddhiAppCreationException("Only attribute EQUAL " + "comparision supported for multiple primary key optimization, " + "but found  '" + attributeCollectionExpression.getClass() + "'", collectionExpression.getExpression().getQueryContextStartIndex(), collectionExpression.getExpression().getQueryContextEndIndex());
            }
        } else {
            throw new SiddhiAppCreationException("Only '" + Compare.Operator.EQUAL + "' supported for multiple " + "primary key for multiple primary key optimization, but found '" + ((CompareCollectionExpression) collectionExpression).getOperator() + "'", collectionExpression.getExpression().getQueryContextStartIndex(), collectionExpression.getExpression().getQueryContextEndIndex());
        }
    } else {
        // Attribute Collection
        throw new SiddhiAppCreationException("Only 'AND' and '" + Compare.Operator.EQUAL + "' operators are " + "supported for multiple primary key optimization, but found '" + ((CompareCollectionExpression) collectionExpression).getOperator() + "'", collectionExpression.getExpression().getQueryContextStartIndex(), collectionExpression.getExpression().getQueryContextEndIndex());
    }
}
Also used : VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) CompareCollectionExpression(io.siddhi.core.util.collection.expression.CompareCollectionExpression) HashMap(java.util.HashMap) AndCollectionExpression(io.siddhi.core.util.collection.expression.AndCollectionExpression) AttributeCollectionExpression(io.siddhi.core.util.collection.expression.AttributeCollectionExpression) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) AndMultiPrimaryKeyCollectionExpression(io.siddhi.core.util.collection.expression.AndMultiPrimaryKeyCollectionExpression) CollectionExpression(io.siddhi.core.util.collection.expression.CollectionExpression) CompareCollectionExpression(io.siddhi.core.util.collection.expression.CompareCollectionExpression) AttributeCollectionExpression(io.siddhi.core.util.collection.expression.AttributeCollectionExpression) BasicCollectionExpression(io.siddhi.core.util.collection.expression.BasicCollectionExpression) NullCollectionExpression(io.siddhi.core.util.collection.expression.NullCollectionExpression) OrCollectionExpression(io.siddhi.core.util.collection.expression.OrCollectionExpression) NotCollectionExpression(io.siddhi.core.util.collection.expression.NotCollectionExpression) AndMultiPrimaryKeyCollectionExpression(io.siddhi.core.util.collection.expression.AndMultiPrimaryKeyCollectionExpression) AndCollectionExpression(io.siddhi.core.util.collection.expression.AndCollectionExpression) Map(java.util.Map) HashMap(java.util.HashMap)

Example 35 with SiddhiAppCreationException

use of io.siddhi.core.exception.SiddhiAppCreationException in project siddhi by wso2.

the class AggregationParser method populateIncomingAggregatorsAndExecutors.

private static void populateIncomingAggregatorsAndExecutors(AggregationDefinition aggregationDefinition, SiddhiQueryContext siddhiQueryContext, Map<String, Table> tableMap, List<VariableExpressionExecutor> incomingVariableExpressionExecutors, MetaStreamEvent incomingMetaStreamEvent, List<ExpressionExecutor> incomingExpressionExecutors, List<IncrementalAttributeAggregator> incrementalAttributeAggregators, List<Variable> groupByVariableList, List<Expression> outputExpressions, boolean isProcessingOnExternalTime, boolean isDistributed, String shardId) {
    boolean isLatestEventAdded = false;
    ExpressionExecutor timestampExecutor = getTimeStampExecutor(siddhiQueryContext, tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent);
    Attribute timestampAttribute = new Attribute(AGG_START_TIMESTAMP_COL, Attribute.Type.LONG);
    incomingMetaStreamEvent.addOutputData(timestampAttribute);
    incomingExpressionExecutors.add(timestampExecutor);
    if (isDistributed) {
        ExpressionExecutor nodeIdExpExecutor = new ConstantExpressionExecutor(shardId, Attribute.Type.STRING);
        incomingExpressionExecutors.add(nodeIdExpExecutor);
        incomingMetaStreamEvent.addOutputData(new Attribute(AGG_SHARD_ID_COL, Attribute.Type.STRING));
    }
    ExpressionExecutor externalTimestampExecutor = null;
    if (isProcessingOnExternalTime) {
        Expression externalTimestampExpression = aggregationDefinition.getAggregateAttribute();
        externalTimestampExecutor = ExpressionParser.parseExpression(externalTimestampExpression, incomingMetaStreamEvent, 0, tableMap, incomingVariableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        if (externalTimestampExecutor.getReturnType() == Attribute.Type.STRING) {
            Expression expression = AttributeFunction.function("incrementalAggregator", "timestampInMilliseconds", externalTimestampExpression);
            externalTimestampExecutor = ExpressionParser.parseExpression(expression, incomingMetaStreamEvent, 0, tableMap, incomingVariableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        } else if (externalTimestampExecutor.getReturnType() != Attribute.Type.LONG) {
            throw new SiddhiAppCreationException("Aggregation Definition '" + aggregationDefinition.getId() + "'s timestamp attribute expects " + "long or string, but found " + externalTimestampExecutor.getReturnType() + ". Hence, can't " + "create the siddhi app '" + siddhiQueryContext.getSiddhiAppContext().getName() + "'", externalTimestampExpression.getQueryContextStartIndex(), externalTimestampExpression.getQueryContextEndIndex());
        }
        Attribute externalTimestampAttribute = new Attribute(AGG_EXTERNAL_TIMESTAMP_COL, Attribute.Type.LONG);
        incomingMetaStreamEvent.addOutputData(externalTimestampAttribute);
        incomingExpressionExecutors.add(externalTimestampExecutor);
    }
    AbstractDefinition incomingLastInputStreamDefinition = incomingMetaStreamEvent.getLastInputDefinition();
    for (Variable groupByVariable : groupByVariableList) {
        incomingMetaStreamEvent.addOutputData(incomingLastInputStreamDefinition.getAttributeList().get(incomingLastInputStreamDefinition.getAttributePosition(groupByVariable.getAttributeName())));
        incomingExpressionExecutors.add(ExpressionParser.parseExpression(groupByVariable, incomingMetaStreamEvent, 0, tableMap, incomingVariableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext));
    }
    // Add AGG_TIMESTAMP to output as well
    aggregationDefinition.getAttributeList().add(timestampAttribute);
    // check and set whether the aggregation in happened on an external timestamp
    if (isProcessingOnExternalTime) {
        outputExpressions.add(Expression.variable(AGG_EXTERNAL_TIMESTAMP_COL));
    } else {
        outputExpressions.add(Expression.variable(AGG_START_TIMESTAMP_COL));
    }
    for (OutputAttribute outputAttribute : aggregationDefinition.getSelector().getSelectionList()) {
        Expression expression = outputAttribute.getExpression();
        // If the select contains the aggregation function expression type will be AttributeFunction
        if (expression instanceof AttributeFunction) {
            IncrementalAttributeAggregator incrementalAggregator = null;
            try {
                incrementalAggregator = (IncrementalAttributeAggregator) SiddhiClassLoader.loadExtensionImplementation(new AttributeFunction("incrementalAggregator", ((AttributeFunction) expression).getName(), ((AttributeFunction) expression).getParameters()), IncrementalAttributeAggregatorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
            } catch (SiddhiAppCreationException ex) {
                try {
                    SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, FunctionExecutorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                    processAggregationSelectors(aggregationDefinition, siddhiQueryContext, tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent, incomingExpressionExecutors, outputExpressions, outputAttribute, expression);
                } catch (SiddhiAppCreationException e) {
                    throw new SiddhiAppCreationException("'" + ((AttributeFunction) expression).getName() + "' is neither a incremental attribute aggregator extension or a function" + " extension", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                }
            }
            if (incrementalAggregator != null) {
                initIncrementalAttributeAggregator(incomingLastInputStreamDefinition, (AttributeFunction) expression, incrementalAggregator);
                incrementalAttributeAggregators.add(incrementalAggregator);
                aggregationDefinition.getAttributeList().add(new Attribute(outputAttribute.getRename(), incrementalAggregator.getReturnType()));
                outputExpressions.add(incrementalAggregator.aggregate());
            }
        } else {
            if (expression instanceof Variable && groupByVariableList.contains(expression)) {
                Attribute groupByAttribute = null;
                for (Attribute attribute : incomingMetaStreamEvent.getOutputData()) {
                    if (attribute.getName().equals(((Variable) expression).getAttributeName())) {
                        groupByAttribute = attribute;
                        break;
                    }
                }
                if (groupByAttribute == null) {
                    throw new SiddhiAppCreationException("Expected GroupBy attribute '" + ((Variable) expression).getAttributeName() + "' not used in aggregation '" + siddhiQueryContext.getName() + "' processing.", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                }
                aggregationDefinition.getAttributeList().add(new Attribute(outputAttribute.getRename(), groupByAttribute.getType()));
                outputExpressions.add(Expression.variable(groupByAttribute.getName()));
            } else {
                isLatestEventAdded = true;
                processAggregationSelectors(aggregationDefinition, siddhiQueryContext, tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent, incomingExpressionExecutors, outputExpressions, outputAttribute, expression);
            }
        }
    }
    if (isProcessingOnExternalTime && isLatestEventAdded) {
        Attribute lastEventTimeStamp = new Attribute(AGG_LAST_TIMESTAMP_COL, Attribute.Type.LONG);
        incomingMetaStreamEvent.addOutputData(lastEventTimeStamp);
        incomingExpressionExecutors.add(externalTimestampExecutor);
    }
}
Also used : Variable(io.siddhi.query.api.expression.Variable) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) Expression(io.siddhi.query.api.expression.Expression) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) IncrementalAttributeAggregator(io.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor)

Aggregations

SiddhiAppCreationException (io.siddhi.core.exception.SiddhiAppCreationException)54 Attribute (io.siddhi.query.api.definition.Attribute)23 VariableExpressionExecutor (io.siddhi.core.executor.VariableExpressionExecutor)16 MetaStreamEvent (io.siddhi.core.event.stream.MetaStreamEvent)15 SiddhiAppRuntime (io.siddhi.core.SiddhiAppRuntime)12 SiddhiManager (io.siddhi.core.SiddhiManager)12 ArrayList (java.util.ArrayList)12 Expression (io.siddhi.query.api.expression.Expression)11 MetaStateEvent (io.siddhi.core.event.state.MetaStateEvent)10 ConstantExpressionExecutor (io.siddhi.core.executor.ConstantExpressionExecutor)10 ExpressionExecutor (io.siddhi.core.executor.ExpressionExecutor)10 Annotation (io.siddhi.query.api.annotation.Annotation)10 Variable (io.siddhi.query.api.expression.Variable)10 ConfigReader (io.siddhi.core.util.config.ConfigReader)9 HashMap (java.util.HashMap)9 Test (org.testng.annotations.Test)9 Element (io.siddhi.query.api.annotation.Element)8 OutputAttribute (io.siddhi.query.api.execution.query.selection.OutputAttribute)8 Table (io.siddhi.core.table.Table)7 MatchingMetaInfoHolder (io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder)7