Search in sources :

Example 16 with ExtendedJdbcTemplate

use of com.serotonin.db.spring.ExtendedJdbcTemplate in project ma-core-public by infiniteautomation.

the class DataPointDao method savePointHierarchy.

public synchronized void savePointHierarchy(final PointFolder root) {
    // Assign ids to the folders.
    final List<Object> params = new ArrayList<>();
    final AtomicInteger folderId = new AtomicInteger(getMaxFolderId(root));
    for (PointFolder sf : root.getSubfolders()) assignFolderIds(sf, 0, folderId, params);
    cachedPointHierarchy = new PointHierarchy(root);
    final ExtendedJdbcTemplate ejt2 = ejt;
    getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            // Dump the hierarchy table.
            ejt2.update("DELETE FROM dataPointHierarchy");
            // Reset the current point folders values in the points.
            ejt2.update("UPDATE dataPoints SET pointFolderId=0");
            // Save the point folders.
            if (folderId.get() > 0) {
                StringBuilder sql = new StringBuilder();
                sql.append("INSERT INTO dataPointHierarchy (id, parentId, name) VALUES ");
                for (int i = 0; i < params.size() / 3; i++) {
                    // three fields per folder
                    if (i > 0)
                        sql.append(",");
                    sql.append("(?,?,?)");
                }
                ejt2.update(sql.toString(), params.toArray(new Object[params.size()]));
            }
            // Save the folder ids for the points.
            savePointsInFolder(root);
            PointHierarchyEventDispatcher.firePointHierarchySaved(root);
        }
    });
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) PointFolder(com.serotonin.m2m2.vo.hierarchy.PointFolder) PointHierarchy(com.serotonin.m2m2.vo.hierarchy.PointHierarchy) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 17 with ExtendedJdbcTemplate

use of com.serotonin.db.spring.ExtendedJdbcTemplate in project ma-core-public by infiniteautomation.

the class DataSourceDao method deleteDataSource.

public void deleteDataSource(final int dataSourceId) {
    DataSourceVO<?> vo = getDataSource(dataSourceId);
    final ExtendedJdbcTemplate ejt2 = ejt;
    DataPointDao.instance.deleteDataPoints(dataSourceId);
    if (vo != null) {
        getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                ejt2.update("DELETE FROM eventHandlersMapping WHERE eventTypeName=? AND eventTypeRef1=?", new Object[] { EventType.EventTypeNames.DATA_SOURCE, dataSourceId });
                ejt2.update("DELETE FROM dataSources WHERE id=?", new Object[] { dataSourceId });
            }
        });
        AuditEventType.raiseDeletedEvent(AuditEventType.TYPE_DATA_SOURCE, vo);
        this.countMonitor.decrement();
    }
}
Also used : ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 18 with ExtendedJdbcTemplate

use of com.serotonin.db.spring.ExtendedJdbcTemplate in project ma-core-public by infiniteautomation.

the class EventDao method purgeAllEvents.

/**
 * Purge all events by truncating the table
 * @return
 */
public int purgeAllEvents() {
    final ExtendedJdbcTemplate ejt2 = ejt;
    int count = getTransactionTemplate().execute(new TransactionCallback<Integer>() {

        @Override
        public Integer doInTransaction(TransactionStatus status) {
            // UserEvents table will be deleted on cascade
            int tot = ejt2.update("delete from events");
            ejt2.update("delete from userComments where commentType=" + UserCommentVO.TYPE_EVENT);
            return tot;
        }
    });
    return count;
}
Also used : ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus)

Example 19 with ExtendedJdbcTemplate

use of com.serotonin.db.spring.ExtendedJdbcTemplate 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 20 with ExtendedJdbcTemplate

use of com.serotonin.db.spring.ExtendedJdbcTemplate in project ma-core-public by infiniteautomation.

the class H2Proxy method runScript.

@Override
public void runScript(String[] script, final OutputStream out) {
    ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate();
    ejt.setDataSource(getDataSource());
    StringBuilder statement = new StringBuilder();
    for (String line : script) {
        // Trim whitespace
        line = line.trim();
        // Skip comments
        if (line.startsWith("--"))
            continue;
        // Replace macros in the line
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "blob", replacement("blob"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "char", replacement("char"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "clob", replacement("clob"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "double", replacement("double"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "identity", replacement("identity"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "int", replacement("int"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "varchar", replacement("varchar"));
        // 
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "ALTER COLUMN", replacement("ALTER COLUMN"));
        // line = com.serotonin.util.StringUtils.replaceMacro(line, "DROP FOREIGN KEY",
        // replacement("DROP FOREIGN KEY"));
        statement.append(line);
        statement.append(" ");
        if (line.endsWith(";")) {
            // Execute the statement
            ejt.execute(statement.toString());
            if (out != null) {
                try {
                    out.write((statement.toString() + "\n").getBytes(Common.UTF8_CS));
                } catch (IOException e) {
                // Don't really care
                }
            }
            statement.delete(0, statement.length() - 1);
        }
    }
}
Also used : ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) IOException(java.io.IOException)

Aggregations

ExtendedJdbcTemplate (com.serotonin.db.spring.ExtendedJdbcTemplate)22 TransactionStatus (org.springframework.transaction.TransactionStatus)12 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)8 DatabaseSchemaDefinition (com.serotonin.m2m2.module.DatabaseSchemaDefinition)3 User (com.serotonin.m2m2.vo.User)3 File (java.io.File)3 DefaultDataPointPropertiesTemplateFactory (com.serotonin.m2m2.vo.template.DefaultDataPointPropertiesTemplateFactory)2 IOException (java.io.IOException)2 SQLException (java.sql.SQLException)2 DataSourceTransactionManager (org.springframework.jdbc.datasource.DataSourceTransactionManager)2 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)1 IMangoLifecycle (com.serotonin.m2m2.IMangoLifecycle)1 CompoundEventDetectorVO (com.serotonin.m2m2.vo.event.CompoundEventDetectorVO)1 PointFolder (com.serotonin.m2m2.vo.hierarchy.PointFolder)1 PointHierarchy (com.serotonin.m2m2.vo.hierarchy.PointHierarchy)1 DirectoryInfo (com.serotonin.util.DirectoryInfo)1 FileNotFoundException (java.io.FileNotFoundException)1 ArrayList (java.util.ArrayList)1 MissingResourceException (java.util.MissingResourceException)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1