Search in sources :

Example 1 with SiddhiAppCreationException

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

the class AggregationRuntime method compileExpression.

public CompiledCondition compileExpression(Expression expression, Within within, Expression per, List<Variable> queryGroupByList, MatchingMetaInfoHolder matchingMetaInfoHolder, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, SiddhiQueryContext siddhiQueryContext) {
    String aggregationName = aggregationDefinition.getId();
    boolean isOptimisedTableLookup = isOptimisedLookup;
    Map<TimePeriod.Duration, CompiledCondition> withinTableCompiledConditions = new HashMap<>();
    CompiledCondition withinInMemoryCompileCondition;
    CompiledCondition onCompiledCondition;
    List<Attribute> additionalAttributes = new ArrayList<>();
    // Define additional attribute list
    additionalAttributes.add(new Attribute("_START", Attribute.Type.LONG));
    additionalAttributes.add(new Attribute("_END", Attribute.Type.LONG));
    int lowerGranularitySize = this.activeIncrementalDurations.size() - 1;
    List<String> lowerGranularityAttributes = new ArrayList<>();
    if (isDistributed) {
        // for values calculated in in-memory in the shards
        for (int i = 0; i < lowerGranularitySize; i++) {
            String attributeName = "_AGG_TIMESTAMP_FILTER_" + i;
            additionalAttributes.add(new Attribute(attributeName, Attribute.Type.LONG));
            lowerGranularityAttributes.add(attributeName);
        }
    }
    // Get table definition. Table definitions for all the tables used to persist aggregates are similar.
    // Therefore it's enough to get the definition from one table.
    AbstractDefinition tableDefinition = aggregationTables.get(activeIncrementalDurations.get(0)).getTableDefinition();
    boolean isOnDemandQuery = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents().length == 1;
    // Alter existing meta stream event or create new one if a meta stream doesn't exist
    // After calling this method the original MatchingMetaInfoHolder's meta stream event would be altered
    // Alter meta info holder to contain stream event and aggregate both when it's a on-demand query
    MetaStreamEvent metaStreamEventForTableLookups;
    if (isOnDemandQuery) {
        metaStreamEventForTableLookups = alterMetaStreamEvent(true, new MetaStreamEvent(), additionalAttributes);
        matchingMetaInfoHolder = alterMetaInfoHolderForOnDemandQuery(metaStreamEventForTableLookups, matchingMetaInfoHolder);
    } else {
        metaStreamEventForTableLookups = alterMetaStreamEvent(false, matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(0), additionalAttributes);
    }
    // Create new MatchingMetaInfoHolder containing newMetaStreamEventWithStartEnd and table meta event
    String aggReferenceId = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(1).getInputReferenceId();
    String referenceName = aggReferenceId == null ? aggregationName : aggReferenceId;
    MetaStreamEvent metaStoreEventForTableLookups = createMetaStoreEvent(tableDefinition, referenceName);
    // Create new MatchingMetaInfoHolder containing metaStreamEventForTableLookups and table meta event
    MatchingMetaInfoHolder metaInfoHolderForTableLookups = createNewStreamTableMetaInfoHolder(metaStreamEventForTableLookups, metaStoreEventForTableLookups);
    // Create per expression executor
    ExpressionExecutor perExpressionExecutor;
    if (per != null) {
        perExpressionExecutor = ExpressionParser.parseExpression(per, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        if (perExpressionExecutor.getReturnType() != Attribute.Type.STRING) {
            throw new SiddhiAppCreationException("Query " + siddhiQueryContext.getName() + "'s per value expected a string but found " + perExpressionExecutor.getReturnType(), per.getQueryContextStartIndex(), per.getQueryContextEndIndex());
        }
        // Additional Per time function verification at compile time if it is a constant
        if (perExpressionExecutor instanceof ConstantExpressionExecutor) {
            String perValue = ((ConstantExpressionExecutor) perExpressionExecutor).getValue().toString();
            try {
                normalizeDuration(perValue);
            } catch (SiddhiAppValidationException e) {
                throw new SiddhiAppValidationException("Aggregation Query's per value is expected to be of a valid time function of the " + "following " + TimePeriod.Duration.SECONDS + ", " + TimePeriod.Duration.MINUTES + ", " + TimePeriod.Duration.HOURS + ", " + TimePeriod.Duration.DAYS + ", " + TimePeriod.Duration.MONTHS + ", " + TimePeriod.Duration.YEARS + ".");
            }
        }
    } else {
        throw new SiddhiAppCreationException("Syntax Error: Aggregation join query must contain a `per` " + "definition for granularity");
    }
    // Create start and end time expression
    Expression startEndTimeExpression;
    ExpressionExecutor startTimeEndTimeExpressionExecutor;
    if (within != null) {
        if (within.getTimeRange().size() == 1) {
            startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0));
        } else {
            // within.getTimeRange().size() == 2
            startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0), within.getTimeRange().get(1));
        }
        startTimeEndTimeExpressionExecutor = ExpressionParser.parseExpression(startEndTimeExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
    } else {
        throw new SiddhiAppCreationException("Syntax Error : Aggregation read query must contain a `within` " + "definition for filtering of aggregation data.");
    }
    // Create within expression
    Expression timeFilterExpression;
    if (isProcessingOnExternalTime) {
        timeFilterExpression = Expression.variable(AGG_EXTERNAL_TIMESTAMP_COL);
    } else {
        timeFilterExpression = Expression.variable(AGG_START_TIMESTAMP_COL);
    }
    Expression withinExpression;
    Expression start = Expression.variable(additionalAttributes.get(0).getName());
    Expression end = Expression.variable(additionalAttributes.get(1).getName());
    Expression compareWithStartTime = Compare.compare(start, Compare.Operator.LESS_THAN_EQUAL, timeFilterExpression);
    Expression compareWithEndTime = Compare.compare(timeFilterExpression, Compare.Operator.LESS_THAN, end);
    withinExpression = Expression.and(compareWithStartTime, compareWithEndTime);
    List<ExpressionExecutor> timestampFilterExecutors = new ArrayList<>();
    if (isDistributed) {
        for (int i = 0; i < lowerGranularitySize; i++) {
            Expression[] expressionArray = new Expression[] { new AttributeFunction("", "currentTimeMillis", null), Expression.value(this.activeIncrementalDurations.get(i + 1).toString()) };
            Expression filterExpression = new AttributeFunction("incrementalAggregator", "getAggregationStartTime", expressionArray);
            timestampFilterExecutors.add(ExpressionParser.parseExpression(filterExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext));
        }
    }
    // Create compile condition per each table used to persist aggregates.
    // These compile conditions are used to check whether the aggregates in tables are within the given duration.
    // Combine with and on condition for table query
    boolean shouldApplyReducedCondition = false;
    Expression reducedExpression = null;
    // Check if there is no on conditions
    if (!(expression instanceof BoolConstant)) {
        // For abstract queryable table
        AggregationExpressionBuilder aggregationExpressionBuilder = new AggregationExpressionBuilder(expression);
        AggregationExpressionVisitor expressionVisitor = new AggregationExpressionVisitor(metaStreamEventForTableLookups.getInputReferenceId(), metaStreamEventForTableLookups.getLastInputDefinition().getAttributeList(), this.tableAttributesNameList);
        aggregationExpressionBuilder.build(expressionVisitor);
        shouldApplyReducedCondition = expressionVisitor.applyReducedExpression();
        reducedExpression = expressionVisitor.getReducedExpression();
    }
    Expression withinExpressionTable;
    if (shouldApplyReducedCondition) {
        withinExpressionTable = Expression.and(withinExpression, reducedExpression);
    } else {
        withinExpressionTable = withinExpression;
    }
    List<Variable> queryGroupByListCopy = new ArrayList<>(queryGroupByList);
    Variable timestampVariable = new Variable(AGG_START_TIMESTAMP_COL);
    List<String> queryGroupByNamesList = queryGroupByListCopy.stream().map(Variable::getAttributeName).collect(Collectors.toList());
    boolean queryGroupByContainsTimestamp = queryGroupByNamesList.remove(AGG_START_TIMESTAMP_COL);
    boolean isQueryGroupBySameAsAggGroupBy = queryGroupByListCopy.isEmpty() || (queryGroupByListCopy.contains(timestampVariable) && queryGroupByNamesList.equals(groupByVariablesList));
    List<VariableExpressionExecutor> variableExpExecutorsForTableLookups = new ArrayList<>();
    Map<TimePeriod.Duration, CompiledSelection> withinTableCompiledSelection = new HashMap<>();
    if (isOptimisedTableLookup) {
        Selector selector = Selector.selector();
        List<Variable> groupByList = new ArrayList<>();
        if (!isQueryGroupBySameAsAggGroupBy) {
            if (queryGroupByContainsTimestamp) {
                if (isProcessingOnExternalTime) {
                    groupByList.add(new Variable(AGG_EXTERNAL_TIMESTAMP_COL));
                } else {
                    groupByList.add(new Variable(AGG_START_TIMESTAMP_COL));
                }
                // Remove timestamp to process the rest
                queryGroupByListCopy.remove(timestampVariable);
            }
            for (Variable queryGroupBy : queryGroupByListCopy) {
                String referenceId = queryGroupBy.getStreamId();
                if (referenceId == null) {
                    if (tableAttributesNameList.contains(queryGroupBy.getAttributeName())) {
                        groupByList.add(queryGroupBy);
                    }
                } else if (referenceId.equalsIgnoreCase(referenceName)) {
                    groupByList.add(queryGroupBy);
                }
            }
            // If query group bys are based on joining stream
            if (groupByList.isEmpty()) {
                isQueryGroupBySameAsAggGroupBy = true;
            }
        }
        groupByList.forEach((groupBy) -> groupBy.setStreamId(referenceName));
        selector.addGroupByList(groupByList);
        List<OutputAttribute> selectorList;
        if (!isQueryGroupBySameAsAggGroupBy) {
            selectorList = constructSelectorList(isProcessingOnExternalTime, isDistributed, isLatestEventColAdded, baseAggregatorBeginIndex, groupByVariablesList.size(), finalBaseExpressionsList, tableDefinition, groupByList);
        } else {
            selectorList = defaultSelectorList;
        }
        for (OutputAttribute outputAttribute : selectorList) {
            if (outputAttribute.getExpression() instanceof Variable) {
                ((Variable) outputAttribute.getExpression()).setStreamId(referenceName);
            } else {
                for (Expression parameter : ((AttributeFunction) outputAttribute.getExpression()).getParameters()) {
                    ((Variable) parameter).setStreamId(referenceName);
                }
            }
        }
        selector.addSelectionList(selectorList);
        try {
            aggregationTables.entrySet().forEach((durationTableEntry -> {
                CompiledSelection compiledSelection = ((QueryableProcessor) durationTableEntry.getValue()).compileSelection(selector, tableDefinition.getAttributeList(), metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
                withinTableCompiledSelection.put(durationTableEntry.getKey(), compiledSelection);
            }));
        } catch (SiddhiAppCreationException | SiddhiAppValidationException | QueryableRecordTableException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Aggregation Query optimization failed for aggregation: '" + aggregationName + "'. " + "Creating table lookup query in normal mode. Reason for failure: " + e.getMessage(), e);
            }
            isOptimisedTableLookup = false;
        }
    }
    for (Map.Entry<TimePeriod.Duration, Table> entry : aggregationTables.entrySet()) {
        CompiledCondition withinTableCompileCondition = entry.getValue().compileCondition(withinExpressionTable, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
        withinTableCompiledConditions.put(entry.getKey(), withinTableCompileCondition);
    }
    // Create compile condition for in-memory data.
    // This compile condition is used to check whether the running aggregates (in-memory data)
    // are within given duration
    withinInMemoryCompileCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), withinExpression, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
    // Create compile condition for in-memory data, in case of distributed
    // Look at the lower level granularities
    Map<TimePeriod.Duration, CompiledCondition> withinTableLowerGranularityCompileCondition = new HashMap<>();
    Expression lowerGranularity;
    if (isDistributed) {
        for (int i = 0; i < lowerGranularitySize; i++) {
            if (isProcessingOnExternalTime) {
                lowerGranularity = Expression.and(Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), withinExpressionTable);
            } else {
                if (shouldApplyReducedCondition) {
                    lowerGranularity = Expression.and(Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), reducedExpression);
                } else {
                    lowerGranularity = Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i)));
                }
            }
            TimePeriod.Duration duration = this.activeIncrementalDurations.get(i);
            String tableName = aggregationName + "_" + duration.toString();
            CompiledCondition compiledCondition = tableMap.get(tableName).compileCondition(lowerGranularity, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
            withinTableLowerGranularityCompileCondition.put(duration, compiledCondition);
        }
    }
    QueryParserHelper.reduceMetaComplexEvent(metaInfoHolderForTableLookups.getMetaStateEvent());
    // On compile condition.
    // After finding all the aggregates belonging to within duration, the final on condition (given as
    // "on stream1.name == aggregator.nickName ..." in the join query) must be executed on that data.
    // This condition is used for that purpose.
    onCompiledCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), expression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, siddhiQueryContext);
    return new IncrementalAggregateCompileCondition(isOnDemandQuery, aggregationName, isProcessingOnExternalTime, isDistributed, activeIncrementalDurations, aggregationTables, outputExpressionExecutors, isOptimisedTableLookup, withinTableCompiledSelection, withinTableCompiledConditions, withinInMemoryCompileCondition, withinTableLowerGranularityCompileCondition, onCompiledCondition, additionalAttributes, perExpressionExecutor, startTimeEndTimeExpressionExecutor, timestampFilterExecutors, aggregateMetaSteamEvent, matchingMetaInfoHolder, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups);
}
Also used : MatchingMetaInfoHolder(io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) Selector(io.siddhi.query.api.execution.query.selection.Selector) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) StreamEvent(io.siddhi.core.event.stream.StreamEvent) MemoryCalculable(io.siddhi.core.util.statistics.MemoryCalculable) Expression(io.siddhi.query.api.expression.Expression) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) Time.normalizeDuration(io.siddhi.query.api.expression.Expression.Time.normalizeDuration) Table(io.siddhi.core.table.Table) SnapshotService(io.siddhi.core.util.snapshot.SnapshotService) Map(java.util.Map) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) ProcessingMode(io.siddhi.core.query.processor.ProcessingMode) AGG_START_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_START_TIMESTAMP_COL) UNKNOWN_STATE(io.siddhi.core.util.SiddhiConstants.UNKNOWN_STATE) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ExpressionParser(io.siddhi.core.util.parser.ExpressionParser) Collectors(java.util.stream.Collectors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Level(io.siddhi.core.util.statistics.metrics.Level) ThroughputTracker(io.siddhi.core.util.statistics.ThroughputTracker) AGG_EXTERNAL_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_EXTERNAL_TIMESTAMP_COL) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Variable(io.siddhi.query.api.expression.Variable) CompiledSelection(io.siddhi.core.util.collection.operator.CompiledSelection) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IncrementalAggregateCompileCondition(io.siddhi.core.util.collection.operator.IncrementalAggregateCompileCondition) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) QueryableRecordTableException(io.siddhi.core.exception.QueryableRecordTableException) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) Within(io.siddhi.query.api.aggregation.Within) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) Compare(io.siddhi.query.api.expression.condition.Compare) ComplexEventChunk(io.siddhi.core.event.ComplexEventChunk) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) Attribute(io.siddhi.query.api.definition.Attribute) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) AGG_LAST_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_LAST_TIMESTAMP_COL) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) OperatorParser(io.siddhi.core.util.parser.OperatorParser) StateEvent(io.siddhi.core.event.state.StateEvent) QueryParserHelper(io.siddhi.core.util.parser.helper.QueryParserHelper) LogManager(org.apache.logging.log4j.LogManager) AGG_SHARD_ID_COL(io.siddhi.core.util.SiddhiConstants.AGG_SHARD_ID_COL) AggregationDefinition(io.siddhi.query.api.definition.AggregationDefinition) Variable(io.siddhi.query.api.expression.Variable) ComplexEventChunk(io.siddhi.core.event.ComplexEventChunk) HashMap(java.util.HashMap) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) ArrayList(java.util.ArrayList) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) QueryableRecordTableException(io.siddhi.core.exception.QueryableRecordTableException) Selector(io.siddhi.query.api.execution.query.selection.Selector) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Table(io.siddhi.core.table.Table) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) IncrementalAggregateCompileCondition(io.siddhi.core.util.collection.operator.IncrementalAggregateCompileCondition) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) Time.normalizeDuration(io.siddhi.query.api.expression.Expression.Time.normalizeDuration) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) Expression(io.siddhi.query.api.expression.Expression) MatchingMetaInfoHolder(io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) CompiledSelection(io.siddhi.core.util.collection.operator.CompiledSelection) Map(java.util.Map) HashMap(java.util.HashMap) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 2 with SiddhiAppCreationException

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

the class IncrementalDataPurger method init.

public void init(AggregationDefinition aggregationDefinition, StreamEventFactory streamEventFactory, Map<TimePeriod.Duration, Table> aggregationTables, Boolean isProcessingOnExternalTime, SiddhiQueryContext siddhiQueryContext, List<TimePeriod.Duration> activeIncrementalDurations, String timeZone, Map<String, Window> windowMap, Map<String, AggregationRuntime> aggregationMap) {
    this.siddhiQueryContext = siddhiQueryContext;
    this.aggregationDefinition = aggregationDefinition;
    List<Annotation> annotations = aggregationDefinition.getAnnotations();
    this.streamEventFactory = streamEventFactory;
    this.aggregationTables = aggregationTables;
    this.activeIncrementalDurations = activeIncrementalDurations;
    this.windowMap = windowMap;
    this.aggregationMap = aggregationMap;
    if (isProcessingOnExternalTime) {
        purgingTimestampField = AGG_EXTERNAL_TIMESTAMP_COL;
    } else {
        purgingTimestampField = AGG_START_TIMESTAMP_COL;
    }
    aggregatedTimestampAttribute = new Attribute(purgingTimestampField, Attribute.Type.LONG);
    VariableExpressionExecutor variableExpressionExecutor = new VariableExpressionExecutor(aggregatedTimestampAttribute, 0, 1);
    variableExpressionExecutorList.add(variableExpressionExecutor);
    for (Map.Entry<TimePeriod.Duration, Table> entry : aggregationTables.entrySet()) {
        this.tableMap.put(entry.getValue().getTableDefinition().getId(), entry.getValue());
        switch(entry.getKey()) {
            case SECONDS:
                retentionPeriods.put(entry.getKey(), Expression.Time.sec(120).value());
                minimumDurationMap.put(entry.getKey(), Expression.Time.sec(120).value());
                break;
            case MINUTES:
                retentionPeriods.put(entry.getKey(), Expression.Time.hour(24).value());
                minimumDurationMap.put(entry.getKey(), Expression.Time.minute(120).value());
                break;
            case HOURS:
                retentionPeriods.put(entry.getKey(), Expression.Time.day(30).value());
                minimumDurationMap.put(entry.getKey(), Expression.Time.hour(25).value());
                break;
            case DAYS:
                retentionPeriods.put(entry.getKey(), Expression.Time.year(1).value());
                minimumDurationMap.put(entry.getKey(), Expression.Time.day(32).value());
                break;
            case MONTHS:
                retentionPeriods.put(entry.getKey(), RETAIN_ALL);
                minimumDurationMap.put(entry.getKey(), Expression.Time.month(13).value());
                break;
            case YEARS:
                retentionPeriods.put(entry.getKey(), RETAIN_ALL);
                minimumDurationMap.put(entry.getKey(), 0L);
        }
    }
    this.timeZone = timeZone;
    Map<String, Annotation> annotationTypes = new HashMap<>();
    for (Annotation annotation : annotations) {
        annotationTypes.put(annotation.getName().toLowerCase(), annotation);
    }
    Annotation purge = annotationTypes.get(SiddhiConstants.NAMESPACE_PURGE);
    if (purge != null) {
        if (purge.getElement(SiddhiConstants.ANNOTATION_ELEMENT_ENABLE) != null) {
            String purgeEnable = purge.getElement(SiddhiConstants.ANNOTATION_ELEMENT_ENABLE);
            if (!("true".equalsIgnoreCase(purgeEnable) || "false".equalsIgnoreCase(purgeEnable))) {
                throw new SiddhiAppCreationException("Invalid value for enable: " + purgeEnable + "." + " Please use true or false");
            } else {
                purgingEnabled = Boolean.parseBoolean(purgeEnable);
            }
        }
        if (purgingEnabled) {
            // If interval is defined, default value of 15 min will be replaced by user input value
            if (purge.getElement(SiddhiConstants.ANNOTATION_ELEMENT_INTERVAL) != null) {
                String interval = purge.getElement(SiddhiConstants.ANNOTATION_ELEMENT_INTERVAL);
                purgeExecutionInterval = timeToLong(interval);
            }
            List<Annotation> retentions = purge.getAnnotations(SiddhiConstants.NAMESPACE_RETENTION_PERIOD);
            if (retentions != null && !retentions.isEmpty()) {
                Annotation retention = retentions.get(0);
                List<Element> elements = retention.getElements();
                for (Element element : elements) {
                    TimePeriod.Duration duration = normalizeDuration(element.getKey());
                    if (!activeIncrementalDurations.contains(duration)) {
                        throw new SiddhiAppCreationException(duration + " granularity cannot be purged since " + "aggregation has not performed in " + duration + " granularity");
                    }
                    if (element.getValue().equalsIgnoreCase(RETAIN_ALL_VALUES)) {
                        retentionPeriods.put(duration, RETAIN_ALL);
                    } else {
                        if (timeToLong(element.getValue()) >= minimumDurationMap.get(duration)) {
                            retentionPeriods.put(duration, timeToLong(element.getValue()));
                        } else {
                            throw new SiddhiAppCreationException(duration + " granularity cannot be purge" + " with a retention of '" + element.getValue() + "', minimum retention" + " should be greater  than " + TimeUnit.MILLISECONDS.toMinutes(minimumDurationMap.get(duration)) + " minutes");
                        }
                    }
                }
            }
        }
    }
    compiledConditionsHolder = createCompileConditions(aggregationTables, tableMap);
}
Also used : Table(io.siddhi.core.table.Table) Attribute(io.siddhi.query.api.definition.Attribute) OrderByAttribute(io.siddhi.query.api.execution.query.selection.OrderByAttribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) HashMap(java.util.HashMap) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) Element(io.siddhi.query.api.annotation.Element) Time.normalizeDuration(io.siddhi.query.api.expression.Expression.Time.normalizeDuration) Annotation(io.siddhi.query.api.annotation.Annotation) HashMap(java.util.HashMap) Map(java.util.Map) EnumMap(java.util.EnumMap)

Example 3 with SiddhiAppCreationException

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

the class QueryParser method parse.

/**
 * Parse a query and return corresponding QueryRuntime.
 *
 * @param query                    query to be parsed.
 * @param siddhiAppContext         associated Siddhi app context.
 * @param streamDefinitionMap      keyvalue containing user given stream definitions.
 * @param tableDefinitionMap       keyvalue containing table definitions.
 * @param windowDefinitionMap      keyvalue containing window definition map.
 * @param aggregationDefinitionMap keyvalue containing aggregation definition map.
 * @param tableMap                 keyvalue containing event tables.
 * @param aggregationMap           keyvalue containing aggrigation runtimes.
 * @param windowMap                keyvalue containing event window map.
 * @param lockSynchronizer         Lock synchronizer for sync the lock across queries.
 * @param queryIndex               query index to identify unknown query by number
 * @param partitioned              is the query partitioned
 * @param partitionId              The ID of the partition
 * @return queryRuntime
 */
public static QueryRuntimeImpl parse(Query query, SiddhiAppContext siddhiAppContext, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, Map<String, AggregationRuntime> aggregationMap, Map<String, Window> windowMap, LockSynchronizer lockSynchronizer, String queryIndex, boolean partitioned, String partitionId) {
    List<VariableExpressionExecutor> executors = new ArrayList<>();
    QueryRuntimeImpl queryRuntime;
    Element nameElement = null;
    LatencyTracker latencyTracker = null;
    LockWrapper lockWrapper = null;
    try {
        nameElement = AnnotationHelper.getAnnotationElement("info", "name", query.getAnnotations());
        String queryName;
        if (nameElement != null) {
            queryName = nameElement.getValue();
        } else {
            queryName = "query_" + queryIndex;
        }
        SiddhiQueryContext siddhiQueryContext = new SiddhiQueryContext(siddhiAppContext, queryName, partitionId);
        siddhiQueryContext.setPartitioned(partitioned);
        latencyTracker = QueryParserHelper.createLatencyTracker(siddhiAppContext, siddhiQueryContext.getName(), SiddhiConstants.METRIC_INFIX_QUERIES, null);
        siddhiQueryContext.setLatencyTracker(latencyTracker);
        OutputStream.OutputEventType outputEventType = query.getOutputStream().getOutputEventType();
        if (query.getOutputRate() != null && query.getOutputRate() instanceof SnapshotOutputRate) {
            if (outputEventType != OutputStream.OutputEventType.ALL_EVENTS) {
                throw new SiddhiAppCreationException("As query '" + siddhiQueryContext.getName() + "' is performing snapshot rate limiting, it can only insert '" + OutputStream.OutputEventType.ALL_EVENTS + "' but it is inserting '" + outputEventType + "'!", query.getOutputStream().getQueryContextStartIndex(), query.getOutputStream().getQueryContextEndIndex());
            }
        }
        siddhiQueryContext.setOutputEventType(outputEventType);
        boolean outputExpectsExpiredEvents = false;
        if (outputEventType != OutputStream.OutputEventType.CURRENT_EVENTS) {
            outputExpectsExpiredEvents = true;
        }
        StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(), query, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, executors, outputExpectsExpiredEvents, siddhiQueryContext);
        QuerySelector selector;
        if (streamRuntime.getQuerySelector() != null) {
            selector = streamRuntime.getQuerySelector();
        } else {
            selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(), streamRuntime.getMetaComplexEvent(), tableMap, executors, SiddhiConstants.UNKNOWN_STATE, streamRuntime.getProcessingMode(), outputExpectsExpiredEvents, siddhiQueryContext);
        }
        boolean isWindow = query.getInputStream() instanceof JoinInputStream;
        if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
            for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
                if (streamHandler instanceof io.siddhi.query.api.execution.query.input.handler.Window) {
                    isWindow = true;
                    break;
                }
            }
        }
        Element synchronizedElement = AnnotationHelper.getAnnotationElement("synchronized", null, query.getAnnotations());
        if (synchronizedElement != null) {
            if (!("false".equalsIgnoreCase(synchronizedElement.getValue()))) {
                // Query LockWrapper does not need a unique
                lockWrapper = new LockWrapper("");
                // id since it will
                // not be passed to the LockSynchronizer.
                // LockWrapper does not have a default lock
                lockWrapper.setLock(new ReentrantLock());
            }
        } else {
            if (isWindow || !(streamRuntime instanceof SingleStreamRuntime)) {
                if (streamRuntime instanceof JoinStreamRuntime) {
                    // If at least one Window is involved in the join, use the LockWrapper of that window
                    // for the query as well.
                    // If join is between two EventWindows, sync the locks of the LockWrapper of those windows
                    // and use either of them for query.
                    MetaStateEvent metaStateEvent = (MetaStateEvent) streamRuntime.getMetaComplexEvent();
                    MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
                    if (metaStreamEvents[0].getEventType() == EventType.WINDOW && metaStreamEvents[1].getEventType() == EventType.WINDOW) {
                        LockWrapper leftLockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId()).getLock();
                        LockWrapper rightLockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId()).getLock();
                        if (!leftLockWrapper.equals(rightLockWrapper)) {
                            // Sync the lock across both wrappers
                            lockSynchronizer.sync(leftLockWrapper, rightLockWrapper);
                        }
                        // Can use either leftLockWrapper or rightLockWrapper since both of them will hold the
                        // same lock internally
                        // If either of their lock is updated later, the other lock also will be update by the
                        // LockSynchronizer.
                        lockWrapper = leftLockWrapper;
                    } else if (metaStreamEvents[0].getEventType() == EventType.WINDOW) {
                        // Share the same wrapper as the query lock wrapper
                        lockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId()).getLock();
                    } else if (metaStreamEvents[1].getEventType() == EventType.WINDOW) {
                        // Share the same wrapper as the query lock wrapper
                        lockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId()).getLock();
                    } else {
                        // Join does not contain any Window
                        // Query LockWrapper does not need a unique
                        lockWrapper = new LockWrapper("");
                        // id since
                        // it will not be passed to the LockSynchronizer.
                        // LockWrapper does not have a default lock
                        lockWrapper.setLock(new ReentrantLock());
                    }
                } else {
                    lockWrapper = new LockWrapper("");
                    lockWrapper.setLock(new ReentrantLock());
                }
            }
        }
        OutputRateLimiter outputRateLimiter = OutputParser.constructOutputRateLimiter(query.getOutputStream().getId(), query.getOutputRate(), query.getSelector().getGroupByList().size() != 0, isWindow, siddhiQueryContext);
        if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
            selector.setBatchingEnabled(false);
        }
        boolean groupBy = !query.getSelector().getGroupByList().isEmpty();
        OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(), streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), tableMap, windowMap, !(streamRuntime instanceof SingleStreamRuntime) || groupBy, siddhiQueryContext);
        QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
        QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
        QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent(), lockWrapper, siddhiQueryContext.getName());
        // Update cache compile selection variable expression executors
        if (streamRuntime instanceof JoinStreamRuntime) {
            streamRuntime.getSingleStreamRuntimes().forEach((singleStreamRuntime -> {
                Processor processorChain = singleStreamRuntime.getProcessorChain();
                if (processorChain instanceof JoinProcessor) {
                    CompiledSelection compiledSelection = ((JoinProcessor) processorChain).getCompiledSelection();
                    if (compiledSelection instanceof AbstractQueryableRecordTable.CompiledSelectionWithCache) {
                        List<VariableExpressionExecutor> variableExpressionExecutors = ((AbstractQueryableRecordTable.CompiledSelectionWithCache) compiledSelection).getVariableExpressionExecutorsForQuerySelector();
                        QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), variableExpressionExecutors);
                    }
                }
            }));
        }
        selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime.getMetaComplexEvent()));
        queryRuntime = new QueryRuntimeImpl(query, streamRuntime, selector, outputRateLimiter, outputCallback, streamRuntime.getMetaComplexEvent(), siddhiQueryContext);
        if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
            selector.setBatchingEnabled(false);
            ((WrappedSnapshotOutputRateLimiter) outputRateLimiter).init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(), selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
        }
        outputRateLimiter.init(lockWrapper, groupBy, siddhiQueryContext);
    } catch (DuplicateDefinitionException e) {
        if (nameElement != null) {
            throw new DuplicateDefinitionException(e.getMessageWithOutContext() + ", when creating query " + nameElement.getValue(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
        } else {
            throw new DuplicateDefinitionException(e.getMessage(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
        }
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, query, siddhiAppContext);
        throw t;
    }
    return queryRuntime;
}
Also used : DuplicateDefinitionException(io.siddhi.query.api.exception.DuplicateDefinitionException) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) AnnotationHelper(io.siddhi.query.api.util.AnnotationHelper) QueryRuntimeImpl(io.siddhi.core.query.QueryRuntimeImpl) OutputCallback(io.siddhi.core.query.output.callback.OutputCallback) SiddhiAppContext(io.siddhi.core.config.SiddhiAppContext) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SingleInputStream(io.siddhi.query.api.execution.query.input.stream.SingleInputStream) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) SiddhiConstants(io.siddhi.core.util.SiddhiConstants) CompiledSelection(io.siddhi.core.util.collection.operator.CompiledSelection) QuerySelector(io.siddhi.core.query.selector.QuerySelector) ArrayList(java.util.ArrayList) StreamRuntime(io.siddhi.core.query.input.stream.StreamRuntime) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) Query(io.siddhi.query.api.execution.query.Query) Table(io.siddhi.core.table.Table) LockSynchronizer(io.siddhi.core.util.lock.LockSynchronizer) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) AggregationRuntime(io.siddhi.core.aggregation.AggregationRuntime) Map(java.util.Map) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) WrappedSnapshotOutputRateLimiter(io.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) LockWrapper(io.siddhi.core.util.lock.LockWrapper) ReentrantLock(java.util.concurrent.locks.ReentrantLock) QueryRuntime(io.siddhi.core.query.QueryRuntime) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) EventType(io.siddhi.core.event.stream.MetaStreamEvent.EventType) OutputRateLimiter(io.siddhi.core.query.output.ratelimit.OutputRateLimiter) ExceptionUtil(io.siddhi.core.util.ExceptionUtil) StateEventPopulatorFactory(io.siddhi.core.event.state.populater.StateEventPopulatorFactory) Element(io.siddhi.query.api.annotation.Element) AbstractQueryableRecordTable(io.siddhi.core.table.record.AbstractQueryableRecordTable) List(java.util.List) JoinStreamRuntime(io.siddhi.core.query.input.stream.join.JoinStreamRuntime) OutputStream(io.siddhi.query.api.execution.query.output.stream.OutputStream) SnapshotOutputRate(io.siddhi.query.api.execution.query.output.ratelimit.SnapshotOutputRate) Processor(io.siddhi.core.query.processor.Processor) Window(io.siddhi.core.window.Window) QueryParserHelper(io.siddhi.core.util.parser.helper.QueryParserHelper) JoinProcessor(io.siddhi.core.query.input.stream.join.JoinProcessor) JoinInputStream(io.siddhi.query.api.execution.query.input.stream.JoinInputStream) StreamHandler(io.siddhi.query.api.execution.query.input.handler.StreamHandler) Processor(io.siddhi.core.query.processor.Processor) JoinProcessor(io.siddhi.core.query.input.stream.join.JoinProcessor) Element(io.siddhi.query.api.annotation.Element) OutputStream(io.siddhi.query.api.execution.query.output.stream.OutputStream) ArrayList(java.util.ArrayList) OutputCallback(io.siddhi.core.query.output.callback.OutputCallback) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) AbstractQueryableRecordTable(io.siddhi.core.table.record.AbstractQueryableRecordTable) JoinInputStream(io.siddhi.query.api.execution.query.input.stream.JoinInputStream) SingleInputStream(io.siddhi.query.api.execution.query.input.stream.SingleInputStream) WrappedSnapshotOutputRateLimiter(io.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) OutputRateLimiter(io.siddhi.core.query.output.ratelimit.OutputRateLimiter) StreamHandler(io.siddhi.query.api.execution.query.input.handler.StreamHandler) ArrayList(java.util.ArrayList) List(java.util.List) StreamRuntime(io.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) JoinStreamRuntime(io.siddhi.core.query.input.stream.join.JoinStreamRuntime) JoinProcessor(io.siddhi.core.query.input.stream.join.JoinProcessor) Window(io.siddhi.core.window.Window) ReentrantLock(java.util.concurrent.locks.ReentrantLock) DuplicateDefinitionException(io.siddhi.query.api.exception.DuplicateDefinitionException) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) JoinStreamRuntime(io.siddhi.core.query.input.stream.join.JoinStreamRuntime) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) QuerySelector(io.siddhi.core.query.selector.QuerySelector) LockWrapper(io.siddhi.core.util.lock.LockWrapper) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) SnapshotOutputRate(io.siddhi.query.api.execution.query.output.ratelimit.SnapshotOutputRate) QueryRuntimeImpl(io.siddhi.core.query.QueryRuntimeImpl) CompiledSelection(io.siddhi.core.util.collection.operator.CompiledSelection) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) WrappedSnapshotOutputRateLimiter(io.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 4 with SiddhiAppCreationException

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

the class SingleInputStreamParser method generateProcessor.

public static Processor generateProcessor(StreamHandler streamHandler, MetaComplexEvent metaEvent, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, boolean supportsBatchProcessing, boolean outputExpectsExpiredEvents, boolean findToBeExecuted, SiddhiQueryContext siddhiQueryContext) {
    Expression[] parameters = streamHandler.getParameters();
    MetaStreamEvent metaStreamEvent;
    int stateIndex = SiddhiConstants.UNKNOWN_STATE;
    if (metaEvent instanceof MetaStateEvent) {
        stateIndex = ((MetaStateEvent) metaEvent).getStreamEventCount() - 1;
        metaStreamEvent = ((MetaStateEvent) metaEvent).getMetaStreamEvent(stateIndex);
    } else {
        metaStreamEvent = (MetaStreamEvent) metaEvent;
    }
    if (streamHandler instanceof Window) {
        metaStreamEvent.initializeOnAfterWindowData();
    }
    ExpressionExecutor[] attributeExpressionExecutors;
    if (parameters != null) {
        if (parameters.length > 0) {
            attributeExpressionExecutors = new ExpressionExecutor[parameters.length];
            for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
                attributeExpressionExecutors[i] = ExpressionParser.parseExpression(parameters[i], metaEvent, stateIndex, tableMap, variableExpressionExecutors, false, SiddhiConstants.CURRENT, ProcessingMode.BATCH, false, siddhiQueryContext);
            }
        } else {
            List<Attribute> attributeList = metaStreamEvent.getLastInputDefinition().getAttributeList();
            int parameterSize = attributeList.size();
            attributeExpressionExecutors = new ExpressionExecutor[parameterSize];
            for (int i = 0; i < parameterSize; i++) {
                attributeExpressionExecutors[i] = ExpressionParser.parseExpression(new Variable(attributeList.get(i).getName()), metaEvent, stateIndex, tableMap, variableExpressionExecutors, false, SiddhiConstants.CURRENT, ProcessingMode.BATCH, false, siddhiQueryContext);
            }
        }
    } else {
        attributeExpressionExecutors = new ExpressionExecutor[0];
    }
    ConfigReader configReader;
    if (streamHandler instanceof Filter) {
        return new FilterProcessor(attributeExpressionExecutors[0]);
    } else if (streamHandler instanceof Window) {
        WindowProcessor windowProcessor = (WindowProcessor) SiddhiClassLoader.loadExtensionImplementation((Extension) streamHandler, WindowProcessorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
        configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader(((Window) streamHandler).getNamespace(), ((Window) streamHandler).getName());
        windowProcessor.initProcessor(metaStreamEvent, attributeExpressionExecutors, configReader, outputExpectsExpiredEvents, findToBeExecuted, false, streamHandler, siddhiQueryContext);
        return windowProcessor;
    } else if (streamHandler instanceof StreamFunction) {
        AbstractStreamProcessor abstractStreamProcessor;
        configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader(((StreamFunction) streamHandler).getNamespace(), ((StreamFunction) streamHandler).getName());
        if (supportsBatchProcessing) {
            try {
                abstractStreamProcessor = (StreamProcessor) SiddhiClassLoader.loadExtensionImplementation((Extension) streamHandler, StreamProcessorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                abstractStreamProcessor.initProcessor(metaStreamEvent, attributeExpressionExecutors, configReader, outputExpectsExpiredEvents, false, false, streamHandler, siddhiQueryContext);
                return abstractStreamProcessor;
            } catch (SiddhiAppCreationException e) {
                if (!e.isClassLoadingIssue()) {
                    ExceptionUtil.populateQueryContext(e, streamHandler, siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext);
                    throw e;
                }
            }
        }
        abstractStreamProcessor = (StreamFunctionProcessor) SiddhiClassLoader.loadExtensionImplementation((Extension) streamHandler, StreamFunctionProcessorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
        abstractStreamProcessor.initProcessor(metaStreamEvent, attributeExpressionExecutors, configReader, outputExpectsExpiredEvents, false, false, streamHandler, siddhiQueryContext);
        return abstractStreamProcessor;
    } else {
        throw new SiddhiAppCreationException(streamHandler.getClass().getName() + " is not supported", streamHandler.getQueryContextStartIndex(), streamHandler.getQueryContextEndIndex());
    }
}
Also used : Window(io.siddhi.query.api.execution.query.input.handler.Window) Variable(io.siddhi.query.api.expression.Variable) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) AbstractStreamProcessor(io.siddhi.core.query.processor.stream.AbstractStreamProcessor) Attribute(io.siddhi.query.api.definition.Attribute) FilterProcessor(io.siddhi.core.query.processor.filter.FilterProcessor) StreamFunction(io.siddhi.query.api.execution.query.input.handler.StreamFunction) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) ConfigReader(io.siddhi.core.util.config.ConfigReader) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) Expression(io.siddhi.query.api.expression.Expression) Filter(io.siddhi.query.api.execution.query.input.handler.Filter) WindowProcessor(io.siddhi.core.query.processor.stream.window.WindowProcessor) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 5 with SiddhiAppCreationException

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

the class JoinInputStreamParser method insertJoinProcessorsAndGetFindable.

private static FindableProcessor insertJoinProcessorsAndGetFindable(JoinProcessor preJoinProcessor, JoinProcessor postJoinProcessor, SingleStreamRuntime streamRuntime, boolean outputExpectsExpiredEvents, InputStream inputStream, SiddhiQueryContext siddhiQueryContext) {
    Processor lastProcessor = streamRuntime.getProcessorChain();
    Processor prevLastProcessor = null;
    boolean containFindable = false;
    if (lastProcessor != null) {
        containFindable = lastProcessor instanceof FindableProcessor;
        while (lastProcessor.getNextProcessor() != null) {
            prevLastProcessor = lastProcessor;
            lastProcessor = lastProcessor.getNextProcessor();
            if (!containFindable) {
                containFindable = lastProcessor instanceof FindableProcessor;
            }
        }
    }
    if (!containFindable) {
        try {
            WindowProcessor windowProcessor = new EmptyWindowProcessor();
            ExpressionExecutor[] expressionExecutors = new ExpressionExecutor[1];
            expressionExecutors[0] = new ConstantExpressionExecutor(0, Attribute.Type.INT);
            ConfigReader configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader("", "lengthBatch");
            windowProcessor.initProcessor(((MetaStreamEvent) streamRuntime.getMetaComplexEvent()), expressionExecutors, configReader, outputExpectsExpiredEvents, true, false, inputStream, siddhiQueryContext);
            if (lastProcessor != null) {
                prevLastProcessor = lastProcessor;
                prevLastProcessor.setNextProcessor(windowProcessor);
                lastProcessor = windowProcessor;
            } else {
                lastProcessor = windowProcessor;
            }
        } catch (Throwable t) {
            throw new SiddhiAppCreationException(t);
        }
    }
    if (lastProcessor instanceof FindableProcessor) {
        if (prevLastProcessor != null) {
            prevLastProcessor.setNextProcessor(preJoinProcessor);
        } else {
            streamRuntime.setProcessorChain(preJoinProcessor);
        }
        preJoinProcessor.setNextProcessor(lastProcessor);
        lastProcessor.setNextProcessor(postJoinProcessor);
        return (FindableProcessor) lastProcessor;
    } else {
        throw new OperationNotSupportedException("Stream " + ((MetaStreamEvent) streamRuntime.getMetaComplexEvent()).getLastInputDefinition().getId() + "'s last processor " + lastProcessor.getClass().getCanonicalName() + " is not an instance of " + FindableProcessor.class.getCanonicalName() + " hence join cannot be proceed");
    }
}
Also used : OperationNotSupportedException(io.siddhi.core.exception.OperationNotSupportedException) FindableProcessor(io.siddhi.core.query.processor.stream.window.FindableProcessor) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) EmptyWindowProcessor(io.siddhi.core.query.processor.stream.window.EmptyWindowProcessor) FindableProcessor(io.siddhi.core.query.processor.stream.window.FindableProcessor) Processor(io.siddhi.core.query.processor.Processor) JoinProcessor(io.siddhi.core.query.input.stream.join.JoinProcessor) TableWindowProcessor(io.siddhi.core.query.processor.stream.window.TableWindowProcessor) WindowProcessor(io.siddhi.core.query.processor.stream.window.WindowProcessor) WindowWindowProcessor(io.siddhi.core.query.processor.stream.window.WindowWindowProcessor) AggregateWindowProcessor(io.siddhi.core.query.processor.stream.window.AggregateWindowProcessor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) ConfigReader(io.siddhi.core.util.config.ConfigReader) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) EmptyWindowProcessor(io.siddhi.core.query.processor.stream.window.EmptyWindowProcessor) EmptyWindowProcessor(io.siddhi.core.query.processor.stream.window.EmptyWindowProcessor) TableWindowProcessor(io.siddhi.core.query.processor.stream.window.TableWindowProcessor) WindowProcessor(io.siddhi.core.query.processor.stream.window.WindowProcessor) WindowWindowProcessor(io.siddhi.core.query.processor.stream.window.WindowWindowProcessor) AggregateWindowProcessor(io.siddhi.core.query.processor.stream.window.AggregateWindowProcessor) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

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