Search in sources :

Example 1 with StreamEventPool

use of org.ballerinalang.siddhi.core.event.stream.StreamEventPool in project ballerina by ballerina-lang.

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) {
    if (aggregationDefinition == null) {
        throw new SiddhiAppCreationException("AggregationDefinition instance is null. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'");
    }
    if (aggregationDefinition.getTimePeriod() == null) {
        throw new SiddhiAppCreationException("AggregationDefinition '" + 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("AggregationDefinition '" + 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");
    }
    try {
        List<VariableExpressionExecutor> incomingVariableExpressionExecutors = new ArrayList<>();
        String aggregatorName = aggregationDefinition.getId();
        StreamRuntime streamRuntime = InputStreamParser.parse(aggregationDefinition.getBasicSingleInputStream(), siddhiAppContext, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, incomingVariableExpressionExecutors, null, false, aggregatorName);
        // 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.initializeAfterWindowData();
        List<ExpressionExecutor> incomingExpressionExecutors = new ArrayList<>();
        List<IncrementalAttributeAggregator> incrementalAttributeAggregators = new ArrayList<>();
        List<Variable> groupByVariableList = aggregationDefinition.getSelector().getGroupByList();
        boolean isProcessingOnExternalTime = aggregationDefinition.getAggregateAttribute() != null;
        // Expressions to get
        List<Expression> outputExpressions = new ArrayList<>();
        // final aggregate outputs. e.g avg = sum/count
        // Expression executors to get
        List<ExpressionExecutor> outputExpressionExecutors = new ArrayList<>();
        // final aggregate outputs. e.g avg = sum/count
        populateIncomingAggregatorsAndExecutors(aggregationDefinition, siddhiAppContext, tableMap, incomingVariableExpressionExecutors, aggregatorName, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, groupByVariableList, outputExpressions);
        int baseAggregatorBeginIndex = incomingMetaStreamEvent.getOutputData().size();
        List<Expression> finalBaseAggregators = getFinalBaseAggregators(siddhiAppContext, tableMap, incomingVariableExpressionExecutors, aggregatorName, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators);
        StreamDefinition incomingOutputStreamDefinition = StreamDefinition.id("");
        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<>();
        boolean groupBy = aggregationDefinition.getSelector().getGroupByList().size() != 0;
        List<ExpressionExecutor> processExpressionExecutors = constructProcessExpressionExecutors(siddhiAppContext, tableMap, aggregatorName, baseAggregatorBeginIndex, finalBaseAggregators, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, groupBy);
        outputExpressionExecutors.addAll(outputExpressions.stream().map(expression -> ExpressionParser.parseExpression(expression, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, siddhiAppContext, groupBy, 0, aggregatorName)).collect(Collectors.toList()));
        // Create group by key generator
        GroupByKeyGenerator groupByKeyGenerator = null;
        if (groupBy) {
            groupByKeyGenerator = new GroupByKeyGenerator(groupByVariableList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiAppContext, aggregatorName);
        }
        // Create new scheduler
        EntryValveExecutor entryValveExecutor = new EntryValveExecutor(siddhiAppContext);
        LockWrapper lockWrapper = new LockWrapper(aggregatorName);
        lockWrapper.setLock(new ReentrantLock());
        Scheduler scheduler = SchedulerParser.parse(siddhiAppContext.getScheduledExecutorService(), entryValveExecutor, siddhiAppContext);
        scheduler.init(lockWrapper, aggregatorName);
        scheduler.setStreamEventPool(new StreamEventPool(processedMetaStreamEvent, 10));
        QueryParserHelper.reduceMetaComplexEvent(incomingMetaStreamEvent);
        QueryParserHelper.reduceMetaComplexEvent(processedMetaStreamEvent);
        QueryParserHelper.updateVariablePosition(incomingMetaStreamEvent, incomingVariableExpressionExecutors);
        QueryParserHelper.updateVariablePosition(processedMetaStreamEvent, processVariableExpressionExecutors);
        List<TimePeriod.Duration> incrementalDurations = getSortedPeriods(aggregationDefinition.getTimePeriod());
        Map<TimePeriod.Duration, Table> aggregationTables = initDefaultTables(aggregatorName, incrementalDurations, processedMetaStreamEvent.getOutputStreamDefinition(), siddhiAppRuntimeBuilder, aggregationDefinition.getAnnotations(), groupByVariableList);
        int bufferSize = 0;
        Element element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_BUFFER_SIZE, null, aggregationDefinition.getAnnotations());
        if (element != null) {
            try {
                bufferSize = Integer.parseInt(element.getValue());
            } catch (NumberFormatException e) {
                throw new SiddhiAppCreationException(e.getMessage() + ": BufferSize must be an integer");
            }
        }
        if (bufferSize > 0) {
            TimePeriod.Duration rootDuration = incrementalDurations.get(0);
            if (rootDuration == TimePeriod.Duration.MONTHS || rootDuration == TimePeriod.Duration.YEARS) {
                throw new SiddhiAppCreationException("A buffer size greater than 0 can be provided, only when the " + "first duration value is seconds, minutes, hours or days");
            }
            if (!isProcessingOnExternalTime) {
                throw new SiddhiAppCreationException("Buffer size cannot be specified when events are aggregated " + "based on event arrival time.");
            // Buffer size is used to process out of order events. However, events would never be out of
            // order if they are processed based on event arrival time.
            }
        } else if (bufferSize < 0) {
            throw new SiddhiAppCreationException("Expected a positive integer as the buffer size, but found " + bufferSize + " as the provided value");
        }
        boolean ignoreEventsOlderThanBuffer = false;
        element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_IGNORE_EVENTS_OLDER_THAN_BUFFER, null, aggregationDefinition.getAnnotations());
        if (element != null) {
            if (element.getValue().equalsIgnoreCase("true")) {
                ignoreEventsOlderThanBuffer = true;
            } else if (!element.getValue().equalsIgnoreCase("false")) {
                throw new SiddhiAppCreationException("IgnoreEventsOlderThanBuffer value must " + "be true or false");
            }
        }
        Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap = buildIncrementalExecutors(isProcessingOnExternalTime, processedMetaStreamEvent, processExpressionExecutors, groupByKeyGenerator, bufferSize, ignoreEventsOlderThanBuffer, incrementalDurations, aggregationTables, siddhiAppContext, aggregatorName);
        // Recreate in-memory data from tables
        RecreateInMemoryData recreateInMemoryData = new RecreateInMemoryData(incrementalDurations, aggregationTables, incrementalExecutorMap, siddhiAppContext, processedMetaStreamEvent, tableMap, windowMap, aggregationMap);
        IncrementalExecutor rootIncrementalExecutor = incrementalExecutorMap.get(incrementalDurations.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(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_FIND);
            latencyTrackerInsert = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_INSERT);
            throughputTrackerFind = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_FIND);
            throughputTrackerInsert = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_INSERT);
        }
        streamRuntime.setCommonProcessor(new IncrementalAggregationProcessor(rootIncrementalExecutor, incomingExpressionExecutors, processedMetaStreamEvent, latencyTrackerInsert, throughputTrackerInsert, siddhiAppContext));
        List<ExpressionExecutor> baseExecutors = cloneExpressionExecutors(processExpressionExecutors);
        ExpressionExecutor timestampExecutor = baseExecutors.remove(0);
        return new AggregationRuntime(aggregationDefinition, incrementalExecutorMap, aggregationTables, ((SingleStreamRuntime) streamRuntime), entryValveExecutor, incrementalDurations, siddhiAppContext, baseExecutors, timestampExecutor, processedMetaStreamEvent, outputExpressionExecutors, latencyTrackerFind, throughputTrackerFind, recreateInMemoryData);
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, aggregationDefinition, siddhiAppContext);
        throw t;
    }
}
Also used : Variable(org.ballerinalang.siddhi.query.api.expression.Variable) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) OutputAttribute(org.ballerinalang.siddhi.query.api.execution.query.selection.OutputAttribute) Scheduler(org.ballerinalang.siddhi.core.util.Scheduler) GroupByKeyGenerator(org.ballerinalang.siddhi.core.query.selector.GroupByKeyGenerator) Element(org.ballerinalang.siddhi.query.api.annotation.Element) ArrayList(java.util.ArrayList) IncrementalExecutor(org.ballerinalang.siddhi.core.aggregation.IncrementalExecutor) StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool) StreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) IncrementalAggregationProcessor(org.ballerinalang.siddhi.core.aggregation.IncrementalAggregationProcessor) AggregationRuntime(org.ballerinalang.siddhi.core.aggregation.AggregationRuntime) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ThroughputTracker(org.ballerinalang.siddhi.core.util.statistics.ThroughputTracker) Table(org.ballerinalang.siddhi.core.table.Table) ExpressionExecutor(org.ballerinalang.siddhi.core.executor.ExpressionExecutor) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) StreamDefinition(org.ballerinalang.siddhi.query.api.definition.StreamDefinition) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) TimePeriod(org.ballerinalang.siddhi.query.api.aggregation.TimePeriod) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) EntryValveExecutor(org.ballerinalang.siddhi.core.query.input.stream.single.EntryValveExecutor) LockWrapper(org.ballerinalang.siddhi.core.util.lock.LockWrapper) Expression(org.ballerinalang.siddhi.query.api.expression.Expression) IncrementalAttributeAggregator(org.ballerinalang.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) RecreateInMemoryData(org.ballerinalang.siddhi.core.aggregation.RecreateInMemoryData) LatencyTracker(org.ballerinalang.siddhi.core.util.statistics.LatencyTracker) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)

Example 2 with StreamEventPool

use of org.ballerinalang.siddhi.core.event.stream.StreamEventPool in project ballerina by ballerina-lang.

the class EventHolderPasser method parse.

public static EventHolder parse(AbstractDefinition tableDefinition, StreamEventPool tableStreamEventPool, SiddhiAppContext siddhiAppContext) {
    ZeroStreamEventConverter eventConverter = new ZeroStreamEventConverter();
    PrimaryKeyReferenceHolder[] primaryKeyReferenceHolders = null;
    Map<String, Integer> indexMetaData = new HashMap<String, Integer>();
    // primaryKey.
    Annotation primaryKeyAnnotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_PRIMARY_KEY, tableDefinition.getAnnotations());
    if (primaryKeyAnnotation != null) {
        if (primaryKeyAnnotation.getElements().size() == 0) {
            throw new SiddhiAppValidationException(SiddhiConstants.ANNOTATION_PRIMARY_KEY + " annotation " + "contains " + primaryKeyAnnotation.getElements().size() + " element, at '" + tableDefinition.getId() + "'");
        }
        primaryKeyReferenceHolders = primaryKeyAnnotation.getElements().stream().map(element -> element.getValue().trim()).map(key -> new PrimaryKeyReferenceHolder(key, tableDefinition.getAttributePosition(key))).toArray(PrimaryKeyReferenceHolder[]::new);
    }
    // indexes.
    Annotation indexAnnotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_INDEX, tableDefinition.getAnnotations());
    if (indexAnnotation != null) {
        if (indexAnnotation.getElements().size() == 0) {
            throw new SiddhiAppValidationException(SiddhiConstants.ANNOTATION_INDEX + " annotation contains " + indexAnnotation.getElements().size() + " element");
        }
        for (Element element : indexAnnotation.getElements()) {
            Integer previousValue = indexMetaData.put(element.getValue().trim(), tableDefinition.getAttributePosition(element.getValue().trim()));
            if (previousValue != null) {
                throw new SiddhiAppCreationException("Multiple " + SiddhiConstants.ANNOTATION_INDEX + " " + "annotations defined with same attribute '" + element.getValue().trim() + "', at '" + tableDefinition.getId() + "'", indexAnnotation.getQueryContextStartIndex(), indexAnnotation.getQueryContextEndIndex());
            }
        }
    }
    // not support indexBy.
    Annotation indexByAnnotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_INDEX_BY, tableDefinition.getAnnotations());
    if (indexByAnnotation != null) {
        throw new OperationNotSupportedException(SiddhiConstants.ANNOTATION_INDEX_BY + " annotation is not " + "supported anymore, please use @PrimaryKey or @Index annotations instead," + " at '" + tableDefinition.getId() + "'");
    }
    if (primaryKeyReferenceHolders != null || indexMetaData.size() > 0) {
        boolean isNumeric = false;
        if (primaryKeyReferenceHolders != null) {
            if (primaryKeyReferenceHolders.length == 1) {
                Attribute.Type type = tableDefinition.getAttributeType(primaryKeyReferenceHolders[0].getPrimaryKeyAttribute());
                if (type == Attribute.Type.DOUBLE || type == Attribute.Type.FLOAT || type == Attribute.Type.INT || type == Attribute.Type.LONG) {
                    isNumeric = true;
                }
            }
        }
        return new IndexEventHolder(tableStreamEventPool, eventConverter, primaryKeyReferenceHolders, isNumeric, indexMetaData, tableDefinition, siddhiAppContext);
    } else {
        return new ListEventHolder(tableStreamEventPool, eventConverter);
    }
}
Also used : EventHolder(org.ballerinalang.siddhi.core.table.holder.EventHolder) Logger(org.slf4j.Logger) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) Annotation(org.ballerinalang.siddhi.query.api.annotation.Annotation) SiddhiConstants(org.ballerinalang.siddhi.core.util.SiddhiConstants) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) SiddhiAppValidationException(org.ballerinalang.siddhi.query.api.exception.SiddhiAppValidationException) SiddhiAppContext(org.ballerinalang.siddhi.core.config.SiddhiAppContext) ZeroStreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter) StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool) Element(org.ballerinalang.siddhi.query.api.annotation.Element) PrimaryKeyReferenceHolder(org.ballerinalang.siddhi.core.table.holder.PrimaryKeyReferenceHolder) AnnotationHelper(org.ballerinalang.siddhi.query.api.util.AnnotationHelper) OperationNotSupportedException(org.ballerinalang.siddhi.core.exception.OperationNotSupportedException) Map(java.util.Map) IndexEventHolder(org.ballerinalang.siddhi.core.table.holder.IndexEventHolder) ListEventHolder(org.ballerinalang.siddhi.core.table.holder.ListEventHolder) AbstractDefinition(org.ballerinalang.siddhi.query.api.definition.AbstractDefinition) OperationNotSupportedException(org.ballerinalang.siddhi.core.exception.OperationNotSupportedException) IndexEventHolder(org.ballerinalang.siddhi.core.table.holder.IndexEventHolder) HashMap(java.util.HashMap) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) Element(org.ballerinalang.siddhi.query.api.annotation.Element) SiddhiAppValidationException(org.ballerinalang.siddhi.query.api.exception.SiddhiAppValidationException) PrimaryKeyReferenceHolder(org.ballerinalang.siddhi.core.table.holder.PrimaryKeyReferenceHolder) Annotation(org.ballerinalang.siddhi.query.api.annotation.Annotation) ZeroStreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter) ListEventHolder(org.ballerinalang.siddhi.core.table.holder.ListEventHolder)

Example 3 with StreamEventPool

use of org.ballerinalang.siddhi.core.event.stream.StreamEventPool in project ballerina by ballerina-lang.

the class OutputParser method constructOutputCallback.

public static OutputCallback constructOutputCallback(final OutputStream outStream, StreamDefinition outputStreamDefinition, Map<String, Table> tableMap, Map<String, Window> eventWindowMap, SiddhiAppContext siddhiAppContext, boolean convertToStreamEvent, String queryName) {
    String id = outStream.getId();
    Table table = null;
    Window window = null;
    if (id != null) {
        table = tableMap.get(id);
        window = eventWindowMap.get(id);
    }
    StreamEventPool streamEventPool = null;
    StreamEventConverter streamEventConverter = null;
    MetaStreamEvent tableMetaStreamEvent = null;
    if (table != null) {
        tableMetaStreamEvent = new MetaStreamEvent();
        tableMetaStreamEvent.setEventType(MetaStreamEvent.EventType.TABLE);
        TableDefinition matchingTableDefinition = TableDefinition.id("");
        for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
            tableMetaStreamEvent.addOutputData(attribute);
            matchingTableDefinition.attribute(attribute.getName(), attribute.getType());
        }
        matchingTableDefinition.setQueryContextStartIndex(outStream.getQueryContextStartIndex());
        matchingTableDefinition.setQueryContextEndIndex(outStream.getQueryContextEndIndex());
        tableMetaStreamEvent.addInputDefinition(matchingTableDefinition);
        streamEventPool = new StreamEventPool(tableMetaStreamEvent, 10);
        streamEventConverter = new ZeroStreamEventConverter();
    }
    // Construct CallBack
    if (outStream instanceof InsertIntoStream) {
        if (window != null) {
            return new InsertIntoWindowCallback(window, outputStreamDefinition, queryName);
        } else if (table != null) {
            DefinitionParserHelper.validateOutputStream(outputStreamDefinition, table.getTableDefinition());
            return new InsertIntoTableCallback(table, outputStreamDefinition, convertToStreamEvent, streamEventPool, streamEventConverter, queryName);
        } else {
            return new InsertIntoStreamCallback(outputStreamDefinition, queryName);
        }
    } else if (outStream instanceof DeleteStream || outStream instanceof UpdateStream || outStream instanceof UpdateOrInsertStream) {
        if (table != null) {
            if (outStream instanceof UpdateStream) {
                if (((UpdateStream) outStream).getUpdateSet() == null) {
                    TableDefinition tableDefinition = table.getTableDefinition();
                    for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
                        if (!tableDefinition.getAttributeList().contains(attribute)) {
                            throw new SiddhiAppCreationException("Attribute " + attribute + " does not exist on " + "Event Table " + tableDefinition, outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
                        }
                    }
                }
            }
            if (outStream instanceof UpdateOrInsertStream) {
                TableDefinition tableDefinition = table.getTableDefinition();
                for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
                    if (!tableDefinition.getAttributeList().contains(attribute)) {
                        throw new SiddhiAppCreationException("Attribute " + attribute + " does not exist on " + "Event Table " + tableDefinition, outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
                    }
                }
            }
            if (outStream instanceof DeleteStream) {
                try {
                    MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(tableMetaStreamEvent, 0, table.getTableDefinition(), 0);
                    CompiledCondition compiledCondition = table.compileCondition((((DeleteStream) outStream).getOnDeleteExpression()), matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    StateEventPool stateEventPool = new StateEventPool(matchingMetaInfoHolder.getMetaStateEvent(), 10);
                    return new DeleteTableCallback(table, compiledCondition, matchingMetaInfoHolder.getMatchingStreamEventIndex(), convertToStreamEvent, stateEventPool, streamEventPool, streamEventConverter, queryName);
                } catch (SiddhiAppValidationException e) {
                    throw new SiddhiAppCreationException("Cannot create delete for table '" + outStream.getId() + "', " + e.getMessageWithOutContext(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
                }
            } else if (outStream instanceof UpdateStream) {
                try {
                    MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(tableMetaStreamEvent, 0, table.getTableDefinition(), 0);
                    CompiledCondition compiledCondition = table.compileCondition((((UpdateStream) outStream).getOnUpdateExpression()), matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    UpdateSet updateSet = ((UpdateStream) outStream).getUpdateSet();
                    if (updateSet == null) {
                        updateSet = new UpdateSet();
                        for (Attribute attribute : matchingMetaInfoHolder.getMatchingStreamDefinition().getAttributeList()) {
                            updateSet.set(new Variable(attribute.getName()), new Variable(attribute.getName()));
                        }
                    }
                    CompiledUpdateSet compiledUpdateSet = table.compileUpdateSet(updateSet, matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    StateEventPool stateEventPool = new StateEventPool(matchingMetaInfoHolder.getMetaStateEvent(), 10);
                    return new UpdateTableCallback(table, compiledCondition, compiledUpdateSet, matchingMetaInfoHolder.getMatchingStreamEventIndex(), convertToStreamEvent, stateEventPool, streamEventPool, streamEventConverter, queryName);
                } catch (SiddhiAppValidationException e) {
                    throw new SiddhiAppCreationException("Cannot create update for table '" + outStream.getId() + "', " + e.getMessageWithOutContext(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext);
                }
            } else {
                DefinitionParserHelper.validateOutputStream(outputStreamDefinition, table.getTableDefinition());
                try {
                    MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(tableMetaStreamEvent, 0, table.getTableDefinition(), 0);
                    CompiledCondition compiledCondition = table.compileCondition((((UpdateOrInsertStream) outStream).getOnUpdateExpression()), matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    UpdateSet updateSet = ((UpdateOrInsertStream) outStream).getUpdateSet();
                    if (updateSet == null) {
                        updateSet = new UpdateSet();
                        for (Attribute attribute : matchingMetaInfoHolder.getMatchingStreamDefinition().getAttributeList()) {
                            updateSet.set(new Variable(attribute.getName()), new Variable(attribute.getName()));
                        }
                    }
                    CompiledUpdateSet compiledUpdateSet = table.compileUpdateSet(updateSet, matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    StateEventPool stateEventPool = new StateEventPool(matchingMetaInfoHolder.getMetaStateEvent(), 10);
                    return new UpdateOrInsertTableCallback(table, compiledCondition, compiledUpdateSet, matchingMetaInfoHolder.getMatchingStreamEventIndex(), convertToStreamEvent, stateEventPool, streamEventPool, streamEventConverter, queryName);
                } catch (SiddhiAppValidationException e) {
                    throw new SiddhiAppCreationException("Cannot create update or insert into for table '" + outStream.getId() + "', " + e.getMessageWithOutContext(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext);
                }
            }
        } else {
            throw new SiddhiAppCreationException("Event table with id :" + id + " does not exist", outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
        }
    } else {
        throw new SiddhiAppCreationException(outStream.getClass().getName() + " not supported", outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
    }
}
Also used : Variable(org.ballerinalang.siddhi.query.api.expression.Variable) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) InsertIntoWindowCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoWindowCallback) UpdateStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.UpdateStream) ZeroStreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter) UpdateTableCallback(org.ballerinalang.siddhi.core.query.output.callback.UpdateTableCallback) DeleteStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.DeleteStream) StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool) UpdateOrInsertTableCallback(org.ballerinalang.siddhi.core.query.output.callback.UpdateOrInsertTableCallback) TableDefinition(org.ballerinalang.siddhi.query.api.definition.TableDefinition) InsertIntoTableCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoTableCallback) Window(org.ballerinalang.siddhi.core.window.Window) Table(org.ballerinalang.siddhi.core.table.Table) StateEventPool(org.ballerinalang.siddhi.core.event.state.StateEventPool) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) StreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.StreamEventConverter) ZeroStreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter) InsertIntoStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.InsertIntoStream) SiddhiAppValidationException(org.ballerinalang.siddhi.query.api.exception.SiddhiAppValidationException) InsertIntoStreamCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoStreamCallback) CompiledUpdateSet(org.ballerinalang.siddhi.core.table.CompiledUpdateSet) UpdateOrInsertStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.UpdateOrInsertStream) CompiledCondition(org.ballerinalang.siddhi.core.util.collection.operator.CompiledCondition) MatchingMetaInfoHolder(org.ballerinalang.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) DeleteTableCallback(org.ballerinalang.siddhi.core.query.output.callback.DeleteTableCallback) UpdateSet(org.ballerinalang.siddhi.query.api.execution.query.output.stream.UpdateSet) CompiledUpdateSet(org.ballerinalang.siddhi.core.table.CompiledUpdateSet) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)

Example 4 with StreamEventPool

use of org.ballerinalang.siddhi.core.event.stream.StreamEventPool in project ballerina by ballerina-lang.

the class QueryParserHelper method initSingleStreamRuntime.

private static void initSingleStreamRuntime(SingleStreamRuntime singleStreamRuntime, int streamEventChainIndex, MetaComplexEvent metaComplexEvent, StateEventPool stateEventPool, LockWrapper lockWrapper, String queryName) {
    MetaStreamEvent metaStreamEvent;
    if (metaComplexEvent instanceof MetaStateEvent) {
        metaStreamEvent = ((MetaStateEvent) metaComplexEvent).getMetaStreamEvent(streamEventChainIndex);
    } else {
        metaStreamEvent = (MetaStreamEvent) metaComplexEvent;
    }
    StreamEventPool streamEventPool = new StreamEventPool(metaStreamEvent, 5);
    ProcessStreamReceiver processStreamReceiver = singleStreamRuntime.getProcessStreamReceiver();
    processStreamReceiver.setMetaStreamEvent(metaStreamEvent);
    processStreamReceiver.setStreamEventPool(streamEventPool);
    processStreamReceiver.setLockWrapper(lockWrapper);
    processStreamReceiver.init();
    Processor processor = singleStreamRuntime.getProcessorChain();
    while (processor != null) {
        if (processor instanceof SchedulingProcessor) {
            ((SchedulingProcessor) processor).getScheduler().setStreamEventPool(streamEventPool);
            ((SchedulingProcessor) processor).getScheduler().init(lockWrapper, queryName);
        }
        if (processor instanceof AbstractStreamProcessor) {
            ((AbstractStreamProcessor) processor).setStreamEventCloner(new StreamEventCloner(metaStreamEvent, streamEventPool));
            ((AbstractStreamProcessor) processor).constructStreamEventPopulater(metaStreamEvent, streamEventChainIndex);
        }
        if (stateEventPool != null && processor instanceof JoinProcessor) {
            if (((JoinProcessor) processor).getCompiledCondition() instanceof IncrementalAggregateCompileCondition) {
                IncrementalAggregateCompileCondition compiledCondition = (IncrementalAggregateCompileCondition) ((JoinProcessor) processor).getCompiledCondition();
                ComplexEventPopulater complexEventPopulater = StreamEventPopulaterFactory.constructEventPopulator(metaStreamEvent, 0, compiledCondition.getAdditionalAttributes());
                compiledCondition.setComplexEventPopulater(complexEventPopulater);
            }
            ((JoinProcessor) processor).setStateEventPool(stateEventPool);
            ((JoinProcessor) processor).setJoinLock(lockWrapper);
        }
        if (stateEventPool != null && processor instanceof StreamPreStateProcessor) {
            ((StreamPreStateProcessor) processor).setStateEventPool(stateEventPool);
            ((StreamPreStateProcessor) processor).setStreamEventPool(streamEventPool);
            ((StreamPreStateProcessor) processor).setStreamEventCloner(new StreamEventCloner(metaStreamEvent, streamEventPool));
            if (metaComplexEvent instanceof MetaStateEvent) {
                ((StreamPreStateProcessor) processor).setStateEventCloner(new StateEventCloner(((MetaStateEvent) metaComplexEvent), stateEventPool));
            }
        }
        processor = processor.getNextProcessor();
    }
}
Also used : ProcessStreamReceiver(org.ballerinalang.siddhi.core.query.input.ProcessStreamReceiver) Processor(org.ballerinalang.siddhi.core.query.processor.Processor) StreamPreStateProcessor(org.ballerinalang.siddhi.core.query.input.stream.state.StreamPreStateProcessor) JoinProcessor(org.ballerinalang.siddhi.core.query.input.stream.join.JoinProcessor) AbstractStreamProcessor(org.ballerinalang.siddhi.core.query.processor.stream.AbstractStreamProcessor) SchedulingProcessor(org.ballerinalang.siddhi.core.query.processor.SchedulingProcessor) AbstractStreamProcessor(org.ballerinalang.siddhi.core.query.processor.stream.AbstractStreamProcessor) IncrementalAggregateCompileCondition(org.ballerinalang.siddhi.core.util.collection.operator.IncrementalAggregateCompileCondition) ComplexEventPopulater(org.ballerinalang.siddhi.core.event.stream.populater.ComplexEventPopulater) StreamPreStateProcessor(org.ballerinalang.siddhi.core.query.input.stream.state.StreamPreStateProcessor) MetaStateEvent(org.ballerinalang.siddhi.core.event.state.MetaStateEvent) SchedulingProcessor(org.ballerinalang.siddhi.core.query.processor.SchedulingProcessor) StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool) StreamEventCloner(org.ballerinalang.siddhi.core.event.stream.StreamEventCloner) JoinProcessor(org.ballerinalang.siddhi.core.query.input.stream.join.JoinProcessor) StateEventCloner(org.ballerinalang.siddhi.core.event.state.StateEventCloner) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)

Example 5 with StreamEventPool

use of org.ballerinalang.siddhi.core.event.stream.StreamEventPool in project ballerina by ballerina-lang.

the class AggregationWindowedPerSnapshotOutputRateLimiter method start.

@Override
public void start() {
    scheduler = SchedulerParser.parse(scheduledExecutorService, this, siddhiAppContext);
    scheduler.setStreamEventPool(new StreamEventPool(0, 0, 0, 5));
    scheduler.init(lockWrapper, queryName);
    long currentTime = System.currentTimeMillis();
    scheduledTime = currentTime + value;
    scheduler.notifyAt(scheduledTime);
}
Also used : StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool)

Aggregations

StreamEventPool (org.ballerinalang.siddhi.core.event.stream.StreamEventPool)34 StreamEvent (org.ballerinalang.siddhi.core.event.stream.StreamEvent)16 MetaStreamEvent (org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)15 Test (org.testng.annotations.Test)11 StreamEventConverter (org.ballerinalang.siddhi.core.event.stream.converter.StreamEventConverter)9 Attribute (org.ballerinalang.siddhi.query.api.definition.Attribute)8 Event (org.ballerinalang.siddhi.core.event.Event)6 ConversionStreamEventChunk (org.ballerinalang.siddhi.core.event.stream.converter.ConversionStreamEventChunk)6 MetaStateEvent (org.ballerinalang.siddhi.core.event.state.MetaStateEvent)5 ZeroStreamEventConverter (org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter)5 StreamDefinition (org.ballerinalang.siddhi.query.api.definition.StreamDefinition)5 StreamEventCloner (org.ballerinalang.siddhi.core.event.stream.StreamEventCloner)4 ComplexEvent (org.ballerinalang.siddhi.core.event.ComplexEvent)3 SelectiveStreamEventConverter (org.ballerinalang.siddhi.core.event.stream.converter.SelectiveStreamEventConverter)3 SimpleStreamEventConverter (org.ballerinalang.siddhi.core.event.stream.converter.SimpleStreamEventConverter)3 SiddhiAppCreationException (org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException)3 Table (org.ballerinalang.siddhi.core.table.Table)3 ArrayList (java.util.ArrayList)2 StateEventCloner (org.ballerinalang.siddhi.core.event.state.StateEventCloner)2 StateEventPool (org.ballerinalang.siddhi.core.event.state.StateEventPool)2