Search in sources :

Example 96 with Element

use of org.wso2.siddhi.query.api.annotation.Element 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
 * @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.wso2.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.wso2.siddhi.query.api.annotation.Element) OutputStream(org.wso2.siddhi.query.api.execution.query.output.stream.OutputStream) ArrayList(java.util.ArrayList) OutputCallback(org.wso2.siddhi.core.query.output.callback.OutputCallback) QueryRuntime(org.wso2.siddhi.core.query.QueryRuntime) JoinInputStream(org.wso2.siddhi.query.api.execution.query.input.stream.JoinInputStream) SingleInputStream(org.wso2.siddhi.query.api.execution.query.input.stream.SingleInputStream) WrappedSnapshotOutputRateLimiter(org.wso2.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) OutputRateLimiter(org.wso2.siddhi.core.query.output.ratelimit.OutputRateLimiter) StreamHandler(org.wso2.siddhi.query.api.execution.query.input.handler.StreamHandler) SingleStreamRuntime(org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime) StreamRuntime(org.wso2.siddhi.core.query.input.stream.StreamRuntime) JoinStreamRuntime(org.wso2.siddhi.core.query.input.stream.join.JoinStreamRuntime) Window(org.wso2.siddhi.core.window.Window) ReentrantLock(java.util.concurrent.locks.ReentrantLock) DuplicateDefinitionException(org.wso2.siddhi.query.api.exception.DuplicateDefinitionException) SingleStreamRuntime(org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime) JoinStreamRuntime(org.wso2.siddhi.core.query.input.stream.join.JoinStreamRuntime) VariableExpressionExecutor(org.wso2.siddhi.core.executor.VariableExpressionExecutor) QuerySelector(org.wso2.siddhi.core.query.selector.QuerySelector) LockWrapper(org.wso2.siddhi.core.util.lock.LockWrapper) MetaStateEvent(org.wso2.siddhi.core.event.state.MetaStateEvent) LatencyTracker(org.wso2.siddhi.core.util.statistics.LatencyTracker) WrappedSnapshotOutputRateLimiter(org.wso2.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) MetaStreamEvent(org.wso2.siddhi.core.event.stream.MetaStreamEvent)

Example 97 with Element

use of org.wso2.siddhi.query.api.annotation.Element in project siddhi by wso2.

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.wso2.siddhi.query.api.execution.query.Query) Element(org.wso2.siddhi.query.api.annotation.Element) ExecutionElement(org.wso2.siddhi.query.api.execution.ExecutionElement) ArrayList(java.util.ArrayList) ElementIdGenerator(org.wso2.siddhi.core.util.ElementIdGenerator) EventTimeBasedMillisTimestampGenerator(org.wso2.siddhi.core.util.timestamp.EventTimeBasedMillisTimestampGenerator) ThreadBarrier(org.wso2.siddhi.core.util.ThreadBarrier) QueryRuntime(org.wso2.siddhi.core.query.QueryRuntime) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Window(org.wso2.siddhi.core.window.Window) SnapshotService(org.wso2.siddhi.core.util.snapshot.SnapshotService) Partition(org.wso2.siddhi.query.api.execution.partition.Partition) SiddhiAppCreationException(org.wso2.siddhi.core.exception.SiddhiAppCreationException) SiddhiAppValidationException(org.wso2.siddhi.query.api.exception.SiddhiAppValidationException) Annotation(org.wso2.siddhi.query.api.annotation.Annotation) PersistenceService(org.wso2.siddhi.core.util.persistence.PersistenceService) SiddhiAppRuntimeBuilder(org.wso2.siddhi.core.util.SiddhiAppRuntimeBuilder) DuplicateAnnotationException(org.wso2.siddhi.query.api.exception.DuplicateAnnotationException) SiddhiParserException(org.wso2.siddhi.query.compiler.exception.SiddhiParserException) ExecutionElement(org.wso2.siddhi.query.api.execution.ExecutionElement) SystemCurrentTimeMillisTimestampGenerator(org.wso2.siddhi.core.util.timestamp.SystemCurrentTimeMillisTimestampGenerator) SiddhiAppContext(org.wso2.siddhi.core.config.SiddhiAppContext) PartitionRuntime(org.wso2.siddhi.core.partition.PartitionRuntime)

Example 98 with Element

use of org.wso2.siddhi.query.api.annotation.Element in project siddhi by wso2.

the class DefinitionParserHelper method getAttributeMappings.

private static AttributesHolder getAttributeMappings(Annotation mapAnnotation, String mapType, StreamDefinition streamDefinition) {
    List<Annotation> attributeAnnotations = mapAnnotation.getAnnotations(SiddhiConstants.ANNOTATION_ATTRIBUTES);
    DefinitionParserHelper.AttributesHolder attributesHolder = new DefinitionParserHelper.AttributesHolder();
    if (attributeAnnotations.size() > 0) {
        Map<String, String> elementMap = new HashMap<>();
        List<String> elementList = new ArrayList<>();
        Boolean attributesNameDefined = null;
        for (Element element : attributeAnnotations.get(0).getElements()) {
            if (element.getKey() == null) {
                if (attributesNameDefined != null && attributesNameDefined) {
                    throw new SiddhiAppCreationException("Error at '" + mapType + "' defined at stream'" + streamDefinition.getId() + "', some attributes are defined and some are not defined.", element.getQueryContextStartIndex(), element.getQueryContextEndIndex());
                }
                attributesNameDefined = false;
                elementList.add(element.getValue());
            } else {
                if (attributesNameDefined != null && !attributesNameDefined) {
                    throw new SiddhiAppCreationException("Error at '" + mapType + "' defined at stream '" + streamDefinition.getId() + "', some attributes are defined and some are not defined.", element.getQueryContextStartIndex(), element.getQueryContextEndIndex());
                }
                attributesNameDefined = true;
                elementMap.put(element.getKey(), element.getValue());
            }
        }
        if (elementMap.size() > 0) {
            List<Attribute> attributeList = streamDefinition.getAttributeList();
            for (int i = 0, attributeListSize = attributeList.size(); i < attributeListSize; i++) {
                Attribute attribute = attributeList.get(i);
                String value = elementMap.get(attribute.getName());
                if (value == null) {
                    throw new SiddhiAppCreationException("Error at '" + mapType + "' defined at stream '" + streamDefinition.getId() + "', attribute '" + attribute.getName() + "' is not mapped.", mapAnnotation.getQueryContextStartIndex(), mapAnnotation.getQueryContextEndIndex());
                }
                assignMapping(attributesHolder, elementMap, i, attribute);
            }
        } else {
            List<Attribute> attributeList = streamDefinition.getAttributeList();
            if (elementList.size() != attributeList.size()) {
                throw new SiddhiAppCreationException("Error at '" + mapType + "' defined at stream '" + streamDefinition.getId() + "', '" + elementList.size() + "' mapping attributes are " + "provided but expected attributes are '" + attributeList.size() + "'.", mapAnnotation.getQueryContextStartIndex(), mapAnnotation.getQueryContextEndIndex());
            }
            for (int i = 0; i < attributeList.size(); i++) {
                Attribute attribute = attributeList.get(i);
                assignMapping(attributesHolder, elementMap, i, attribute);
            }
        }
    }
    return attributesHolder;
}
Also used : HashMap(java.util.HashMap) Attribute(org.wso2.siddhi.query.api.definition.Attribute) SiddhiAppCreationException(org.wso2.siddhi.core.exception.SiddhiAppCreationException) Element(org.wso2.siddhi.query.api.annotation.Element) ArrayList(java.util.ArrayList) Annotation(org.wso2.siddhi.query.api.annotation.Annotation)

Example 99 with Element

use of org.wso2.siddhi.query.api.annotation.Element in project siddhi by wso2.

the class DefinitionParserHelper method constructOptionHolder.

private static OptionHolder constructOptionHolder(StreamDefinition streamDefinition, Annotation annotation, org.wso2.siddhi.annotation.Extension extension, String[] supportedDynamicOptions) {
    List<String> supportedDynamicOptionList = new ArrayList<>();
    if (supportedDynamicOptions != null) {
        supportedDynamicOptionList = Arrays.asList(supportedDynamicOptions);
    }
    Map<String, String> options = new HashMap<String, String>();
    Map<String, String> dynamicOptions = new HashMap<String, String>();
    for (Element element : annotation.getElements()) {
        if (Pattern.matches("(.*?)\\{\\{.*?\\}\\}(.*?)", element.getValue())) {
            if (supportedDynamicOptionList.contains(element.getKey())) {
                dynamicOptions.put(element.getKey(), element.getValue());
            } else {
                throw new SiddhiAppCreationException("'" + element.getKey() + "' is not a supported " + "DynamicOption " + "for the Extension '" + extension.namespace() + ":" + extension.name() + "', it only supports following as its DynamicOptions: " + supportedDynamicOptionList, annotation.getQueryContextStartIndex(), annotation.getQueryContextEndIndex());
            }
        } else {
            options.put(element.getKey(), element.getValue());
        }
    }
    return new OptionHolder(streamDefinition, options, dynamicOptions, extension);
}
Also used : HashMap(java.util.HashMap) OptionHolder(org.wso2.siddhi.core.util.transport.OptionHolder) SiddhiAppCreationException(org.wso2.siddhi.core.exception.SiddhiAppCreationException) Element(org.wso2.siddhi.query.api.annotation.Element) ArrayList(java.util.ArrayList)

Example 100 with Element

use of org.wso2.siddhi.query.api.annotation.Element in project siddhi by wso2.

the class DefinitionParserHelper method addEventSource.

public static void addEventSource(StreamDefinition streamDefinition, ConcurrentMap<String, List<Source>> eventSourceMap, SiddhiAppContext siddhiAppContext) {
    for (Annotation sourceAnnotation : streamDefinition.getAnnotations()) {
        if (SiddhiConstants.ANNOTATION_SOURCE.equalsIgnoreCase(sourceAnnotation.getName())) {
            sourceAnnotation = updateAnnotationRef(sourceAnnotation, SiddhiConstants.NAMESPACE_SOURCE, siddhiAppContext);
            Annotation mapAnnotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_MAP, sourceAnnotation.getAnnotations());
            if (mapAnnotation == null) {
                mapAnnotation = Annotation.annotation(SiddhiConstants.ANNOTATION_MAP).element(SiddhiConstants.ANNOTATION_ELEMENT_TYPE, "passThrough");
            }
            final String sourceType = sourceAnnotation.getElement(SiddhiConstants.ANNOTATION_ELEMENT_TYPE);
            final String mapType = mapAnnotation.getElement(SiddhiConstants.ANNOTATION_ELEMENT_TYPE);
            if (sourceType != null && mapType != null) {
                SourceHandlerManager sourceHandlerManager = siddhiAppContext.getSiddhiContext().getSourceHandlerManager();
                SourceHandler sourceHandler = null;
                if (sourceHandlerManager != null) {
                    sourceHandler = sourceHandlerManager.generateSourceHandler();
                }
                // load input transport extension
                Extension sourceExtension = constructExtension(streamDefinition, SiddhiConstants.ANNOTATION_SOURCE, sourceType, sourceAnnotation, SiddhiConstants.NAMESPACE_SOURCE);
                Source source = (Source) SiddhiClassLoader.loadExtensionImplementation(sourceExtension, SourceExecutorExtensionHolder.getInstance(siddhiAppContext));
                ConfigReader configReader = siddhiAppContext.getSiddhiContext().getConfigManager().generateConfigReader(sourceExtension.getNamespace(), sourceExtension.getName());
                // load input mapper extension
                Extension mapperExtension = constructExtension(streamDefinition, SiddhiConstants.ANNOTATION_MAP, mapType, sourceAnnotation, SiddhiConstants.NAMESPACE_SOURCE_MAPPER);
                SourceMapper sourceMapper = (SourceMapper) SiddhiClassLoader.loadExtensionImplementation(mapperExtension, SourceMapperExecutorExtensionHolder.getInstance(siddhiAppContext));
                ConfigReader mapperConfigReader = siddhiAppContext.getSiddhiContext().getConfigManager().generateConfigReader(mapperExtension.getNamespace(), mapperExtension.getName());
                validateSourceMapperCompatibility(streamDefinition, sourceType, mapType, source, sourceMapper, sourceAnnotation);
                OptionHolder sourceOptionHolder = constructOptionHolder(streamDefinition, sourceAnnotation, source.getClass().getAnnotation(org.wso2.siddhi.annotation.Extension.class), null);
                OptionHolder mapOptionHolder = constructOptionHolder(streamDefinition, mapAnnotation, sourceMapper.getClass().getAnnotation(org.wso2.siddhi.annotation.Extension.class), null);
                AttributesHolder attributesHolder = getAttributeMappings(mapAnnotation, mapType, streamDefinition);
                String[] transportPropertyNames = getTransportPropertyNames(attributesHolder);
                try {
                    source.init(sourceType, sourceOptionHolder, sourceMapper, transportPropertyNames, configReader, mapType, mapOptionHolder, attributesHolder.payloadMappings, attributesHolder.transportMappings, mapperConfigReader, sourceHandler, streamDefinition, siddhiAppContext);
                } catch (Throwable t) {
                    ExceptionUtil.populateQueryContext(t, sourceAnnotation, siddhiAppContext);
                    throw t;
                }
                siddhiAppContext.getSnapshotService().addSnapshotable(source.getStreamDefinition().getId(), source);
                if (sourceHandlerManager != null) {
                    sourceHandlerManager.registerSourceHandler(sourceHandler.getElementId(), sourceHandler);
                    siddhiAppContext.getSnapshotService().addSnapshotable(streamDefinition.getId(), sourceHandler);
                }
                List<Source> eventSources = eventSourceMap.get(streamDefinition.getId());
                if (eventSources == null) {
                    eventSources = new ArrayList<>();
                    eventSources.add(source);
                    eventSourceMap.put(streamDefinition.getId(), eventSources);
                } else {
                    eventSources.add(source);
                }
            } else {
                throw new SiddhiAppCreationException("Both @Sink(type=) and @map(type=) are required.", sourceAnnotation.getQueryContextStartIndex(), sourceAnnotation.getQueryContextEndIndex());
            }
        }
    }
}
Also used : SourceHandler(org.wso2.siddhi.core.stream.input.source.SourceHandler) SourceHandlerManager(org.wso2.siddhi.core.stream.input.source.SourceHandlerManager) SiddhiAppCreationException(org.wso2.siddhi.core.exception.SiddhiAppCreationException) ConfigReader(org.wso2.siddhi.core.util.config.ConfigReader) Annotation(org.wso2.siddhi.query.api.annotation.Annotation) Source(org.wso2.siddhi.core.stream.input.source.Source) Extension(org.wso2.siddhi.query.api.extension.Extension) OptionHolder(org.wso2.siddhi.core.util.transport.OptionHolder) SourceMapper(org.wso2.siddhi.core.stream.input.source.SourceMapper)

Aggregations

Test (org.testng.annotations.Test)87 StreamDefinition (org.wso2.siddhi.query.api.definition.StreamDefinition)82 Query (org.wso2.siddhi.query.api.execution.query.Query)81 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)79 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)79 SiddhiApp (org.wso2.siddhi.query.api.SiddhiApp)79 Event (org.wso2.siddhi.core.event.Event)77 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)76 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)73 Element (org.w3c.dom.Element)34 OMElement (org.apache.axiom.om.OMElement)25 QName (javax.xml.namespace.QName)15 SVGCoordinates (org.wso2.carbon.bpel.ui.bpel2svg.SVGCoordinates)14 ActivityInterface (org.wso2.carbon.bpel.ui.bpel2svg.ActivityInterface)13 NodeList (org.w3c.dom.NodeList)12 Element (org.wso2.siddhi.query.api.annotation.Element)12 Node (org.w3c.dom.Node)11 ArrayList (java.util.ArrayList)9 SiddhiAppCreationException (org.wso2.siddhi.core.exception.SiddhiAppCreationException)8 HashMap (java.util.HashMap)7