use of org.wso2.siddhi.core.config.SiddhiAppContext in project siddhi by wso2.
the class SelectorParser method parse.
/**
* Parse Selector portion of a query and return corresponding QuerySelector.
*
* @param selector selector to be parsed
* @param outputStream output stream
* @param siddhiAppContext query to be parsed
* @param metaComplexEvent Meta event used to collect execution info of stream associated with query
* @param tableMap Table Map
* @param variableExpressionExecutors variable expression executors
* @param queryName query name of selector belongs to.
* @param metaPosition helps to identify the meta position of aggregates
* @return QuerySelector
*/
public static QuerySelector parse(Selector selector, OutputStream outputStream, SiddhiAppContext siddhiAppContext, MetaComplexEvent metaComplexEvent, Map<String, Table> tableMap, List<VariableExpressionExecutor> variableExpressionExecutors, String queryName, int metaPosition) {
boolean currentOn = false;
boolean expiredOn = false;
String id = null;
if (outputStream.getOutputEventType() == OutputStream.OutputEventType.CURRENT_EVENTS || outputStream.getOutputEventType() == OutputStream.OutputEventType.ALL_EVENTS) {
currentOn = true;
}
if (outputStream.getOutputEventType() == OutputStream.OutputEventType.EXPIRED_EVENTS || outputStream.getOutputEventType() == OutputStream.OutputEventType.ALL_EVENTS) {
expiredOn = true;
}
id = outputStream.getId();
containsAggregatorThreadLocal.remove();
QuerySelector querySelector = new QuerySelector(id, selector, currentOn, expiredOn, siddhiAppContext);
List<AttributeProcessor> attributeProcessors = getAttributeProcessors(selector, id, siddhiAppContext, metaComplexEvent, tableMap, variableExpressionExecutors, outputStream, queryName, metaPosition);
querySelector.setAttributeProcessorList(attributeProcessors, "true".equals(containsAggregatorThreadLocal.get()));
containsAggregatorThreadLocal.remove();
ConditionExpressionExecutor havingCondition = generateHavingExecutor(selector.getHavingExpression(), metaComplexEvent, siddhiAppContext, tableMap, variableExpressionExecutors, queryName);
querySelector.setHavingConditionExecutor(havingCondition, "true".equals(containsAggregatorThreadLocal.get()));
containsAggregatorThreadLocal.remove();
if (!selector.getGroupByList().isEmpty()) {
querySelector.setGroupByKeyGenerator(new GroupByKeyGenerator(selector.getGroupByList(), metaComplexEvent, SiddhiConstants.UNKNOWN_STATE, null, variableExpressionExecutors, siddhiAppContext, queryName));
}
if (!selector.getOrderByList().isEmpty()) {
querySelector.setOrderByEventComparator(new OrderByEventComparator(selector.getOrderByList(), metaComplexEvent, SiddhiConstants.HAVING_STATE, null, variableExpressionExecutors, siddhiAppContext, queryName));
}
if (selector.getLimit() != null) {
ExpressionExecutor expressionExecutor = ExpressionParser.parseExpression((Expression) selector.getLimit(), metaComplexEvent, SiddhiConstants.HAVING_STATE, tableMap, variableExpressionExecutors, siddhiAppContext, false, 0, queryName);
containsAggregatorThreadLocal.remove();
querySelector.setLimit(((Number) (((ConstantExpressionExecutor) expressionExecutor).getValue())).longValue());
}
return querySelector;
}
use of org.wso2.siddhi.core.config.SiddhiAppContext 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;
}
use of org.wso2.siddhi.core.config.SiddhiAppContext in project siddhi by wso2.
the class StateInputStreamParser method parseInputStream.
public static StateStreamRuntime parseInputStream(StateInputStream stateInputStream, SiddhiAppContext siddhiAppContext, MetaStateEvent metaStateEvent, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, List<VariableExpressionExecutor> variableExpressionExecutors, LatencyTracker latencyTracker, String queryName) {
Map<String, ProcessStreamReceiver> processStreamReceiverMap = new HashMap<String, ProcessStreamReceiver>();
StateStreamRuntime stateStreamRuntime = new StateStreamRuntime(siddhiAppContext, metaStateEvent);
String defaultLockKey = "";
for (String streamId : stateInputStream.getAllStreamIds()) {
int streamCount = stateInputStream.getStreamCount(streamId);
if (streamCount == 1) {
if (stateInputStream.getStateType() == StateInputStream.Type.SEQUENCE) {
processStreamReceiverMap.put(streamId, new SequenceSingleProcessStreamReceiver(streamId, stateStreamRuntime, defaultLockKey, latencyTracker, queryName, siddhiAppContext));
} else {
processStreamReceiverMap.put(streamId, new PatternSingleProcessStreamReceiver(streamId, defaultLockKey, latencyTracker, queryName, siddhiAppContext));
}
} else {
if (stateInputStream.getStateType() == StateInputStream.Type.SEQUENCE) {
processStreamReceiverMap.put(streamId, new SequenceMultiProcessStreamReceiver(streamId, streamCount, stateStreamRuntime, latencyTracker, queryName, siddhiAppContext));
} else {
processStreamReceiverMap.put(streamId, new PatternMultiProcessStreamReceiver(streamId, streamCount, latencyTracker, queryName, siddhiAppContext));
}
}
}
StateElement stateElement = stateInputStream.getStateElement();
InnerStateRuntime innerStateRuntime = parse(stateElement, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, metaStateEvent, siddhiAppContext, variableExpressionExecutors, processStreamReceiverMap, null, null, stateInputStream.getStateType(), new ArrayList<Map.Entry<Long, Set<Integer>>>(), latencyTracker, queryName);
stateStreamRuntime.setInnerStateRuntime(innerStateRuntime);
((StreamPreStateProcessor) innerStateRuntime.getFirstProcessor()).setThisLastProcessor((StreamPostStateProcessor) innerStateRuntime.getLastProcessor());
return stateStreamRuntime;
}
use of org.wso2.siddhi.core.config.SiddhiAppContext in project siddhi by wso2.
the class StoreQueryParser method constructStoreQueryRuntime.
private static StoreQueryRuntime constructStoreQueryRuntime(Table table, StoreQuery storeQuery, SiddhiAppContext siddhiAppContext, Map<String, Table> tableMap, String queryName, int metaPosition, Expression onCondition, MetaStreamEvent metaStreamEvent, List<VariableExpressionExecutor> variableExpressionExecutors) {
metaStreamEvent.setEventType(EventType.TABLE);
initMetaStreamEvent(metaStreamEvent, table.getTableDefinition());
MatchingMetaInfoHolder metaStreamInfoHolder = generateMatchingMetaInfoHolder(metaStreamEvent, table.getTableDefinition());
CompiledCondition compiledCondition = table.compileCondition(onCondition, metaStreamInfoHolder, siddhiAppContext, variableExpressionExecutors, tableMap, queryName);
if (table instanceof QueryableProcessor) {
List<Attribute> expectedOutputAttributes = buildExpectedOutputAttributes(storeQuery, siddhiAppContext, tableMap, queryName, metaPosition, metaStreamInfoHolder);
CompiledSelection compiledSelection = ((QueryableProcessor) table).compileSelection(storeQuery.getSelector(), expectedOutputAttributes, metaStreamInfoHolder, siddhiAppContext, variableExpressionExecutors, tableMap, queryName);
SelectStoreQueryRuntime storeQueryRuntime = new SelectStoreQueryRuntime((QueryableProcessor) table, compiledCondition, compiledSelection, expectedOutputAttributes, queryName);
QueryParserHelper.reduceMetaComplexEvent(metaStreamInfoHolder.getMetaStateEvent());
QueryParserHelper.updateVariablePosition(metaStreamInfoHolder.getMetaStateEvent(), variableExpressionExecutors);
return storeQueryRuntime;
} else {
FindStoreQueryRuntime storeQueryRuntime = new FindStoreQueryRuntime(table, compiledCondition, queryName, metaStreamEvent);
populateFindStoreQueryRuntime(storeQueryRuntime, metaStreamInfoHolder, storeQuery.getSelector(), variableExpressionExecutors, siddhiAppContext, tableMap, queryName, metaPosition);
return storeQueryRuntime;
}
}
use of org.wso2.siddhi.core.config.SiddhiAppContext 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());
}
}
}
}
Aggregations