Search in sources :

Example 16 with ShouldNeverHappenException

use of com.serotonin.ShouldNeverHappenException in project ma-core-public by infiniteautomation.

the class EventInstanceDao method getPropertiesMap.

/* (non-Javadoc)
	 * @see com.serotonin.m2m2.db.dao.AbstractBasicDao#getPropertiesMap()
	 */
@Override
protected Map<String, IntStringPair> getPropertiesMap() {
    Map<String, IntStringPair> map = new HashMap<String, IntStringPair>();
    map.put("activeTimestamp", new IntStringPair(Types.BIGINT, "activeTs"));
    map.put("activeTimestampString", new IntStringPair(Types.BIGINT, "activeTs"));
    map.put("rtnTimestampString", new IntStringPair(Types.BIGINT, "rtnTs"));
    /*
         * IF(evt.rtnTs=null,
         * 		IF(evt.rtnApplicable='Y',
         * 			(NOW() - evt.activeTs),
         * 			-1),
         * 		IF(evt.rtnApplicable='Y',
         * 			(evt.rtnTs - evt.activeTs),
         * 			-1)
         *  )
         */
    switch(Common.databaseProxy.getType()) {
        case MYSQL:
        case MSSQL:
            map.put("totalTimeString", new IntStringPair(Types.BIGINT, "IF(evt.rtnTs is null,IF(evt.rtnApplicable='Y',(? - evt.activeTs),-1),IF(evt.rtnApplicable='Y',(evt.rtnTs - evt.activeTs),-1))"));
            break;
        case H2:
        case DERBY:
            map.put("totalTimeString", new IntStringPair(Types.BIGINT, "CASE WHEN evt.rtnTs IS NULL THEN " + "CASE WHEN evt.rtnApplicable='Y' THEN (? - evt.activeTs) ELSE -1 END " + "ELSE CASE WHEN evt.rtnApplicable='Y' THEN (evt.rtnTs - evt.activeTs) ELSE -1 END END"));
            break;
        default:
            throw new ShouldNeverHappenException("Unsupported database for Alarms.");
    }
    map.put("messageString", new IntStringPair(Types.VARCHAR, "message"));
    map.put("rtnTimestampString", new IntStringPair(Types.BIGINT, "rtnTs"));
    map.put("userNotified", new IntStringPair(Types.CHAR, "silenced"));
    map.put("acknowledged", new IntStringPair(Types.BIGINT, "ackTs"));
    // Mapping for user
    map.put("userId", new IntStringPair(Types.INTEGER, "ue.userId"));
    return map;
}
Also used : IntStringPair(com.serotonin.db.pair.IntStringPair) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException)

Example 17 with ShouldNeverHappenException

use of com.serotonin.ShouldNeverHappenException in project ma-core-public by infiniteautomation.

the class DBUpgrade method checkUpgrade.

public static void checkUpgrade(String settingsKey, int codeVersion, String pkg, String moduleName, ClassLoader classLoader) {
    // If this is a very old version of the system, there may be multiple upgrades to run, so start a loop.
    while (true) {
        // Get the current schema version.
        int schemaVersion = SystemSettingsDao.getIntValue(settingsKey, -1);
        if (schemaVersion == -1) {
            if ("core".equals(moduleName))
                // Probably an old core. Assume the version to be 1 to do complete upgrade
                schemaVersion = 1;
            else {
                // Probably a new module. Put the current code version into the database.
                SystemSettingsDao.instance.setIntValue(settingsKey, codeVersion);
                schemaVersion = codeVersion;
            }
        }
        // Convert the schema version to the class name convention. This simply means replacing dots with
        // underscores and prefixing 'Upgrade' and this package.
        String upgradeClassname = pkg + ".Upgrade" + Integer.toString(schemaVersion);
        // See if there is a class with this name.
        Class<?> clazz = null;
        DBUpgrade upgrade = null;
        try {
            clazz = Class.forName(upgradeClassname, true, classLoader);
        } catch (ClassNotFoundException e) {
        // no op
        }
        if (clazz != null) {
            try {
                upgrade = (DBUpgrade) clazz.newInstance();
            } catch (Exception e) {
                // Should never happen so wrap in a runtime and rethrow.
                throw new ShouldNeverHappenException(e);
            }
        }
        if (upgrade == null) {
            if (schemaVersion != codeVersion)
                LOG.warn("The code version " + codeVersion + " of module " + moduleName + " does not match the schema version " + schemaVersion);
            break;
        }
        try {
            LOG.warn("Upgrading '" + moduleName + "' from " + schemaVersion + " to " + upgrade.getNewSchemaVersion());
            upgrade.upgrade();
            SystemSettingsDao.instance.setValue(settingsKey, upgrade.getNewSchemaVersion());
        } catch (Exception e) {
            throw new ShouldNeverHappenException(e);
        }
    }
}
Also used : ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException)

Example 18 with ShouldNeverHappenException

use of com.serotonin.ShouldNeverHappenException in project ma-core-public by infiniteautomation.

the class SetPointHandlerRT method eventInactive.

@Override
public void eventInactive(EventInstance evt) {
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE)
        return;
    // Validate that the target point is available.
    DataPointRT targetPoint = Common.runtimeManager.getDataPoint(vo.getTargetPointId());
    if (targetPoint == null) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetPointMissing"), evt.getEventType());
        return;
    }
    if (!targetPoint.getPointLocator().isSettable()) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetNotSettable"), evt.getEventType());
        return;
    }
    int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId();
    DataValue value;
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        // Get the source data point.
        DataPointRT sourcePoint = Common.runtimeManager.getDataPoint(vo.getInactivePointId());
        if (sourcePoint == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointMissing"), evt.getEventType());
            return;
        }
        PointValueTime valueTime = sourcePoint.getPointValue();
        if (valueTime == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointValue"), evt.getEventType());
            return;
        }
        if (DataTypes.getDataType(valueTime.getValue()) != targetDataType) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointDataType"), evt.getEventType());
            return;
        }
        value = valueTime.getValue();
    } else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE)
        value = DataValue.stringToValue(vo.getInactiveValueToSet(), targetDataType);
    else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        if (inactiveScript == null) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScript"), evt.getEventType());
            return;
        }
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put("target", targetPoint);
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(inactiveScript, context, new HashMap<String, Object>(), evt.getRtnTimestamp(), targetPoint.getDataTypeId(), evt.getRtnTimestamp(), vo.getScriptPermissions(), NULL_WRITER, new ScriptLog(NULL_WRITER, LogLevel.FATAL), setCallback, importExclusions, false);
            value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getCause().getMessage()), evt.getEventType());
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getMessage()), evt.getEventType());
            return;
        }
    } else
        throw new ShouldNeverHappenException("Unknown active action: " + vo.getInactiveAction());
    Common.backgroundProcessing.addWorkItem(new SetPointWorkItem(vo.getTargetPointId(), new PointValueTime(value, evt.getRtnTimestamp()), this));
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) HashMap(java.util.HashMap) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 19 with ShouldNeverHappenException

use of com.serotonin.ShouldNeverHappenException in project ma-core-public by infiniteautomation.

the class DataPointRT method savePointValue.

private void savePointValue(PointValueTime newValue, SetPointSource source, boolean async, boolean saveToDatabase) {
    // Null values are not very nice, and since they don't have a specific meaning they are hereby ignored.
    if (newValue == null)
        return;
    // Check the data type of the value against that of the locator, just for fun.
    int valueDataType = DataTypes.getDataType(newValue.getValue());
    if (valueDataType != DataTypes.UNKNOWN && valueDataType != vo.getPointLocator().getDataTypeId())
        // to know how it happened, and the stack trace here provides the best information.
        throw new ShouldNeverHappenException("Data type mismatch between new value and point locator: newValue=" + DataTypes.getDataType(newValue.getValue()) + ", locator=" + vo.getPointLocator().getDataTypeId());
    // Check if this value qualifies for discardation.
    if (vo.isDiscardExtremeValues() && DataTypes.getDataType(newValue.getValue()) == DataTypes.NUMERIC) {
        double newd = newValue.getDoubleValue();
        // Discard if NaN
        if (Double.isNaN(newd))
            return;
        if (newd < vo.getDiscardLowLimit() || newd > vo.getDiscardHighLimit())
            // Discard the value
            return;
    }
    if (newValue.getTime() > Common.timer.currentTimeMillis() + SystemSettingsDao.getFutureDateLimit()) {
        // Too far future dated. Toss it. But log a message first.
        LOG.warn("Future dated value detected: pointId=" + vo.getId() + ", value=" + newValue.getValue().toString() + ", type=" + vo.getPointLocator().getDataTypeId() + ", ts=" + newValue.getTime(), new Exception());
        return;
    }
    boolean backdated = pointValue != null && newValue.getTime() < pointValue.getTime();
    // Determine whether the new value qualifies for logging.
    boolean logValue;
    // ... or even saving in the cache.
    boolean saveValue = true;
    switch(vo.getLoggingType()) {
        case DataPointVO.LoggingTypes.ON_CHANGE_INTERVAL:
        case DataPointVO.LoggingTypes.ON_CHANGE:
            if (pointValue == null)
                logValue = true;
            else if (backdated)
                // Backdated. Ignore it
                logValue = false;
            else {
                if (newValue.getValue() instanceof NumericValue) {
                    // Get the new double
                    double newd = newValue.getDoubleValue();
                    // See if the new value is outside of the tolerance.
                    double diff = toleranceOrigin - newd;
                    if (diff < 0)
                        diff = -diff;
                    if (diff > vo.getTolerance()) {
                        toleranceOrigin = newd;
                        logValue = true;
                    } else
                        logValue = false;
                } else if (newValue.getValue() instanceof ImageValue) {
                    logValue = !((ImageValue) newValue.getValue()).equalDigests(((ImageValue) pointValue.getValue()).getDigest());
                } else
                    logValue = !Objects.equals(newValue.getValue(), pointValue.getValue());
            }
            saveValue = logValue;
            break;
        case DataPointVO.LoggingTypes.ALL:
            logValue = true;
            break;
        case DataPointVO.LoggingTypes.ON_TS_CHANGE:
            if (pointValue == null)
                logValue = true;
            else if (backdated)
                // Backdated. Ignore it
                logValue = false;
            else
                logValue = newValue.getTime() != pointValue.getTime();
            saveValue = logValue;
            break;
        case DataPointVO.LoggingTypes.INTERVAL:
            if (!backdated)
                intervalSave(newValue);
        default:
            logValue = false;
    }
    if (!saveToDatabase)
        logValue = false;
    if (saveValue) {
        valueCache.savePointValue(newValue, source, logValue, async);
        if (vo.getLoggingType() == DataPointVO.LoggingTypes.ON_CHANGE_INTERVAL)
            rescheduleChangeInterval(Common.getMillis(vo.getIntervalLoggingPeriodType(), vo.getIntervalLoggingPeriod()));
    }
    // fetch the annotation
    if (source != null) {
        newValue = new AnnotatedPointValueTime(newValue.getValue(), newValue.getTime(), source.getSetPointSourceMessage());
    }
    // Ignore historical values.
    if (pointValue == null || newValue.getTime() >= pointValue.getTime()) {
        PointValueTime oldValue = pointValue;
        pointValue = newValue;
        fireEvents(oldValue, newValue, null, source != null, false, logValue, true, false);
    } else
        fireEvents(null, newValue, null, false, true, logValue, false, false);
}
Also used : ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) NumericValue(com.serotonin.m2m2.rt.dataImage.types.NumericValue) ImageValue(com.serotonin.m2m2.rt.dataImage.types.ImageValue) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException)

Example 20 with ShouldNeverHappenException

use of com.serotonin.ShouldNeverHappenException in project ma-core-public by infiniteautomation.

the class AnalogChangeDetectorRT method getMessage.

@Override
public TranslatableMessage getMessage() {
    String name = vo.njbGetDataPoint().getExtendedName();
    String prettyLimit = vo.njbGetDataPoint().getTextRenderer().getText(vo.getLimit(), TextRenderer.HINT_SPECIFIC);
    TranslatableMessage durationDescription = getDurationDescription();
    if (vo.isCheckIncrease() && vo.isCheckDecrease())
        return new TranslatableMessage("event.detector.analogChangePeriod", name, prettyLimit, durationDescription);
    else if (vo.isCheckIncrease())
        return new TranslatableMessage("event.detector.analogIncreasePeriod", name, prettyLimit, durationDescription);
    else if (vo.isCheckDecrease())
        return new TranslatableMessage("event.detector.analogDecreasePeriod", name, prettyLimit, durationDescription);
    else
        throw new ShouldNeverHappenException("Illegal state for analog change detector" + vo.getXid());
}
Also used : ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Aggregations

ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)83 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)10 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)9 SQLException (java.sql.SQLException)9 ParseException (java.text.ParseException)8 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)6 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)6 FileNotFoundException (java.io.FileNotFoundException)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 ResultSet (java.sql.ResultSet)5 Statement (java.sql.Statement)5 JsonException (com.serotonin.json.JsonException)4 JsonWriter (com.serotonin.json.JsonWriter)4 ImageValue (com.serotonin.m2m2.rt.dataImage.types.ImageValue)4 NumericValue (com.serotonin.m2m2.rt.dataImage.types.NumericValue)4 CronTimerTrigger (com.serotonin.timer.CronTimerTrigger)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 StringWriter (java.io.StringWriter)4 HashMap (java.util.HashMap)4