Search in sources :

Example 6 with QueryRuntime

use of org.ballerinalang.siddhi.core.query.QueryRuntime in project ballerina by ballerina-lang.

the class PartitionParser method parse.

public static PartitionRuntime parse(SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder, Partition partition, SiddhiAppContext siddhiAppContext, ConcurrentMap<String, AbstractDefinition> streamDefinitionMap, int queryIndex) {
    PartitionRuntime partitionRuntime = new PartitionRuntime(siddhiAppRuntimeBuilder.getStreamDefinitionMap(), siddhiAppRuntimeBuilder.getStreamJunctions(), partition, siddhiAppContext);
    validateStreamPartitions(partition.getPartitionTypeMap(), streamDefinitionMap);
    for (Query query : partition.getQueryList()) {
        List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
        ConcurrentMap<String, AbstractDefinition> combinedStreamMap = new ConcurrentHashMap<String, AbstractDefinition>();
        combinedStreamMap.putAll(streamDefinitionMap);
        combinedStreamMap.putAll(partitionRuntime.getLocalStreamDefinitionMap());
        QueryRuntime queryRuntime = QueryParser.parse(query, siddhiAppContext, combinedStreamMap, siddhiAppRuntimeBuilder.getTableDefinitionMap(), siddhiAppRuntimeBuilder.getWindowDefinitionMap(), siddhiAppRuntimeBuilder.getAggregationDefinitionMap(), siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getAggregationMap(), siddhiAppRuntimeBuilder.getWindowMap(), siddhiAppRuntimeBuilder.getLockSynchronizer(), String.valueOf(queryIndex));
        queryIndex++;
        MetaStateEvent metaStateEvent = createMetaEventForPartitioner(queryRuntime.getMetaComplexEvent());
        partitionRuntime.addQuery(queryRuntime);
        partitionRuntime.addPartitionReceiver(queryRuntime, executors, metaStateEvent);
        QueryParserHelper.reduceMetaComplexEvent(metaStateEvent);
        if (queryRuntime.getMetaComplexEvent() instanceof MetaStateEvent) {
            QueryParserHelper.updateVariablePosition(metaStateEvent, executors);
        } else {
            QueryParserHelper.updateVariablePosition(metaStateEvent.getMetaStreamEvent(0), executors);
        }
        partitionRuntime.init();
    }
    return partitionRuntime;
}
Also used : Query(org.ballerinalang.siddhi.query.api.execution.query.Query) QueryRuntime(org.ballerinalang.siddhi.core.query.QueryRuntime) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) ArrayList(java.util.ArrayList) AbstractDefinition(org.ballerinalang.siddhi.query.api.definition.AbstractDefinition) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PartitionRuntime(org.ballerinalang.siddhi.core.partition.PartitionRuntime) MetaStateEvent(org.ballerinalang.siddhi.core.event.state.MetaStateEvent)

Example 7 with QueryRuntime

use of org.ballerinalang.siddhi.core.query.QueryRuntime in project ballerina by ballerina-lang.

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
 * @return queryRuntime
 */
public static QueryRuntime 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) {
    List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
    QueryRuntime queryRuntime;
    Element nameElement = null;
    LatencyTracker latencyTracker = null;
    LockWrapper lockWrapper = null;
    try {
        nameElement = AnnotationHelper.getAnnotationElement("info", "name", query.getAnnotations());
        String queryName = null;
        if (nameElement != null) {
            queryName = nameElement.getValue();
        } else {
            queryName = "query_" + queryIndex + "_" + UUID.randomUUID().toString();
        }
        latencyTracker = QueryParserHelper.createLatencyTracker(siddhiAppContext, queryName, SiddhiConstants.METRIC_INFIX_QUERIES, null);
        OutputStream.OutputEventType outputEventType = query.getOutputStream().getOutputEventType();
        boolean outputExpectsExpiredEvents = false;
        if (outputEventType != OutputStream.OutputEventType.CURRENT_EVENTS) {
            outputExpectsExpiredEvents = true;
        }
        StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(), siddhiAppContext, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, executors, latencyTracker, outputExpectsExpiredEvents, queryName);
        QuerySelector selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(), siddhiAppContext, streamRuntime.getMetaComplexEvent(), tableMap, executors, queryName, SiddhiConstants.UNKNOWN_STATE);
        boolean isWindow = query.getInputStream() instanceof JoinInputStream;
        if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
            for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
                if (streamHandler instanceof org.ballerinalang.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, siddhiAppContext.getScheduledExecutorService(), siddhiAppContext, queryName);
        if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
            selector.setBatchingEnabled(false);
        }
        siddhiAppContext.addEternalReferencedHolder(outputRateLimiter);
        OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(), streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), tableMap, windowMap, siddhiAppContext, !(streamRuntime instanceof SingleStreamRuntime), queryName);
        QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
        QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
        QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent(), lockWrapper, queryName);
        selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime.getMetaComplexEvent()));
        queryRuntime = new QueryRuntime(query, siddhiAppContext, streamRuntime, selector, outputRateLimiter, outputCallback, streamRuntime.getMetaComplexEvent(), lockWrapper != null, queryName);
        if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
            selector.setBatchingEnabled(false);
            ((WrappedSnapshotOutputRateLimiter) outputRateLimiter).init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(), selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
        }
        outputRateLimiter.init(siddhiAppContext, lockWrapper, queryName);
    } 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 : Element(org.ballerinalang.siddhi.query.api.annotation.Element) OutputStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.OutputStream) ArrayList(java.util.ArrayList) OutputCallback(org.ballerinalang.siddhi.core.query.output.callback.OutputCallback) QueryRuntime(org.ballerinalang.siddhi.core.query.QueryRuntime) JoinInputStream(org.ballerinalang.siddhi.query.api.execution.query.input.stream.JoinInputStream) SingleInputStream(org.ballerinalang.siddhi.query.api.execution.query.input.stream.SingleInputStream) OutputRateLimiter(org.ballerinalang.siddhi.core.query.output.ratelimit.OutputRateLimiter) WrappedSnapshotOutputRateLimiter(org.ballerinalang.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) StreamHandler(org.ballerinalang.siddhi.query.api.execution.query.input.handler.StreamHandler) StreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.StreamRuntime) JoinStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.join.JoinStreamRuntime) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) Window(org.ballerinalang.siddhi.core.window.Window) ReentrantLock(java.util.concurrent.locks.ReentrantLock) DuplicateDefinitionException(org.ballerinalang.siddhi.query.api.exception.DuplicateDefinitionException) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) JoinStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.join.JoinStreamRuntime) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) QuerySelector(org.ballerinalang.siddhi.core.query.selector.QuerySelector) LockWrapper(org.ballerinalang.siddhi.core.util.lock.LockWrapper) MetaStateEvent(org.ballerinalang.siddhi.core.event.state.MetaStateEvent) LatencyTracker(org.ballerinalang.siddhi.core.util.statistics.LatencyTracker) WrappedSnapshotOutputRateLimiter(org.ballerinalang.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)

Example 8 with QueryRuntime

use of org.ballerinalang.siddhi.core.query.QueryRuntime in project ballerina by ballerina-lang.

the class SiddhiAppParser method parse.

/**
 * Parse an SiddhiApp returning SiddhiAppRuntime.
 *
 * @param siddhiApp       plan to be parsed
 * @param siddhiAppString content of Siddhi application as string
 * @param siddhiContext   SiddhiContext  @return SiddhiAppRuntime
 * @return SiddhiAppRuntimeBuilder
 */
public static SiddhiAppRuntimeBuilder parse(SiddhiApp siddhiApp, String siddhiAppString, SiddhiContext siddhiContext) {
    SiddhiAppContext siddhiAppContext = new SiddhiAppContext();
    siddhiAppContext.setSiddhiContext(siddhiContext);
    siddhiAppContext.setSiddhiAppString(siddhiAppString);
    try {
        Element element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_NAME, null, siddhiApp.getAnnotations());
        if (element != null) {
            siddhiAppContext.setName(element.getValue());
        } else {
            siddhiAppContext.setName(UUID.randomUUID().toString());
        }
        Annotation annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_ENFORCE_ORDER, siddhiApp.getAnnotations());
        if (annotation != null) {
            siddhiAppContext.setEnforceOrder(true);
        }
        annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_ASYNC, siddhiApp.getAnnotations());
        if (annotation != null) {
            throw new SiddhiAppCreationException("@Async not supported in SiddhiApp level, " + "instead use @Async with streams", annotation.getQueryContextStartIndex(), annotation.getQueryContextEndIndex());
        }
        annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_STATISTICS, siddhiApp.getAnnotations());
        List<Element> statisticsElements = new ArrayList<>();
        if (annotation != null) {
            statisticsElements = annotation.getElements();
        }
        if (siddhiContext.getStatisticsConfiguration() != null) {
            siddhiAppContext.setStatisticsManager(siddhiContext.getStatisticsConfiguration().getFactory().createStatisticsManager(siddhiContext.getStatisticsConfiguration().getMetricPrefix(), siddhiAppContext.getName(), statisticsElements));
        }
        Element statStateEnableElement = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_STATISTICS, SiddhiConstants.ANNOTATION_ELEMENT_ENABLE, siddhiApp.getAnnotations());
        if (statStateEnableElement != null && Boolean.valueOf(statStateEnableElement.getValue())) {
            siddhiAppContext.setStatsEnabled(true);
        } else {
            Element statStateElement = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_STATISTICS, null, siddhiApp.getAnnotations());
            // where sp uses @app:statistics('true').
            if (annotation != null && (statStateElement == null || Boolean.valueOf(statStateElement.getValue()))) {
                siddhiAppContext.setStatsEnabled(true);
            }
        }
        Element statStateIncludElement = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_STATISTICS, SiddhiConstants.ANNOTATION_ELEMENT_INCLUDE, siddhiApp.getAnnotations());
        siddhiAppContext.setIncludedMetrics(generateIncludedMetrics(statStateIncludElement));
        siddhiAppContext.setThreadBarrier(new ThreadBarrier());
        siddhiAppContext.setExecutorService(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Siddhi-" + siddhiAppContext.getName() + "-executor-thread-%d").build()));
        siddhiAppContext.setScheduledExecutorService(Executors.newScheduledThreadPool(5, new ThreadFactoryBuilder().setNameFormat("Siddhi-" + siddhiAppContext.getName() + "-scheduler-thread-%d").build()));
        // Select the TimestampGenerator based on playback mode on/off
        annotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_PLAYBACK, siddhiApp.getAnnotations());
        if (annotation != null) {
            String idleTime = null;
            String increment = null;
            EventTimeBasedMillisTimestampGenerator timestampGenerator = new EventTimeBasedMillisTimestampGenerator(siddhiAppContext.getScheduledExecutorService());
            // Get the optional elements of playback annotation
            for (Element e : annotation.getElements()) {
                if (SiddhiConstants.ANNOTATION_ELEMENT_IDLE_TIME.equalsIgnoreCase(e.getKey())) {
                    idleTime = e.getValue();
                } else if (SiddhiConstants.ANNOTATION_ELEMENT_INCREMENT.equalsIgnoreCase(e.getKey())) {
                    increment = e.getValue();
                } else {
                    throw new SiddhiAppValidationException("Playback annotation accepts only idle.time and " + "increment but found " + e.getKey());
                }
            }
            // idleTime and increment are optional but if one presents, the other also should be given
            if (idleTime != null && increment == null) {
                throw new SiddhiAppValidationException("Playback annotation requires both idle.time and " + "increment but increment not found");
            } else if (idleTime == null && increment != null) {
                throw new SiddhiAppValidationException("Playback annotation requires both idle.time and " + "increment but idle.time does not found");
            } else if (idleTime != null) {
                // The fourth case idleTime == null && increment == null are ignored because it means no heartbeat.
                try {
                    timestampGenerator.setIdleTime(SiddhiCompiler.parseTimeConstantDefinition(idleTime).value());
                } catch (SiddhiParserException ex) {
                    throw new SiddhiParserException("Invalid idle.time constant '" + idleTime + "' in playback " + "annotation", ex);
                }
                try {
                    timestampGenerator.setIncrementInMilliseconds(SiddhiCompiler.parseTimeConstantDefinition(increment).value());
                } catch (SiddhiParserException ex) {
                    throw new SiddhiParserException("Invalid increment constant '" + increment + "' in playback " + "annotation", ex);
                }
            }
            siddhiAppContext.setTimestampGenerator(timestampGenerator);
            siddhiAppContext.setPlayback(true);
        } else {
            siddhiAppContext.setTimestampGenerator(new SystemCurrentTimeMillisTimestampGenerator());
        }
        siddhiAppContext.setSnapshotService(new SnapshotService(siddhiAppContext));
        siddhiAppContext.setPersistenceService(new PersistenceService(siddhiAppContext));
        siddhiAppContext.setElementIdGenerator(new ElementIdGenerator(siddhiAppContext.getName()));
    } catch (DuplicateAnnotationException e) {
        throw new DuplicateAnnotationException(e.getMessageWithOutContext() + " for the same Siddhi app " + siddhiApp.toString(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
    }
    SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder = new SiddhiAppRuntimeBuilder(siddhiAppContext);
    defineStreamDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getStreamDefinitionMap(), siddhiAppContext);
    defineTableDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getTableDefinitionMap(), siddhiAppContext);
    defineWindowDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getWindowDefinitionMap(), siddhiAppContext);
    defineFunctionDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getFunctionDefinitionMap(), siddhiAppContext);
    defineAggregationDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getAggregationDefinitionMap(), siddhiAppContext);
    for (Window window : siddhiAppRuntimeBuilder.getWindowMap().values()) {
        try {
            window.init(siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getWindowMap(), window.getWindowDefinition().getId());
        } catch (Throwable t) {
            ExceptionUtil.populateQueryContext(t, window.getWindowDefinition(), siddhiAppContext);
            throw t;
        }
    }
    int queryIndex = 1;
    for (ExecutionElement executionElement : siddhiApp.getExecutionElementList()) {
        if (executionElement instanceof Query) {
            try {
                QueryRuntime queryRuntime = QueryParser.parse((Query) executionElement, siddhiAppContext, siddhiAppRuntimeBuilder.getStreamDefinitionMap(), siddhiAppRuntimeBuilder.getTableDefinitionMap(), siddhiAppRuntimeBuilder.getWindowDefinitionMap(), siddhiAppRuntimeBuilder.getAggregationDefinitionMap(), siddhiAppRuntimeBuilder.getTableMap(), siddhiAppRuntimeBuilder.getAggregationMap(), siddhiAppRuntimeBuilder.getWindowMap(), siddhiAppRuntimeBuilder.getLockSynchronizer(), String.valueOf(queryIndex));
                siddhiAppRuntimeBuilder.addQuery(queryRuntime);
                queryIndex++;
            } catch (Throwable t) {
                ExceptionUtil.populateQueryContext(t, (Query) executionElement, siddhiAppContext);
                throw t;
            }
        } else {
            try {
                PartitionRuntime partitionRuntime = PartitionParser.parse(siddhiAppRuntimeBuilder, (Partition) executionElement, siddhiAppContext, siddhiAppRuntimeBuilder.getStreamDefinitionMap(), queryIndex);
                siddhiAppRuntimeBuilder.addPartition(partitionRuntime);
                siddhiAppContext.getSnapshotService().addSnapshotable("partition", partitionRuntime);
                queryIndex += ((Partition) executionElement).getQueryList().size();
            } catch (Throwable t) {
                ExceptionUtil.populateQueryContext(t, (Partition) executionElement, siddhiAppContext);
                throw t;
            }
        }
    }
    // Done last as they have to be started last
    defineTriggerDefinitions(siddhiAppRuntimeBuilder, siddhiApp.getTriggerDefinitionMap(), siddhiAppContext);
    return siddhiAppRuntimeBuilder;
}
Also used : Query(org.ballerinalang.siddhi.query.api.execution.query.Query) ExecutionElement(org.ballerinalang.siddhi.query.api.execution.ExecutionElement) Element(org.ballerinalang.siddhi.query.api.annotation.Element) ArrayList(java.util.ArrayList) ElementIdGenerator(org.ballerinalang.siddhi.core.util.ElementIdGenerator) EventTimeBasedMillisTimestampGenerator(org.ballerinalang.siddhi.core.util.timestamp.EventTimeBasedMillisTimestampGenerator) ThreadBarrier(org.ballerinalang.siddhi.core.util.ThreadBarrier) QueryRuntime(org.ballerinalang.siddhi.core.query.QueryRuntime) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Window(org.ballerinalang.siddhi.core.window.Window) SnapshotService(org.ballerinalang.siddhi.core.util.snapshot.SnapshotService) Partition(org.ballerinalang.siddhi.query.api.execution.partition.Partition) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) SiddhiAppValidationException(org.ballerinalang.siddhi.query.api.exception.SiddhiAppValidationException) Annotation(org.ballerinalang.siddhi.query.api.annotation.Annotation) PersistenceService(org.ballerinalang.siddhi.core.util.persistence.PersistenceService) SiddhiAppRuntimeBuilder(org.ballerinalang.siddhi.core.util.SiddhiAppRuntimeBuilder) DuplicateAnnotationException(org.ballerinalang.siddhi.query.api.exception.DuplicateAnnotationException) SiddhiParserException(org.ballerinalang.siddhi.query.compiler.exception.SiddhiParserException) ExecutionElement(org.ballerinalang.siddhi.query.api.execution.ExecutionElement) SystemCurrentTimeMillisTimestampGenerator(org.ballerinalang.siddhi.core.util.timestamp.SystemCurrentTimeMillisTimestampGenerator) SiddhiAppContext(org.ballerinalang.siddhi.core.config.SiddhiAppContext) PartitionRuntime(org.ballerinalang.siddhi.core.partition.PartitionRuntime)

Example 9 with QueryRuntime

use of org.ballerinalang.siddhi.core.query.QueryRuntime in project ballerina by ballerina-lang.

the class SiddhiAppRuntimeBuilder method addQuery.

public String addQuery(QueryRuntime queryRuntime) {
    QueryRuntime oldQueryRuntime = queryProcessorMap.put(queryRuntime.getQueryId(), queryRuntime);
    if (oldQueryRuntime != null) {
        throw new SiddhiAppCreationException("Multiple queries with name '" + queryRuntime.getQueryId() + "' defined in Siddhi App '" + siddhiAppContext.getName() + "'", queryRuntime.getQuery().getQueryContextStartIndex(), queryRuntime.getQuery().getQueryContextEndIndex());
    }
    StreamRuntime streamRuntime = queryRuntime.getStreamRuntime();
    for (SingleStreamRuntime singleStreamRuntime : streamRuntime.getSingleStreamRuntimes()) {
        ProcessStreamReceiver processStreamReceiver = singleStreamRuntime.getProcessStreamReceiver();
        if (processStreamReceiver.toStream()) {
            StreamJunction streamJuction = streamJunctionMap.get(processStreamReceiver.getStreamId());
            if (streamJuction != null) {
                streamJuction.subscribe(processStreamReceiver);
            } else {
                throw new SiddhiAppCreationException("Expecting a stream, but provided '" + processStreamReceiver.getStreamId() + "' is not a stream");
            }
        }
    }
    OutputCallback outputCallback = queryRuntime.getOutputCallback();
    if (outputCallback != null && outputCallback instanceof InsertIntoStreamCallback) {
        InsertIntoStreamCallback insertIntoStreamCallback = (InsertIntoStreamCallback) outputCallback;
        StreamDefinition streamDefinition = insertIntoStreamCallback.getOutputStreamDefinition();
        streamDefinitionMap.putIfAbsent(streamDefinition.getId(), streamDefinition);
        DefinitionParserHelper.validateOutputStream(streamDefinition, streamDefinitionMap.get(streamDefinition.getId()));
        StreamJunction outputStreamJunction = streamJunctionMap.get(streamDefinition.getId());
        if (outputStreamJunction == null) {
            outputStreamJunction = new StreamJunction(streamDefinition, siddhiAppContext.getExecutorService(), siddhiAppContext.getBufferSize(), siddhiAppContext);
            streamJunctionMap.putIfAbsent(streamDefinition.getId(), outputStreamJunction);
        }
        insertIntoStreamCallback.init(streamJunctionMap.get(insertIntoStreamCallback.getOutputStreamDefinition().getId()));
    } else if (outputCallback != null && outputCallback instanceof InsertIntoWindowCallback) {
        InsertIntoWindowCallback insertIntoWindowCallback = (InsertIntoWindowCallback) outputCallback;
        StreamDefinition streamDefinition = insertIntoWindowCallback.getOutputStreamDefinition();
        windowDefinitionMap.putIfAbsent(streamDefinition.getId(), streamDefinition);
        DefinitionParserHelper.validateOutputStream(streamDefinition, windowDefinitionMap.get(streamDefinition.getId()));
        StreamJunction outputStreamJunction = streamJunctionMap.get(streamDefinition.getId());
        if (outputStreamJunction == null) {
            outputStreamJunction = new StreamJunction(streamDefinition, siddhiAppContext.getExecutorService(), siddhiAppContext.getBufferSize(), siddhiAppContext);
            streamJunctionMap.putIfAbsent(streamDefinition.getId(), outputStreamJunction);
        }
        insertIntoWindowCallback.getWindow().setPublisher(streamJunctionMap.get(insertIntoWindowCallback.getOutputStreamDefinition().getId()).constructPublisher());
    }
    return queryRuntime.getQueryId();
}
Also used : ProcessStreamReceiver(org.ballerinalang.siddhi.core.query.input.ProcessStreamReceiver) StreamDefinition(org.ballerinalang.siddhi.query.api.definition.StreamDefinition) InsertIntoWindowCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoWindowCallback) QueryRuntime(org.ballerinalang.siddhi.core.query.QueryRuntime) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) StreamJunction(org.ballerinalang.siddhi.core.stream.StreamJunction) StreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) InsertIntoStreamCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoStreamCallback) OutputCallback(org.ballerinalang.siddhi.core.query.output.callback.OutputCallback)

Aggregations

QueryRuntime (org.ballerinalang.siddhi.core.query.QueryRuntime)9 ArrayList (java.util.ArrayList)5 StreamRuntime (org.ballerinalang.siddhi.core.query.input.stream.StreamRuntime)4 SingleStreamRuntime (org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime)4 OutputCallback (org.ballerinalang.siddhi.core.query.output.callback.OutputCallback)3 StreamJunction (org.ballerinalang.siddhi.core.stream.StreamJunction)3 Window (org.ballerinalang.siddhi.core.window.Window)3 StreamDefinition (org.ballerinalang.siddhi.query.api.definition.StreamDefinition)3 Query (org.ballerinalang.siddhi.query.api.execution.query.Query)3 SiddhiAppContext (org.ballerinalang.siddhi.core.config.SiddhiAppContext)2 MetaStateEvent (org.ballerinalang.siddhi.core.event.state.MetaStateEvent)2 MetaStreamEvent (org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)2 SiddhiAppCreationException (org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException)2 VariableExpressionExecutor (org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor)2 PartitionRuntime (org.ballerinalang.siddhi.core.partition.PartitionRuntime)2 StoreQueryRuntime (org.ballerinalang.siddhi.core.query.StoreQueryRuntime)2 ElementIdGenerator (org.ballerinalang.siddhi.core.util.ElementIdGenerator)2 SnapshotService (org.ballerinalang.siddhi.core.util.snapshot.SnapshotService)2 Element (org.ballerinalang.siddhi.query.api.annotation.Element)2 AbstractDefinition (org.ballerinalang.siddhi.query.api.definition.AbstractDefinition)2