io.siddhi.query.api.definition.Attribute Java Examples

The following examples show how to use io.siddhi.query.api.definition.Attribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JoinInputStreamParser.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private static void populateJoinProcessors(MetaStreamEvent metaStreamEvent, String inputStreamId,
                                           JoinProcessor preJoinProcessor, JoinProcessor postJoinProcessor,
                                           CompiledCondition compiledCondition,
                                           CompiledSelection compiledSelection,
                                           List<Attribute> expectedOutputAttributes) {
    if (metaStreamEvent.getEventType() == TABLE && metaStreamEvent.getEventType() == AGGREGATE) {
        throw new SiddhiAppCreationException(inputStreamId + " of join query cannot trigger join " +
                "because its a " + metaStreamEvent.getEventType() + ", only WINDOW and STEAM can " +
                "trigger join");
    }
    preJoinProcessor.setTrigger(false);    // Pre JoinProcessor does not process the events
    preJoinProcessor.setCompiledCondition(compiledCondition);
    preJoinProcessor.setCompiledSelection(compiledSelection);
    preJoinProcessor.setExpectedOutputAttributes(expectedOutputAttributes);
    postJoinProcessor.setTrigger(true);
    postJoinProcessor.setCompiledCondition(compiledCondition);
    postJoinProcessor.setCompiledSelection(compiledSelection);
    postJoinProcessor.setExpectedOutputAttributes(expectedOutputAttributes);
}
 
Example #2
Source File: IfThenElseFunctionExecutor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors,
                            ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) {
    if (attributeExpressionExecutors.length != 3) {
        // check whether all the arguments passed
        throw new SiddhiAppValidationException("Invalid no of arguments passed to ifThenElse() function, " +
                "required only 3, but found " + attributeExpressionExecutors.length);
    } else if (!attributeExpressionExecutors[0].getReturnType().equals(Attribute.Type.BOOL)) {
        // check whether first argument Boolean or not
        throw new SiddhiAppValidationException("Input type of if in ifThenElse function should be of " +
                "type BOOL, but found " + attributeExpressionExecutors[0].getReturnType());
    } else if (!attributeExpressionExecutors[1].getReturnType().equals(
            attributeExpressionExecutors[2].getReturnType())) {
        // check whether second and thirds argument's return type are equivalent.
        throw new SiddhiAppValidationException("Input type of then in ifThenElse function and else in " +
                "ifThenElse function should be of equivalent type. but found then type: " +
                attributeExpressionExecutors[1].getReturnType() + " and else type: " +
                attributeExpressionExecutors[2].getReturnType());
    } else {
        returnType = attributeExpressionExecutors[1].getReturnType();
    }
    return null;
}
 
Example #3
Source File: ContainsIgnoreCaseExtension.java    From eagle with Apache License 2.0 6 votes vote down vote up
/**
 * The initialization method for ContainsIgnoreCaseExtension,
 * this method will be called before the other methods.
 *
 * @param attributeExpressionExecutors the executors of each function parameter
 * @param configReader                 the config reader for the Siddhi app
 * @param siddhiQueryContext           the context of the Siddhi query
 */
@Override
protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader,
                            SiddhiQueryContext siddhiQueryContext) {
    if (attributeExpressionExecutors.length != 2) {
        throw new SiddhiAppValidationException("Invalid no of arguments passed to str:containsIgnoreCase() "
                + "function, required 2, but found " + attributeExpressionExecutors.length);
    }
    if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) {
        throw new SiddhiAppValidationException("Invalid parameter type found for the first argument of "
                + "str:containsIgnoreCase() function, required " + Attribute.Type.STRING + ", but found "
                + attributeExpressionExecutors[0].getReturnType().toString());
    }
    if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) {
        throw new SiddhiAppValidationException("Invalid parameter type found for the second argument of "
                + "str:containsIgnoreCase() function, required " + Attribute.Type.STRING + ", but found "
                + attributeExpressionExecutors[1].getReturnType().toString());
    }
    return null;
}
 
Example #4
Source File: ExpressionParser.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate the return type of arithmetic operation executors.(Ex: add, subtract, etc)
 *
 * @param leftExpressionExecutor  left ExpressionExecutor
 * @param rightExpressionExecutor right ExpressionExecutor
 * @return Attribute Type
 */
private static Attribute.Type parseArithmeticOperationResultType(ExpressionExecutor leftExpressionExecutor,
                                                                 ExpressionExecutor rightExpressionExecutor) {
    if (leftExpressionExecutor.getReturnType() == Attribute.Type.DOUBLE
            || rightExpressionExecutor.getReturnType() == Attribute.Type.DOUBLE) {
        return Attribute.Type.DOUBLE;
    } else if (leftExpressionExecutor.getReturnType() == Attribute.Type.FLOAT
            || rightExpressionExecutor.getReturnType() == Attribute.Type.FLOAT) {
        return Attribute.Type.FLOAT;
    } else if (leftExpressionExecutor.getReturnType() == Attribute.Type.LONG
            || rightExpressionExecutor.getReturnType() == Attribute.Type.LONG) {
        return Attribute.Type.LONG;
    } else if (leftExpressionExecutor.getReturnType() == Attribute.Type.INT
            || rightExpressionExecutor.getReturnType() == Attribute.Type.INT) {
        return Attribute.Type.INT;
    } else {
        throw new ArithmeticException("Arithmetic operation between " + leftExpressionExecutor.getReturnType()
                + " and " + rightExpressionExecutor.getReturnType() + " cannot be executed");
    }
}
 
Example #5
Source File: FilterTestCase1.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = SiddhiAppCreationException.class)
public void testFilterQuery48() throws InterruptedException {
    log.info("Filter test48");

    SiddhiManager siddhiManager = new SiddhiManager();

    StreamDefinition cseEventStream = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.FLOAT).attribute("available", Attribute.Type.BOOL);
    Query query = new Query();
    query.from(InputStream.stream("cseEventStream").
            filter(Expression.not(Expression.variable("price"))));
    query.annotation(Annotation.annotation("info").element("name", "query1"));
    query.select(
            Selector.selector().
                    select("symbol", Expression.variable("symbol")).
                    select("price", Expression.variable("price")).
                    select("available", Expression.variable("available"))
    );
    query.insertInto("StockQuote");

    SiddhiApp siddhiApp = new SiddhiApp("ep1");
    siddhiApp.defineStream(cseEventStream);
    siddhiApp.addQuery(query);
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);

}
 
Example #6
Source File: CreateSetFunctionExecutor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private boolean isAttributeTypeSupported(Attribute.Type type) {
    switch (type) {
        case FLOAT:
            return true;
        case INT:
            return true;
        case LONG:
            return true;
        case DOUBLE:
            return true;
        case STRING:
            return true;
        case BOOL:
            return true;
        default:
            return false;
    }
}
 
Example #7
Source File: NotConditionExpressionExecutor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
public NotConditionExpressionExecutor(ExpressionExecutor conditionExecutor) {
    if (conditionExecutor.getReturnType().equals(Attribute.Type.BOOL)) {
        this.conditionExecutor = conditionExecutor;
    } else {
        throw new OperationNotSupportedException("Return type of condition executor " + conditionExecutor
                .toString() + " should be of type BOOL. Actual Type: " + conditionExecutor.getReturnType()
                .toString());
    }
}
 
Example #8
Source File: StreamEventConverterFactory.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private static List<StreamEventConverter.ConversionMapping> getConversionElements(
        MetaStreamEvent metaStreamEvent, int size) {

    AbstractDefinition inputDefinition = metaStreamEvent.getInputDefinitions().get(0);
    List<StreamEventConverter.ConversionMapping> conversionMappings = new ArrayList<StreamEventConverter
            .ConversionMapping>(size);

    for (int j = 0; j < 3; j++) {
        List<Attribute> currentDataList = null;
        if (j == 0) {
            currentDataList = metaStreamEvent.getBeforeWindowData();
        } else if (j == 1) {
            currentDataList = metaStreamEvent.getOnAfterWindowData();
        } else if (j == 2) {
            currentDataList = metaStreamEvent.getOutputData();
        }
        if (currentDataList != null) {
            int i = 0;
            for (Attribute attribute : currentDataList) {           //Only variable slots will be filled.
                if (attribute == null) {
                    i++;
                } else if (!inputDefinition.getAttributeList().contains(attribute)) {
                    i++;
                } else {
                    int fromPosition = inputDefinition.getAttributePosition(attribute.getName());
                    StreamEventConverter.ConversionMapping conversionMapping = new StreamEventConverter
                            .ConversionMapping();
                    conversionMapping.setFromPosition(fromPosition);
                    int[] toPosition = new int[2];
                    toPosition[0] = j;
                    toPosition[1] = i;
                    conversionMapping.setToPosition(toPosition);
                    conversionMappings.add(conversionMapping);
                    i++;
                }
            }
        }
    }
    return conversionMappings;
}
 
Example #9
Source File: SiddhiStreamSchema.java    From flink-siddhi with Apache License 2.0 5 votes vote down vote up
public String getStreamDefinitionExpression(StreamDefinition streamDefinition) {
    List<String> columns = new ArrayList<>();
    Preconditions.checkNotNull(streamDefinition, "StreamDefinition is null");
    for (Attribute attribute : streamDefinition.getAttributeList()) {
        columns.add(String.format("%s %s", attribute.getName(), attribute.getType().toString().toLowerCase()));
    }
    return String.format(DEFINE_STREAM_TEMPLATE, streamDefinition.getId(), StringUtils.join(columns, ","));
}
 
Example #10
Source File: SiddhiDefinitionAdapter.java    From eagle with Apache License 2.0 5 votes vote down vote up
public static StreamDefinition convertFromSiddiDefinition(AbstractDefinition siddhiDefinition) {
    StreamDefinition streamDefinition = new StreamDefinition();
    streamDefinition.setStreamId(siddhiDefinition.getId());
    List<StreamColumn> columns = new ArrayList<>(siddhiDefinition.getAttributeNameArray().length);
    for (Attribute attribute : siddhiDefinition.getAttributeList()) {
        StreamColumn column = new StreamColumn();
        column.setType(convertFromSiddhiAttributeType(attribute.getType()));
        column.setName(attribute.getName());
        columns.add(column);
    }
    streamDefinition.setColumns(columns);
    streamDefinition.setTimeseries(true);
    streamDefinition.setDescription("Auto-generated stream schema from siddhi for " + siddhiDefinition.getId());
    return streamDefinition;
}
 
Example #11
Source File: FilterTestCase1.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterQuery72() throws InterruptedException {
    log.info("Filter test72");

    SiddhiManager siddhiManager = new SiddhiManager();
    StreamDefinition cseEventStream = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.DOUBLE)
            .attribute("quantity", Attribute.Type.INT);

    Query query = new Query();
    query.from(InputStream.stream("cseEventStream").filter(Expression.compare(Expression.variable("price"),
            Compare.Operator.LESS_THAN_EQUAL,
            Expression.value(200L))));
    query.annotation(Annotation.annotation("info").element("name", "query1"));
    query.select(Selector.selector().select("symbol", Expression.variable("symbol")).select("price", Expression
            .variable("price")).select("quantity", Expression.variable("quantity")));
    query.insertInto("outputStream");

    SiddhiApp siddhiApp = new SiddhiApp("ep1");
    siddhiApp.defineStream(cseEventStream);
    siddhiApp.addQuery(query);
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);

    siddhiAppRuntime.addCallback("query1", new QueryCallback() {
        @Override
        public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
            EventPrinter.print(timeStamp, inEvents, removeEvents);
            count.addAndGet(inEvents.length);
        }
    });

    InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream");
    siddhiAppRuntime.start();
    inputHandler.send(new Object[]{"WSO2", 500f, 60d, 5});
    inputHandler.send(new Object[]{"WSO2", 70f, 60d, 2});
    inputHandler.send(new Object[]{"WSO2", 60f, 300d, 4});
    SiddhiTestHelper.waitForEvents(10, 2, count, 100);
    siddhiAppRuntime.shutdown();

}
 
Example #12
Source File: FaultFunctionExtension.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
public StateFactory init(ExpressionExecutor[] attributeExpressionExecutors,
                         ConfigReader configReader,
                         SiddhiQueryContext siddhiQueryContext) {
    returnType = Attribute.Type.DOUBLE;
    return null;
}
 
Example #13
Source File: FilterTestCase1.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterQuery70() throws InterruptedException {
    log.info("Filter test70");

    SiddhiManager siddhiManager = new SiddhiManager();
    StreamDefinition cseEventStream = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.DOUBLE)
            .attribute("quantity", Attribute.Type.INT);

    Query query = new Query();
    query.from(InputStream.stream("cseEventStream").filter(Expression.compare(Expression.variable("volume"),
            Compare.Operator.LESS_THAN_EQUAL,
            Expression.value(200L))));
    query.annotation(Annotation.annotation("info").element("name", "query1"));
    query.select(Selector.selector().select("symbol", Expression.variable("symbol")).select("price", Expression
            .variable("price")).select("quantity", Expression.variable("quantity")));
    query.insertInto("outputStream");

    SiddhiApp siddhiApp = new SiddhiApp("ep1");
    siddhiApp.defineStream(cseEventStream);
    siddhiApp.addQuery(query);
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);

    siddhiAppRuntime.addCallback("query1", new QueryCallback() {
        @Override
        public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
            EventPrinter.print(timeStamp, inEvents, removeEvents);
            count.addAndGet(inEvents.length);
        }
    });

    InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream");
    siddhiAppRuntime.start();
    inputHandler.send(new Object[]{"WSO2", 50f, 60d, 5});
    inputHandler.send(new Object[]{"WSO2", 70f, 60d, 2});
    inputHandler.send(new Object[]{"WSO2", 60f, 300d, 4});
    SiddhiTestHelper.waitForEvents(10, 2, count, 100);
    siddhiAppRuntime.shutdown();

}
 
Example #14
Source File: SimpleQueryTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testFunctionDefinition() throws SiddhiParserException {
    FunctionDefinition functionDefinition = SiddhiCompiler.
            parseFunctionDefinition("define function concatFn[javascript] return string " +
                    "{var str1 = data[0];};");

    AssertJUnit.assertEquals(functionDefinition.getId(), "concatFn");
    AssertJUnit.assertEquals(functionDefinition.getBody(), "var str1 = data[0]");
    AssertJUnit.assertEquals(functionDefinition.getLanguage(), "javascript");
    AssertJUnit.assertEquals(functionDefinition.getReturnType(), Attribute.Type.STRING);
}
 
Example #15
Source File: ExpressionBatchWindowProcessor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
protected StateFactory init(MetaStreamEvent metaStreamEvent,
                            AbstractDefinition inputDefinition,
                            ExpressionExecutor[] attributeExpressionExecutors,
                            ConfigReader configReader, StreamEventClonerHolder streamEventClonerHolder,
                            boolean outputExpectsExpiredEvents, boolean findToBeExecuted,
                            SiddhiQueryContext siddhiQueryContext) {
    if (attributeExpressionExecutors[0] instanceof ConstantExpressionExecutor) {
        expressionString = (String) ((ConstantExpressionExecutor)
                attributeExpressionExecutors[0]).getValue();
        constructExpression(metaStreamEvent, siddhiQueryContext);
    } else {
        for (Attribute attribute : inputDefinition.getAttributeList()) {
            metaStreamEvent.addData(attribute);
        }
        expressionStringExecutor = attributeExpressionExecutors[0];
    }
    if (attributeExpressionExecutors.length > 1) {
        if (attributeExpressionExecutors[1] instanceof ConstantExpressionExecutor) {
            includeTriggeringEvent = (Boolean) ((ConstantExpressionExecutor)
                    attributeExpressionExecutors[1]).getValue();
        } else {
            includeTriggeringEventExecutor = attributeExpressionExecutors[1];
        }
        if (attributeExpressionExecutors.length > 2 &&
                attributeExpressionExecutors[2] instanceof ConstantExpressionExecutor) {
            streamInputEvents = (Boolean) ((ConstantExpressionExecutor)
                    attributeExpressionExecutors[2]).getValue();
        }
    }
    return () -> new WindowState();
}
 
Example #16
Source File: CustomPlusFunctionExtension.java    From flink-siddhi with Apache License 2.0 5 votes vote down vote up
/**
 * The main execution method which will be called upon event arrival
 * when there are zero or one function parameter
 *
 * @param data null if the function parameter count is zero or
 *             runtime data value of the function parameter
 * @return the function result
 */
@Override
protected Object execute(Object data) {
    if (returnType == Attribute.Type.DOUBLE) {
        return Double.parseDouble(String.valueOf(data));
    } else {
        return Long.parseLong(String.valueOf(data));
    }
}
 
Example #17
Source File: DefineTableTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void test4() throws SiddhiParserException {
    TableDefinition streamDefinition = SiddhiCompiler.parseTableDefinition("" +
            " @from(datasource='MyDatabase','CUSTOM')" +
            " define table cseStream ( symbol string, price int, volume float )");
    AssertJUnit.assertEquals(TableDefinition.
                    id("cseStream").
                    attribute("symbol", Attribute.Type.STRING).
                    attribute("price", Attribute.Type.INT).
                    attribute("volume", Attribute.Type.FLOAT).annotation(Annotation.annotation("from").element
                    ("datasource", "MyDatabase").element("CUSTOM")).toString(),
            streamDefinition.toString());
}
 
Example #18
Source File: MetaStreamEvent.java    From siddhi with Apache License 2.0 5 votes vote down vote up
public List<Attribute> getOnAfterWindowData() {
    if (onAfterWindowData != null) {
        return onAfterWindowData;
    } else {
        return new ArrayList<Attribute>();  //return empty arraylist to avoid NPE
    }
}
 
Example #19
Source File: MaximumFunctionExecutor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader,
                            SiddhiQueryContext siddhiQueryContext) {
    Attribute.Type attributeTypeOne = attributeExpressionExecutors[0].getReturnType();
    if (!((attributeTypeOne == Attribute.Type.DOUBLE) || (attributeTypeOne == Attribute.Type.INT) ||
            (attributeTypeOne == Attribute.Type.FLOAT) || (attributeTypeOne == Attribute.Type.LONG))) {
        throw new SiddhiAppValidationException("Invalid parameter type found for the argument" + 1 +
                " of maximum() function, " +
                "required " + Attribute.Type.INT + " or " + Attribute.Type.LONG +
                " or " + Attribute.Type.FLOAT + " or " + Attribute.Type.DOUBLE +
                ", but found " + attributeTypeOne.toString());
    }
    for (int i = 1; i < attributeExpressionExecutors.length; i++) {
        Attribute.Type attributeType = attributeExpressionExecutors[i].getReturnType();
        if (!((attributeType == Attribute.Type.DOUBLE) || (attributeType == Attribute.Type.INT) ||
                (attributeType == Attribute.Type.FLOAT) || (attributeType == Attribute.Type.LONG))) {
            throw new SiddhiAppValidationException("Invalid parameter type found for the argument" + i +
                    " of maximum() function, " +
                    "required " + Attribute.Type.INT + " or " + Attribute.Type.LONG +
                    " or " + Attribute.Type.FLOAT + " or " + Attribute.Type.DOUBLE +
                    ", but found " + attributeType.toString());
        }
        if (attributeTypeOne != attributeType) {
            throw new SiddhiAppValidationException("Invalid parameter type found for arguments  " +
                    "of maximum() function, all parameters should be of same type, but found " +
                    attributeTypeOne + " and " + attributeExpressionExecutors[i].getReturnType());
        }

    }
    returnType = attributeTypeOne;
    return null;
}
 
Example #20
Source File: FilterTestCase2.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterQuery90() throws InterruptedException {
    log.info("Filter test90");

    SiddhiManager siddhiManager = new SiddhiManager();
    StreamDefinition cseEventStream = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.DOUBLE)
            .attribute("quantity", Attribute.Type.INT);

    Query query = new Query();
    query.from(InputStream.stream("cseEventStream").filter(Expression.compare(Expression.variable("quantity"),
            Compare.Operator.LESS_THAN, Expression.value(10f))));
    query.annotation(Annotation.annotation("info").element("name", "query1"));
    query.select(Selector.selector().select("symbol", Expression.variable("symbol")).select("price", Expression
            .variable("price")).select("quantity", Expression.variable("quantity")));
    query.insertInto("outputStream");

    SiddhiApp siddhiApp = new SiddhiApp("ep1");
    siddhiApp.defineStream(cseEventStream);
    siddhiApp.addQuery(query);
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);

    siddhiAppRuntime.addCallback("query1", new QueryCallback() {
        @Override
        public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
            EventPrinter.print(timeStamp, inEvents, removeEvents);
            count.addAndGet(inEvents.length);
        }
    });

    InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream");
    siddhiAppRuntime.start();
    inputHandler.send(new Object[]{"WSO2", 50f, 60d, 6});
    inputHandler.send(new Object[]{"WSO2", 70f, 40d, 10});
    inputHandler.send(new Object[]{"WSO2", 44f, 200d, 56});
    SiddhiTestHelper.waitForEvents(10, 1, count, 100);
    AssertJUnit.assertEquals(1, count.get());
    siddhiAppRuntime.shutdown();
}
 
Example #21
Source File: IncrementalAggregateCompileCondition.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private StreamEvent query(Table tableForPerDuration, StateEvent matchingEvent, CompiledCondition compiledCondition,
                          CompiledSelection compiledSelection, Attribute[] outputAttributes) {
    if (tableForPerDuration.getIsConnected()) {
        try {
            return ((QueryableProcessor) tableForPerDuration)
                    .query(matchingEvent, compiledCondition, compiledSelection, outputAttributes);
        } catch (ConnectionUnavailableException e) {
            // On-demand query does not have retry logic and retry called manually
            if (LOG.isDebugEnabled()) {
                LOG.debug("Unable to query table '" + tableForPerDuration.getTableDefinition().getId() + "', "
                        + "as the datasource is unavailable.");
            }
            if (!isOnDemandQuery) {
                tableForPerDuration.setIsConnectedToFalse();
                tableForPerDuration.connectWithRetry();
                return query(tableForPerDuration, matchingEvent, compiledCondition, compiledSelection,
                        outputAttributes);
            }
            throw new SiddhiAppRuntimeException(e.getMessage(), e);
        }
    } else if (tableForPerDuration.getIsTryingToConnect()) {
        LOG.warn("Error on '" + aggregationName + "' while performing query for event '" + matchingEvent +
                "', operation busy waiting at Table '" + tableForPerDuration.getTableDefinition().getId() +
                "' as its trying to reconnect!");
        tableForPerDuration.waitWhileConnect();
        LOG.info("Aggregation '" + aggregationName + "' table '" +
                tableForPerDuration.getTableDefinition().getId() + "' has become available for query for " +
                "matching event '" + matchingEvent + "'");
        return query(tableForPerDuration, matchingEvent, compiledCondition, compiledSelection,
                outputAttributes);
    } else {
        tableForPerDuration.connectWithRetry();
        return query(tableForPerDuration, matchingEvent, compiledCondition, compiledSelection,
                outputAttributes);

    }
}
 
Example #22
Source File: GroupingWindowProcessor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
protected StateFactory<S> init(MetaStreamEvent metaStreamEvent, AbstractDefinition inputDefinition,
                               ExpressionExecutor[] attributeExpressionExecutors,
                               ConfigReader configReader, StreamEventClonerHolder streamEventClonerHolder,
                               boolean outputExpectsExpiredEvents, boolean findToBeExecuted,
                               SiddhiQueryContext siddhiQueryContext) {
    StateFactory<S> stateFactory = init(attributeExpressionExecutors, configReader, outputExpectsExpiredEvents,
            siddhiQueryContext);
    Attribute groupingKey = new Attribute("_groupingKey", Attribute.Type.STRING);
    internalAttributes = new ArrayList<Attribute>(1);
    internalAttributes.add(groupingKey);
    metaStreamEvent.addData(groupingKey);
    return stateFactory;
}
 
Example #23
Source File: FilterTestCase2.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterQuery85() throws InterruptedException {
    log.info("Filter test85");

    SiddhiManager siddhiManager = new SiddhiManager();
    StreamDefinition cseEventStream = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.DOUBLE)
            .attribute("quantity", Attribute.Type.INT);

    Query query = new Query();
    query.from(InputStream.stream("cseEventStream").filter(Expression.compare(Expression.variable("quantity"),
            Compare.Operator.LESS_THAN,
            Expression.value(4L))));
    query.annotation(Annotation.annotation("info").element("name", "query1"));
    query.select(Selector.selector().select("symbol", Expression.variable("symbol")).select("price", Expression
            .variable("price")).select("quantity", Expression.variable("quantity")));
    query.insertInto("outputStream");

    SiddhiApp siddhiApp = new SiddhiApp("ep1");
    siddhiApp.defineStream(cseEventStream);
    siddhiApp.addQuery(query);
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);

    siddhiAppRuntime.addCallback("query1", new QueryCallback() {
        @Override
        public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
            EventPrinter.print(timeStamp, inEvents, removeEvents);
            count.addAndGet(inEvents.length);
        }
    });

    InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream");
    siddhiAppRuntime.start();
    inputHandler.send(new Object[]{"WSO2", 500f, 50d, 6});
    inputHandler.send(new Object[]{"WSO2", 70f, 60d, 2});
    inputHandler.send(new Object[]{"WSO2", 50f, 300d, 4});
    SiddhiTestHelper.waitForEvents(10, 1, count, 100);
    AssertJUnit.assertEquals(1, count.get());
    siddhiAppRuntime.shutdown();
}
 
Example #24
Source File: DefineStreamTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatingStreamDefinition() {
    SiddhiApp.siddhiApp("Test").defineStream(StreamDefinition.id("StockStream").attribute("symbol",
            Attribute.Type.STRING).attribute("price", Attribute.Type.INT).attribute("volume", Attribute.Type
            .FLOAT));


}
 
Example #25
Source File: StreamEventPopulaterFactory.java    From siddhi with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs StreamEventPopulater according to MetaStateEvent and to be mapped attributes
 *
 * @param metaStreamEvent       info for populating the StreamEvent
 * @param streamEventChainIndex StreamEvent chain index
 * @param attributes            mapped attributes
 * @return StateEventPopulater
 */
public static SelectiveComplexEventPopulater constructEventPopulator(MetaStreamEvent metaStreamEvent, int
        streamEventChainIndex, List<Attribute> attributes) {

    List<StreamMappingElement> streamMappingElements = new ArrayList<StreamMappingElement>();
    for (int i = 0, attributesSize = attributes.size(); i < attributesSize; i++) {
        Attribute attribute = attributes.get(i);
        StreamMappingElement streamMappingElement = new StreamMappingElement();
        streamMappingElement.setFromPosition(i);
        int index = metaStreamEvent.getOutputData().indexOf(attribute);
        if (index > -1) {
            streamMappingElement.setToPosition(new int[]{streamEventChainIndex, 0, OUTPUT_DATA_INDEX, index});
        } else {
            index = metaStreamEvent.getOnAfterWindowData().indexOf(attribute);
            if (index > -1) {
                streamMappingElement.setToPosition(new int[]{streamEventChainIndex, 0,
                        ON_AFTER_WINDOW_DATA_INDEX, index});
            } else {
                index = metaStreamEvent.getBeforeWindowData().indexOf(attribute);
                if (index > -1) {
                    streamMappingElement.setToPosition(new int[]{streamEventChainIndex, 0,
                            BEFORE_WINDOW_DATA_INDEX, index});
                } else {
                    streamMappingElement.setToPosition(null);
                }
            }
        }
        streamMappingElements.add(streamMappingElement);
    }

    return new SelectiveComplexEventPopulater(streamMappingElements);

}
 
Example #26
Source File: SiddhiAppParser.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private static StreamDefinition createFaultStreamDefinition(StreamDefinition streamDefinition) {

        List<Attribute> attributeList = streamDefinition.getAttributeList();
        StreamDefinition faultStreamDefinition = new StreamDefinition();
        faultStreamDefinition.setId(SiddhiConstants.FAULT_STREAM_PREFIX.concat(streamDefinition.getId()));
        for (Attribute attribute : attributeList) {
            faultStreamDefinition.attribute(attribute.getName(), attribute.getType());
        }
        faultStreamDefinition.attribute("_error", Attribute.Type.OBJECT);

        faultStreamDefinition.setQueryContextStartIndex(streamDefinition.getQueryContextStartIndex());
        faultStreamDefinition.setQueryContextEndIndex(streamDefinition.getQueryContextEndIndex());
        return faultStreamDefinition;
    }
 
Example #27
Source File: EventTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
    public void testConditionExpressionExecutors() {
//        StreamDefinition streamDefinition = StreamDefinition.id("cseEventStream").attribute("symbol", Attribute
// .Type.STRING).attribute("price", Attribute.Type.FLOAT).attribute("volume", Attribute.Type.INT);

        VariableExpressionExecutor priceVariableExpressionExecutor = new VariableExpressionExecutor(new Attribute
                ("price", Attribute.Type.FLOAT), 0, 0);
        priceVariableExpressionExecutor.setPosition(new int[]{0, SiddhiConstants.UNKNOWN_STATE, SiddhiConstants
                .OUTPUT_DATA_INDEX, 1});

        VariableExpressionExecutor volumeVariableExpressionExecutor = new VariableExpressionExecutor(new Attribute
                ("volume", Attribute.Type.INT), 0, 0);
        volumeVariableExpressionExecutor.setPosition(new int[]{0, SiddhiConstants.UNKNOWN_STATE, SiddhiConstants
                .OUTPUT_DATA_INDEX, 2});

        ExpressionExecutor compareLessThanExecutor = new LessThanCompareConditionExpressionExecutorFloatFloat(new
                ConstantExpressionExecutor(10f, Attribute.Type.FLOAT), priceVariableExpressionExecutor);
        ExpressionExecutor compareGreaterThanExecutor = new GreaterThanCompareConditionExpressionExecutorIntInt(new
                ConstantExpressionExecutor(10, Attribute.Type.INT), volumeVariableExpressionExecutor);
        ExpressionExecutor andExecutor = new AndConditionExpressionExecutor(compareLessThanExecutor,
                compareGreaterThanExecutor);

        int count = 0;
        for (int i = 0; i < 3; i++) {
            StreamEvent event = new StreamEvent(0, 0, 3);
            event.setOutputData(new Object[]{"WSO2", i * 11f, 5});
            if ((Boolean) andExecutor.execute(event)) {
                count++;
            }
        }

        AssertJUnit.assertEquals("Two events should pass through executor", 2, count);
    }
 
Example #28
Source File: DefineStreamTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamDefinition6() {
    StreamDefinition streamDefinition = StreamDefinition.id("Foo");
    streamDefinition.setId("StockStream");
    streamDefinition.attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.INT).attribute("volume", Attribute.Type.FLOAT);
    StreamDefinition streamDefinition2 = StreamDefinition.id("StockStream").attribute("symbol", Attribute.Type
            .STRING).attribute("price", Attribute.Type.INT).attribute("volume", Attribute.Type.FLOAT);
    Assert.assertEquals(streamDefinition, streamDefinition2);
    Assert.assertEquals(streamDefinition.hashCode(), streamDefinition2.hashCode());
    streamDefinition.annotation(Annotation.annotation("Foo"));
    Assert.assertTrue(streamDefinition.equalsIgnoreAnnotations(streamDefinition2));
    Assert.assertFalse(streamDefinition.equals(streamDefinition2));
}
 
Example #29
Source File: DefineFunctionTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = SiddhiAppValidationException.class)
public void testFunction2() {
    SiddhiApp.siddhiApp("test").defineFunction(
            new FunctionDefinition().id("foo").type(Attribute.Type.STRING)
                    .body("return 'hello world!'"));

}
 
Example #30
Source File: DefineFunctionTestCase.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = SiddhiAppValidationException.class)
public void testFunction4() {
    SiddhiApp.siddhiApp("test").defineFunction(
            new FunctionDefinition().language("JS").type(Attribute.Type.STRING)
                    .body("return 'hello world!'"));

}