Search in sources :

Example 76 with ShouldNeverHappenException

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

the class DatabaseBackupWorkItem method schedule.

/**
 * Statically Schedule a Timer Task that will run this work item.
 *
 * TODO For Startup Make this an RTM and add to the RuntimeManager's list of
 * startup RTMS currently only the Module RTMs get started there. For now
 * this call is used within the RuntimeManager
 */
public static void schedule() {
    try {
        // Test trigger for running every 25 seconds.
        // String cronTrigger = "0/25 * * * * ?";
        // Trigger to run at Set Hour/Minute "s m h * * ?";
        int hour = SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_HOUR);
        int minute = SystemSettingsDao.getIntValue(SystemSettingsDao.DATABASE_BACKUP_MINUTE);
        String cronTrigger = "0 " + minute + " " + hour + " * * ?";
        task = new DatabaseBackupTask(cronTrigger);
        Common.timer.schedule(task);
    } catch (ParseException e) {
        throw new ShouldNeverHappenException(e);
    }
}
Also used : ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ParseException(java.text.ParseException)

Example 77 with ShouldNeverHappenException

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

the class EventDetectorRowMapper method mapRow.

/* (non-Javadoc)
	 * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
	 */
@Override
public AbstractEventDetectorVO<?> mapRow(ResultSet rs, int rowNum) throws SQLException {
    EventDetectorDefinition<?> definition = ModuleRegistry.getEventDetectorDefinition(rs.getString(this.firstColumn + 3));
    if (definition == null)
        throw new ShouldNeverHappenException("Event Detector defintion of type: " + rs.getString(this.firstColumn + 3) + " not found.");
    AbstractEventDetectorVO<?> vo = definition.baseCreateEventDetectorVO();
    vo.setId(rs.getInt(this.firstColumn));
    vo.setXid(rs.getString(this.firstColumn + 1));
    vo.setDefinition(definition);
    // Extract the source id
    int sourceIdColumnIndex;
    if (this.sourceIdColumnOffset < 0)
        sourceIdColumnIndex = this.firstColumn + 5 + EventDetectorDao.instance.getSourceIdIndex(definition.getSourceTypeName());
    else
        sourceIdColumnIndex = this.firstColumn + this.sourceIdColumnOffset;
    vo.setSourceId(rs.getInt(sourceIdColumnIndex));
    // Read Into Detector
    JsonTypeReader typeReader = new JsonTypeReader(rs.getString(this.firstColumn + 4));
    try {
        JsonValue value = typeReader.read();
        JsonObject root = value.toJsonObject();
        JsonReader reader = new JsonReader(Common.JSON_CONTEXT, root);
        root.remove("handlers");
        reader.readInto(vo);
    } catch (ClassCastException | IOException | JsonException e) {
        LOG.error(e.getMessage(), e);
    }
    return vo;
}
Also used : JsonException(com.serotonin.json.JsonException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) JsonValue(com.serotonin.json.type.JsonValue) JsonObject(com.serotonin.json.type.JsonObject) JsonReader(com.serotonin.json.JsonReader) IOException(java.io.IOException) JsonTypeReader(com.serotonin.json.type.JsonTypeReader)

Example 78 with ShouldNeverHappenException

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

the class AbstractDatabaseProxy method initialize.

/* (non-Javadoc)
     * @see com.serotonin.m2m2.db.DatabaseProxy#initialize(java.lang.ClassLoader)
     */
@Override
public void initialize(ClassLoader classLoader) {
    initializeImpl("");
    useMetrics = Common.envProps.getBoolean("db.useMetrics", false);
    ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate();
    ejt.setDataSource(getDataSource());
    transactionManager = new DataSourceTransactionManager(getDataSource());
    try {
        if (newDatabaseCheck(ejt)) {
            // Check if we should convert from another database.
            String convertTypeStr = null;
            try {
                convertTypeStr = Common.envProps.getString("convert.db.type");
            } catch (MissingResourceException e) {
                convertTypeStr = "";
            }
            if (!StringUtils.isBlank(convertTypeStr)) {
                // Found a database type from which to convert.
                DatabaseType convertType = DatabaseType.valueOf(convertTypeStr.toUpperCase());
                if (convertType == null)
                    throw new IllegalArgumentException("Unknown convert database type: " + convertType);
                // TODO check that the convert source has the current DB version, or upgrade it if not.
                AbstractDatabaseProxy sourceProxy = convertType.getImpl();
                sourceProxy.initializeImpl("convert.");
                DBConvert convert = new DBConvert();
                convert.setSource(sourceProxy);
                convert.setTarget(this);
                try {
                    convert.execute();
                } catch (SQLException e) {
                    throw new ShouldNeverHappenException(e);
                }
                sourceProxy.terminate(false);
            } else {
                // Record the current version.
                SystemSettingsDao.instance.setValue(SystemSettingsDao.DATABASE_SCHEMA_VERSION, Integer.toString(Common.getDatabaseSchemaVersion()));
                // Add the settings flag that this is a new instance. This flag is removed when an administrator
                // logs in.
                SystemSettingsDao.instance.setBooleanValue(SystemSettingsDao.NEW_INSTANCE, true);
                /**
                 * Add a startup task to run after the Audit system is ready
                 */
                Providers.get(IMangoLifecycle.class).addStartupTask(new Runnable() {

                    @Override
                    public void run() {
                        // New database. Create a default user.
                        User user = new User();
                        user.setId(Common.NEW_ID);
                        user.setName("Administrator");
                        user.setUsername("admin");
                        user.setPassword(Common.encrypt("admin"));
                        user.setEmail("admin@yourMangoDomain.com");
                        user.setPhone("");
                        user.setPermissions(SuperadminPermissionDefinition.GROUP_NAME);
                        user.setDisabled(false);
                        user.setHomeUrl("/ui/administration/home");
                        UserDao.instance.saveUser(user);
                        DefaultDataPointPropertiesTemplateFactory factory = new DefaultDataPointPropertiesTemplateFactory();
                        factory.saveDefaultTemplates();
                    }
                });
            }
        } else
            // The database exists, so let's make its schema version matches the application version.
            DBUpgrade.checkUpgrade();
        // Check if we are using NoSQL
        if (NoSQLProxyFactory.instance.getProxy() != null) {
            noSQLProxy = NoSQLProxyFactory.instance.getProxy();
            noSQLProxy.initialize();
        }
    } catch (CannotGetJdbcConnectionException e) {
        log.fatal("Unable to connect to database of type " + getType().name(), e);
        throw e;
    } catch (Exception e) {
        log.fatal("Exception initializing database proxy: " + e.getMessage(), e);
        throw e;
    }
    // Allow modules to upgrade themselves
    for (DatabaseSchemaDefinition def : ModuleRegistry.getDefinitions(DatabaseSchemaDefinition.class)) DBUpgrade.checkUpgrade(def, classLoader);
    postInitialize(ejt);
}
Also used : User(com.serotonin.m2m2.vo.User) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) DatabaseSchemaDefinition(com.serotonin.m2m2.module.DatabaseSchemaDefinition) MissingResourceException(java.util.MissingResourceException) DefaultDataPointPropertiesTemplateFactory(com.serotonin.m2m2.vo.template.DefaultDataPointPropertiesTemplateFactory) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) SQLException(java.sql.SQLException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) MissingResourceException(java.util.MissingResourceException) FileNotFoundException(java.io.FileNotFoundException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) IMangoLifecycle(com.serotonin.m2m2.IMangoLifecycle) DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager)

Example 79 with ShouldNeverHappenException

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

the class BasePooledProxy method runScript.

@Override
public void runScript(InputStream input, OutputStream out) {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(input));
        List<String> lines = new ArrayList<String>();
        String line;
        while ((line = in.readLine()) != null) lines.add(line);
        String[] script = new String[lines.size()];
        lines.toArray(script);
        runScript(script, out);
    } catch (IOException ioe) {
        throw new ShouldNeverHappenException(ioe);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException ioe) {
            log.warn("", ioe);
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ArrayList(java.util.ArrayList) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) IOException(java.io.IOException)

Example 80 with ShouldNeverHappenException

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

the class DerbyProxy method runScript.

@Override
public void runScript(final InputStream in, OutputStream out) {
    final OutputStream finalOut;
    if (out == null)
        finalOut = new ByteArrayOutputStream();
    else
        finalOut = out;
    Common.databaseProxy.doInConnection(new ConnectionCallbackVoid() {

        @Override
        public void doInConnection(Connection conn) {
            try {
                ij.runScript(conn, in, "ASCII", finalOut, Common.UTF8);
            } catch (UnsupportedEncodingException e) {
                throw new ShouldNeverHappenException(e);
            }
        }
    });
    if (finalOut != out) {
        ByteArrayOutputStream baos = (ByteArrayOutputStream) finalOut;
        String s = new String(baos.toByteArray(), Common.UTF8_CS);
        log.info("Derby script output: " + s);
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) Connection(java.sql.Connection) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ConnectionCallbackVoid(com.serotonin.db.spring.ConnectionCallbackVoid)

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