io.siddhi.core.exception.SiddhiAppRuntimeException Java Examples

The following examples show how to use io.siddhi.core.exception.SiddhiAppRuntimeException. 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: ExpressionWindowProcessor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private MetaStateEvent constructExpression(MetaStreamEvent metaStreamEvent,
                                           SiddhiQueryContext siddhiQueryContext) {
    Expression expression = SiddhiCompiler.parseExpression(expressionString);
    MetaStreamEvent metaStreamEventFirst = new MetaStreamEventWrapper(metaStreamEvent);
    metaStreamEventFirst.setInputReferenceId("first");
    MetaStreamEvent metaStreamEventLast = new MetaStreamEventWrapper(metaStreamEvent);
    metaStreamEventLast.setInputReferenceId("last");
    MetaStateEvent metaStateEvent = new MetaStateEvent(
            new MetaStreamEvent[]{metaStreamEvent, metaStreamEventFirst, metaStreamEventLast});
    variableExpressionExecutors = new ArrayList<>();
    SiddhiQueryContext exprQueryContext = new SiddhiOnDemandQueryContext(
            siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext.getName(),
            expressionString);
    expressionExecutor = ExpressionParser.parseExpression(expression, metaStateEvent,
            0, new HashMap<>(), variableExpressionExecutors, false,
            0, ProcessingMode.SLIDE, true, exprQueryContext);
    if (expressionExecutor.getReturnType() != Attribute.Type.BOOL) {
        throw new SiddhiAppRuntimeException("Expression ('" + expressionString + "') does not return Bool");
    }
    return metaStateEvent;
}
 
Example #2
Source File: SnapshotService.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private void waitForSystemStabilization() {
    int retryCount = 100;
    int activeThreads = siddhiAppContext.getThreadBarrier().getActiveThreads();
    while (activeThreads != 0 && retryCount > 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new SiddhiAppRuntimeException("Stabilization of Siddhi App " + siddhiAppContext.getName() +
                    " for snapshot/restore interrupted. " + e.getMessage(), e);
        }
        activeThreads = siddhiAppContext.getThreadBarrier().getActiveThreads();
        retryCount--;
    }
    if (retryCount == 0) {
        throw new SiddhiAppRuntimeException("Siddhi App " + siddhiAppContext.getName() +
                " not stabilized for snapshot/restore, Active thread count is " +
                activeThreads);
    }
}
 
Example #3
Source File: PartitionStateHolder.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
public void returnState(State state) {
    String partitionFlowId = SiddhiAppContext.getPartitionFlowId();
    String groupByFlowId = SiddhiAppContext.getGroupByFlowId();
    if (state.activeUseCount == 0) {
        try {
            if (state.canDestroy()) {
                removeState(partitionFlowId, groupByFlowId);
            }
        } catch (Throwable t) {
            log.error("Dropping partition state for partition key '" + partitionFlowId +
                    "' and the group by key '" + groupByFlowId + "', due to error! " + t.getMessage(), t);
            removeState(partitionFlowId, groupByFlowId);
        }
    } else if (state.activeUseCount < 0) {
        throw new SiddhiAppRuntimeException("State active count has reached less then zero for partition key '" +
                partitionFlowId + "' and the group by key '" + groupByFlowId + "', current value is " +
                state.activeUseCount);
    }
}
 
Example #4
Source File: CacheExpirer.java    From siddhi with Apache License 2.0 6 votes vote down vote up
public Runnable generateCacheExpirer() {
    class CheckAndExpireCache implements Runnable {

        public CheckAndExpireCache() {
        }

        @Override
        public void run() {
            try {
                storeTable.handleCacheExpiry(cacheExpiryCompiledCondition, generateDeleteEventChunk());
            } catch (Exception e) {
                throw new SiddhiAppRuntimeException(siddhiAppContext.getName() + ": " + e.getMessage());
            }
        }
    }
    return new CheckAndExpireCache();
}
 
Example #5
Source File: AttributeConverter.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the given object to the given type.
 *
 * @param propertyValue the actual object
 * @param attributeType the desired data type
 * @return the converted object
 */
public Object getPropertyValue(String propertyValue, Attribute.Type attributeType) {
    switch (attributeType) {
        case BOOL:
            return Boolean.parseBoolean(propertyValue);
        case DOUBLE:
            return Double.parseDouble(propertyValue);
        case FLOAT:
            return Float.parseFloat(propertyValue);
        case INT:
            return Integer.parseInt(propertyValue);
        case LONG:
            return Long.parseLong(propertyValue);
        case STRING:
            return propertyValue;
        case OBJECT:
            return propertyValue;
        default:
            throw new SiddhiAppRuntimeException("No supported mapping for '" + propertyValue +
                    "' with class '" + propertyValue.getClass().getName() + "' to attribute type '" +
                    attributeType + "'.");
    }
}
 
Example #6
Source File: IncrementalTimeConverterUtil.java    From siddhi with Apache License 2.0 6 votes vote down vote up
public static long getPreviousStartTime(long currentStartTime, TimePeriod.Duration duration) {
    switch (duration) {
        case SECONDS:
            return currentStartTime - getMillisecondsPerDuration(duration);
        case MINUTES:
            return currentStartTime - getMillisecondsPerDuration(duration);
        case HOURS:
            return currentStartTime - getMillisecondsPerDuration(duration);
        case DAYS:
            return currentStartTime - getMillisecondsPerDuration(duration);
        case MONTHS:
            return getStartTimeOfPreviousMonth(currentStartTime);
        case YEARS:
            return getStartTimeOfPreviousYear(currentStartTime);
        default:
            throw new SiddhiAppRuntimeException("Undefined duration " + duration.toString());
    }
}
 
Example #7
Source File: IncrementalTimeConverterUtil.java    From siddhi with Apache License 2.0 6 votes vote down vote up
public static long getStartTimeOfAggregates(long currentTime, TimePeriod.Duration duration, String timeZone) {
    switch (duration) {
        case SECONDS:
            return currentTime - currentTime % getMillisecondsPerDuration(duration);
        case MINUTES:
            return currentTime - currentTime % getMillisecondsPerDuration(duration);
        case HOURS:
            return getStartTimeOfAggregatesForHour(currentTime, timeZone);
        case DAYS:
            return getStartTimeOfAggregatesForDay(currentTime, timeZone);
        case MONTHS:
            return getStartTimeOfAggregatesForMonth(currentTime, timeZone);
        case YEARS:
            return getStartTimeOfAggregatesForYear(currentTime, timeZone);
        default:
            throw new SiddhiAppRuntimeException("Undefined duration " + duration.toString());
    }
}
 
Example #8
Source File: IncrementalTimeConverterUtil.java    From siddhi with Apache License 2.0 6 votes vote down vote up
public static long getNextEmitTime(long currentTime, TimePeriod.Duration duration, String timeZone) {
    switch (duration) {
        case SECONDS:
            return currentTime - currentTime % 1000 + 1000;
        case MINUTES:
            return currentTime - currentTime % 60000 + 60000;
        case HOURS:
            return getNextEmitTimeForHour(currentTime, timeZone);
        case DAYS:
            return getNextEmitTimeForDay(currentTime, timeZone);
        case MONTHS:
            return getNextEmitTimeForMonth(currentTime, timeZone);
        case YEARS:
            return getNextEmitTimeForYear(currentTime, timeZone);
        default:
            throw new SiddhiAppRuntimeException("Undefined duration " + duration.toString());
    }
}
 
Example #9
Source File: FunctionExecutor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * The main execution method which will be called upon event arrival
 *
 * @param event the event to be executed
 * @return the execution result
 */
@Override
public Object execute(ComplexEvent event) {
    try {
        S state = stateHolder.getState();
        try {
            switch (attributeSize) {
                case 0:
                    return execute((Object) null, state);
                case 1:
                    return execute(attributeExpressionExecutors[0].execute(event), state);
                default:
                    Object[] data = new Object[attributeSize];
                    for (int i = 0; i < attributeSize; i++) {
                        data[i] = attributeExpressionExecutors[i].execute(event);
                    }
                    return execute(data, state);
            }
        } finally {
            stateHolder.returnState(state);
        }
    } catch (Exception e) {
        throw new SiddhiAppRuntimeException(e.getMessage() + ". Exception on class '" + this.getClass().getName()
                + "'", e);
    }
}
 
Example #10
Source File: JoinProcessor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private StreamEvent query(StateEvent joinStateEvent) throws SiddhiAppRuntimeException {
    Table table = ((TableWindowProcessor) findableProcessor).getTable();
    if (table.getIsConnected()) {
        try {
            return ((QueryableProcessor) findableProcessor).query(joinStateEvent, compiledCondition,
                    compiledSelection, expectedOutputAttributes);
        } catch (ConnectionUnavailableException e) {
            table.setIsConnectedToFalse();
            table.connectWithRetry();
            return query(joinStateEvent);
        }
    } else if (table.getIsTryingToConnect()) {
        log.warn("Error while performing query '" + queryName + "' within Siddhi app '" + siddhiAppName +
                "' for event '" + joinStateEvent + "', operation busy waiting at Table '" +
                table.getTableDefinition().getId() + "' as its trying to reconnect!");
        table.waitWhileConnect();
        log.info("Table '" + table.getTableDefinition().getId() + "' has become available for query '" +
                queryName + "' within Siddhi app '" + siddhiAppName + "for matching event '" +
                joinStateEvent + "'");
        return query(joinStateEvent);
    } else {
        table.connectWithRetry();
        return query(joinStateEvent);
    }
}
 
Example #11
Source File: ExpressionBatchWindowProcessor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
private MetaStateEvent constructExpression(MetaStreamEvent metaStreamEvent,
                                           SiddhiQueryContext siddhiQueryContext) {
    Expression expression = SiddhiCompiler.parseExpression(expressionString);
    MetaStreamEvent metaStreamEventFirst = new MetaStreamEventWrapper(metaStreamEvent);
    metaStreamEventFirst.setInputReferenceId("first");
    MetaStreamEvent metaStreamEventLast = new MetaStreamEventWrapper(metaStreamEvent);
    metaStreamEventLast.setInputReferenceId("last");
    MetaStateEvent metaStateEvent = new MetaStateEvent(
            new MetaStreamEvent[]{metaStreamEvent, metaStreamEventFirst, metaStreamEventLast});
    variableExpressionExecutors = new ArrayList<>();
    SiddhiQueryContext exprQueryContext = new SiddhiOnDemandQueryContext(
            siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext.getName(),
            expressionString);
    expressionExecutor = ExpressionParser.parseExpression(expression, metaStateEvent,
            0, new HashMap<>(), variableExpressionExecutors, false,
            0, ProcessingMode.SLIDE, true, exprQueryContext);
    if (expressionExecutor.getReturnType() != Attribute.Type.BOOL) {
        throw new SiddhiAppRuntimeException("Expression ('" + expressionString + "') does not return Bool");
    }
    return metaStateEvent;
}
 
Example #12
Source File: MinIncrementalAttributeAggregator.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
public void init(String attributeName, Attribute.Type attributeType) {

    if (attributeName == null) {
        throw new SiddhiAppCreationException("Min incremental attribute aggregation cannot be executed " +
                "when no parameters are given");
    }

    if (attributeType.equals(Attribute.Type.INT) || attributeType.equals(Attribute.Type.LONG) ||
            attributeType.equals(Attribute.Type.DOUBLE) || attributeType.equals(Attribute.Type.FLOAT)) {
        this.baseAttributes = new Attribute[]{new Attribute("AGG_MIN_".concat(attributeName), attributeType)};
        this.baseAttributesInitialValues = new Expression[]{Expression.variable(attributeName)};
        this.returnType = attributeType;
    } else {
        throw new SiddhiAppRuntimeException(
                "Min aggregation cannot be executed on attribute type " + attributeType.toString());
    }
}
 
Example #13
Source File: MaxIncrementalAttributeAggregator.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
public void init(String attributeName, Attribute.Type attributeType) {

    if (attributeName == null) {
        throw new SiddhiAppCreationException("Max incremental attribute aggregation cannot be executed " +
                "when no parameters are given");
    }

    if (attributeType.equals(Attribute.Type.INT) || attributeType.equals(Attribute.Type.LONG) ||
            attributeType.equals(Attribute.Type.DOUBLE) || attributeType.equals(Attribute.Type.FLOAT)) {
        this.baseAttributes = new Attribute[]{new Attribute("AGG_MAX_".concat(attributeName), attributeType)};
        this.baseAttributesInitialValues = new Expression[]{Expression.variable(attributeName)};
        this.returnType = attributeType;
    } else {
        throw new SiddhiAppRuntimeException(
                "Max aggregation cannot be executed on attribute type " + attributeType.toString());
    }
}
 
Example #14
Source File: IncrementalUnixTimeFunctionExecutor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
public static long getUnixTimeStamp(String stringTimeStamp) {
    stringTimeStamp = stringTimeStamp.trim();
    // stringTimeStamp must be of format "2017-06-01 04:05:50 +05:00 (not GMT) or 2017-06-01 04:05:50 (if in GMT)"
    if (gmtRegexPattern.matcher(stringTimeStamp).matches()) {
        String[] dateTime = stringTimeStamp.split(" ");
        return Instant.parse(dateTime[0].concat("T").concat(dateTime[1]).concat("Z")).toEpochMilli();
    } else if (nonGmtRegexPattern.matcher(stringTimeStamp).matches()) {
        String[] dateTimeZone = stringTimeStamp.split(" ");
        String[] splitDate = dateTimeZone[0].split("-");
        String[] splitTime = dateTimeZone[1].split(":");
        return ZonedDateTime
                .of(Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]), Integer.parseInt(splitDate[2]),
                        Integer.parseInt(splitTime[0]), Integer.parseInt(splitTime[1]),
                        Integer.parseInt(splitTime[2]), 0, ZoneId.ofOffset("GMT", ZoneOffset.of(dateTimeZone[2])))
                .toEpochSecond() * 1000;
    }
    throw new SiddhiAppRuntimeException("Timestamp '" + stringTimeStamp + "' doesn't match "
            + "the supported formats <yyyy>-<MM>-<dd> <HH>:<mm>:<ss> (for GMT time zone) or " +
            "<yyyy>-<MM>-<dd> <HH>:<mm>:<ss> <Z> (for non GMT time zone). The ISO 8601 UTC offset must be "
            + "provided for <Z> (ex. +05:30, -11:00)");
}
 
Example #15
Source File: IncrementalStartTimeEndTimeFunctionExecutor.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute(Object[] data, State state) {
    long startTime;
    long endTime;

    if (data[0] instanceof Long) {
        startTime = (long) data[0];
    } else {
        startTime = IncrementalUnixTimeFunctionExecutor.getUnixTimeStamp(data[0].toString());
    }
    if (data[1] instanceof Long) {
        endTime = (long) data[1];
    } else {
        endTime = IncrementalUnixTimeFunctionExecutor.getUnixTimeStamp(data[1].toString());
    }

    if (!(startTime < endTime)) {
        throw new SiddhiAppRuntimeException("The start time must be less than the end time in the within clause. "
                + "However, the given start time is " + startTime + " and given end time is " + endTime
                + ", in unix time. Hence, start time is not less than end time.");
    }
    return new Long[]{startTime, endTime};
}
 
Example #16
Source File: PassThroughSourceMapper.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
protected void mapAndProcess(Object eventObject, InputEventHandler inputEventHandler) throws InterruptedException {
    if (eventObject != null) {
        if (eventObject instanceof Event[]) {
            inputEventHandler.sendEvents((Event[]) eventObject);
        } else if (eventObject instanceof Event) {
            inputEventHandler.sendEvent((Event) eventObject);
        } else if (eventObject instanceof Object[]) {
            Event event = new Event(-1, (Object[]) eventObject);
            inputEventHandler.sendEvent(event);
        } else {
            throw new SiddhiAppRuntimeException("Event object must be either Event[], Event or Object[] " +
                    "but found " + eventObject.getClass().getCanonicalName());
        }
    }
}
 
Example #17
Source File: TestAsyncInMemory.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        if (fail || failOnce) {
            failOnce = false;
            numberOfErrorOccurred++;
            throw new ConnectionUnavailableException("Connection unavailable during publishing");
        }
        sink.send(payload, dynamicOptions, state);
    } catch (Throwable e) {
        if (failRuntime) {
            onError(payload, dynamicOptions, new SiddhiAppRuntimeException(e.getMessage(), e));
        } else {
            onError(payload, dynamicOptions, new ConnectionUnavailableException(e.getMessage(), e));
        }
    }
}
 
Example #18
Source File: TestTrpSourceMapper.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@Override
protected void mapAndProcess(Object eventObject, InputEventHandler inputEventHandler) throws InterruptedException {
    if (eventObject != null) {
        if (eventObject instanceof Event) {
            Event output = new Event(streamDefinition.getAttributeList().size());
            for (AttributeMapping attributeMapping : attributeMappingList) {
                output.getData()[attributeMapping.getPosition()] = ((Event) eventObject).getData(
                        Integer.parseInt(attributeMapping.getMapping()));
            }
            inputEventHandler.sendEvent(output);
        } else {
            throw new SiddhiAppRuntimeException("Event object must be either Event[], Event or Object[] " +
                    "but found " + eventObject.getClass().getCanonicalName());
        }
    }
}
 
Example #19
Source File: IncrementalTimeConverterUtil.java    From siddhi with Apache License 2.0 5 votes vote down vote up
public static int getMillisecondsPerDuration(TimePeriod.Duration duration) {
    switch (duration) {
        case SECONDS:
            return 1000;
        case MINUTES:
            return 60000;
        case HOURS:
            return 3600000;
        case DAYS:
            return 86400000;
        default:
            throw new SiddhiAppRuntimeException("Cannot provide number of milliseconds per duration " + duration
                    + ".Number of milliseconds are only define for SECONDS, MINUTES, HOURS and DAYS");
    }
}
 
Example #20
Source File: IfThenElseFunctionExecutor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(ComplexEvent event) {
    try {
        Boolean condition = Boolean.TRUE.equals(attributeExpressionExecutors[0].execute(event));
        return execute(
                new Object[]{
                        condition,
                        (condition) ? attributeExpressionExecutors[1].execute(event) : null,
                        (!condition) ? attributeExpressionExecutors[2].execute(event) : null
                });
    } catch (Exception e) {
        throw new SiddhiAppRuntimeException(e.getMessage() + ". Exception on class '" + this.getClass().getName()
                + "'", e);
    }
}
 
Example #21
Source File: IncrementalTimeGetTimeZone.java    From siddhi with Apache License 2.0 5 votes vote down vote up
public static String getTimeZone(String stringTimeStamp) {
    stringTimeStamp = stringTimeStamp.trim();
    // stringTimeStamp must be of format "2017-06-01 04:05:50 +05:00 (not GMT) or 2017-06-01 04:05:50 (if in GMT)"
    if (gmtRegexPattern.matcher(stringTimeStamp).matches()) {
        return "+00:00";
    } else if (nonGmtRegexPattern.matcher(stringTimeStamp).matches()) {
        String[] dateTimeZone = stringTimeStamp.split(" ");
        return dateTimeZone[2];
    }
    throw new SiddhiAppRuntimeException("Timestamp " + stringTimeStamp + "doesn't match "
            + "the supported formats <yyyy>-<MM>-<dd> <HH>:<mm>:<ss> (for GMT time zone) or " +
            "<yyyy>-<MM>-<dd> <HH>:<mm>:<ss> <Z> (for non GMT time zone). The ISO 8601 UTC offset must be "
            + "provided for <Z> (ex. +05:30, -11:00");
}
 
Example #22
Source File: SizeOfSetFunctionExecutor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
protected Object execute(Object data, State state) {
    if (data == null) {
        return 0;
    }
    if (!(data instanceof Set)) {
        throw new SiddhiAppRuntimeException("Input to sizeOfSet() function should be an instance of " +
                "java.util.Set, but found " + data.getClass().getCanonicalName());
    }
    Set set = (Set) data;
    return set.size();
}
 
Example #23
Source File: IncrementalAggregateBaseTimeFunctionExecutor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
protected Object execute(Object[] data, State state) {
    long time = (long) data[0];
    String durationName = (String) data[1];
    TimePeriod.Duration duration;
    switch (durationName) {
        case "SECONDS":
            duration = TimePeriod.Duration.SECONDS;
            break;
        case "MINUTES":
            duration = TimePeriod.Duration.MINUTES;
            break;
        case "HOURS":
            duration = TimePeriod.Duration.HOURS;
            break;
        case "DAYS":
            duration = TimePeriod.Duration.DAYS;
            break;
        case "MONTHS":
            duration = TimePeriod.Duration.MONTHS;
            break;
        case "YEARS":
            duration = TimePeriod.Duration.YEARS;
            break;
        default:
            // Will not get hit
            throw new SiddhiAppRuntimeException("Duration '" + durationName + "' used for " +
                    "incrementalAggregator:aggregateBaseTime() is invalid.");
    }
    return IncrementalTimeConverterUtil.getStartTimeOfAggregates(time, duration, timeZone);
}
 
Example #24
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 #25
Source File: TestSourceOptionSourceMapper.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
protected void mapAndProcess(Object eventObject, InputEventHandler inputEventHandler) throws InterruptedException {
    if (eventObject != null) {
        if (eventObject instanceof Event) {
            Event event = ((Event) eventObject);
            event.getData()[0] = sourceOptionHolder.validateAndGetOption("topic").getValue(event);
            event.getData()[1] = sourceType;
            inputEventHandler.sendEvent((Event) eventObject);
        } else {
            throw new SiddhiAppRuntimeException("Event object must be Event " +
                    "but found " + eventObject.getClass().getCanonicalName());
        }
    }

}
 
Example #26
Source File: PartitionStateHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
public void returnAllStates(Map states) {
    for (Iterator<Map.Entry<String, Map<String, State>>> statesIterator =
         ((Set<Map.Entry<String, Map<String, State>>>) states.entrySet()).iterator(); statesIterator.hasNext(); ) {
        Map.Entry<String, Map<String, State>> statesEntry = statesIterator.next();
        for (Iterator<Map.Entry<String, State>> stateIterator = statesEntry.getValue().entrySet().iterator();
             stateIterator.hasNext(); ) {
            Map.Entry<String, State> stateEntry = stateIterator.next();
            State state = stateEntry.getValue();
            if (state.activeUseCount == 0) {
                try {
                    if (state.canDestroy()) {
                        stateIterator.remove();
                    }
                } catch (Throwable t) {
                    log.error("Dropping partition state for partition key '" + statesEntry.getKey() +
                            "' and the group by key '" + stateEntry.getKey() + "', due to error! " +
                            t.getMessage(), t);
                    stateIterator.remove();
                }
            } else if (state.activeUseCount < 0) {
                throw new SiddhiAppRuntimeException("State active count has reached less then zero for " +
                        "partition key '" + statesEntry.getKey() + "' and the group by key '" +
                        stateEntry.getKey() + "', current value is " +
                        state.activeUseCount);
            }
        }
        if (statesEntry.getValue().isEmpty()) {
            statesIterator.remove();
        }
    }
}
 
Example #27
Source File: PartitionStateHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
public void returnGroupByStates(Map states) {
    String partitionFlowId = SiddhiAppContext.getPartitionFlowId();
    for (Iterator<Map.Entry<String, State>> iterator =
         ((Set<Map.Entry<String, State>>) states.entrySet()).iterator();
         iterator.hasNext(); ) {
        Map.Entry<String, State> stateEntry = iterator.next();
        State state = stateEntry.getValue();
        if (state.activeUseCount == 0) {
            try {
                if (state.canDestroy()) {
                    iterator.remove();
                }
            } catch (Throwable t) {
                log.error("Dropping partition state for partition key '" + partitionFlowId +
                        "' and the group by key '" + stateEntry.getKey() + "', due to error! " + t.getMessage(), t);
                iterator.remove();
            }
        } else if (state.activeUseCount < 0) {
            throw new SiddhiAppRuntimeException("State active count has reached less then zero for partition key '"
                    + partitionFlowId + "' and the group by key '" + stateEntry.getKey() + "', current value is " +
                    state.activeUseCount);
        }

    }
    if (states.isEmpty()) {
        states.remove(partitionFlowId);
    }
}
 
Example #28
Source File: IndexEventHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
private void add(StreamEvent streamEvent) {
    StreamEvent existingValue = null;
    if (primaryKeyData != null) {
        Object primaryKey = constructPrimaryKey(streamEvent, primaryKeyReferenceHolders);
        existingValue = primaryKeyData.putIfAbsent(primaryKey, streamEvent);
        if (existingValue != null) {
            Exception e = new SiddhiAppRuntimeException("Siddhi App '" + siddhiAppName + "' table '" +
                    tableName + "' dropping event : " + streamEvent + ", as there is already an event stored " +
                    "with primary key '" + primaryKey + "'");
            if (siddhiAppContext.getRuntimeExceptionListener() != null) {
                siddhiAppContext.getRuntimeExceptionListener().exceptionThrown(e);
            }
            log.error(e.getMessage(), e);
        }
    }

    if (indexData != null) {
        for (Map.Entry<String, Integer> indexEntry : indexMetaData.entrySet()) {
            TreeMap<Object, Set<StreamEvent>> indexMap = indexData.get(indexEntry.getKey());
            Object key = streamEvent.getOutputData()[indexEntry.getValue()];
            Set<StreamEvent> values = indexMap.get(key);
            if (values == null) {
                values = new HashSet<StreamEvent>();
                values.add(streamEvent);
                indexMap.put(streamEvent.getOutputData()[indexEntry.getValue()], values);
            } else {
                values.add(streamEvent);
            }
        }
    }

}
 
Example #29
Source File: IncrementalAggregationProcessor.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
public void process(ComplexEventChunk complexEventChunk) {
    ComplexEventChunk<StreamEvent> streamEventChunk =
            new ComplexEventChunk<>();
    try {
        int noOfEvents = 0;
        if (latencyTrackerInsert != null && Level.BASIC.compareTo(siddhiAppContext.getRootMetricsLevel()) <= 0) {
            latencyTrackerInsert.markIn();
        }
        while (complexEventChunk.hasNext()) {
            ComplexEvent complexEvent = complexEventChunk.next();
            if (!isFirstEventArrived) {
                aggregationRuntime.initialiseExecutors(true);
                isFirstEventArrived = true;
            }
            StreamEvent newEvent = streamEventFactory.newInstance();
            for (int i = 0; i < incomingExpressionExecutors.size(); i++) {
                ExpressionExecutor expressionExecutor = incomingExpressionExecutors.get(i);
                Object outputData = expressionExecutor.execute(complexEvent);
                if (expressionExecutor instanceof IncrementalUnixTimeFunctionExecutor && outputData == null) {
                    throw new SiddhiAppRuntimeException("Cannot retrieve the timestamp of event");
                }
                newEvent.setOutputData(outputData, i);
            }
            streamEventChunk.add(newEvent);
            noOfEvents++;
        }
        aggregationRuntime.processEvents(streamEventChunk);
        if (throughputTrackerInsert != null &&
                Level.BASIC.compareTo(siddhiAppContext.getRootMetricsLevel()) <= 0) {
            throughputTrackerInsert.eventsIn(noOfEvents);
        }
    } finally {
        if (latencyTrackerInsert != null && Level.BASIC.compareTo(siddhiAppContext.getRootMetricsLevel()) <= 0) {
            latencyTrackerInsert.markOut();
        }
    }

}
 
Example #30
Source File: SiddhiAppRuntimeImpl.java    From siddhi with Apache License 2.0 5 votes vote down vote up
public void startSources() {
    if (running) {
        log.warn("Error calling startSources() for Siddhi App '" + siddhiAppContext.getName() + "', " +
                "SiddhiApp already started with the sources.");
        return;
    }
    if (!runningWithoutSources) {
        throw new SiddhiAppRuntimeException("Cannot call startSources() without calling startWithoutSources() " +
                "for Siddhi App '" + siddhiAppContext.getName() + "'");
    } else {
        try {
            for (List<Source> sources : sourceMap.values()) {
                for (Source source : sources) {
                    source.connectWithRetry();
                }
            }
            running = true;
            runningWithoutSources = false;
        } catch (Throwable t) {
            log.error("Error starting Siddhi App '" + siddhiAppContext.getName() + "', " +
                    "triggering shutdown process. " + t.getMessage());
            try {
                shutdown();
            } catch (Throwable t1) {
                log.error("Error shutting down partially started Siddhi App '" + siddhiAppContext.getName() + "', "
                        + t1.getMessage());
            }
        }
    }
}