diff --git a/WebContent/WEB-INF/applicationContext.xml b/WebContent/WEB-INF/applicationContext.xml
index 3e69cf3c19..abf6de4bfc 100644
--- a/WebContent/WEB-INF/applicationContext.xml
+++ b/WebContent/WEB-INF/applicationContext.xml
@@ -27,6 +27,8 @@
http://www.springframework.org/schema/cache/spring-cache.xsd
">
+
+
@@ -76,12 +78,39 @@
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -168,10 +197,12 @@
-
-
-
-
+
+
+
+
+
+
@@ -187,8 +218,6 @@
-
-
@@ -211,16 +240,119 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
-
diff --git a/src/br/org/scadabr/db/configuration/ConfigurationDB.java b/src/br/org/scadabr/db/configuration/ConfigurationDB.java
index 0154027bc8..69ead72bff 100644
--- a/src/br/org/scadabr/db/configuration/ConfigurationDB.java
+++ b/src/br/org/scadabr/db/configuration/ConfigurationDB.java
@@ -125,6 +125,55 @@ public static void useMysqlDB() {
}
}
+ public static void usePostgresDB() {
+
+ String fileSeparator = System.getProperty("file.separator");
+
+ String path = Common.ctx.getServletContext().getRealPath("");
+
+ boolean win = false;
+
+ File envFile = null;
+
+ if (fileSeparator.equals("\\")) {
+ path = path + "\\" + "WEB-INF" + "\\" + "classes" + "\\";
+ envFile = new File(path + "\\" + "env.properties");
+ win = true;
+ }
+
+ if (fileSeparator.equals("/")) {
+ path = path + "/" + "WEB-INF" + "/" + "classes" + "/";
+ envFile = new File(path + "/" + "env.properties");
+ }
+
+ if (envFile.exists()) {
+
+ if (win) {
+ File postgresFile = new File(path + "\\" + "env.properties.postgres");
+
+ if (postgresFile.exists()) {
+ try {
+ ConfigurationDB.copy(postgresFile, envFile);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ } else {
+ File postgresFile = new File(path + "/" + "env.properties.postgres");
+
+ if (postgresFile.exists()) {
+ try {
+ ConfigurationDB.copy(postgresFile, envFile);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ }
+ }
+
public static void useMssqlDB() {
}
diff --git a/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java b/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java
index 2f21e4d07d..a647318868 100644
--- a/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java
+++ b/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java
@@ -9,7 +9,9 @@
import com.serotonin.json.JsonReader;
import com.serotonin.json.JsonRemoteEntity;
import com.serotonin.json.JsonSerializable;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
+import org.scada_lts.web.beans.ApplicationBeans;
@JsonRemoteEntity
public class SystemSettingsJSONWrapper implements JsonSerializable {
@@ -22,15 +24,14 @@ public void jsonSerialize(Map map) {
Set> defaultValues = SystemSettingsDAO.DEFAULT_VALUES
.entrySet();
- SystemSettingsDAO dao = new SystemSettingsDAO();
for (Entry entry : defaultValues) {
if (entry.getValue() instanceof Integer) {
- map.put(entry.getKey(), dao.getIntValue(entry.getKey()));
+ map.put(entry.getKey(), SystemSettingsDAO.getIntValue(entry.getKey()));
} else if (entry.getValue() instanceof Boolean) {
- map.put(entry.getKey(), dao.getBooleanValue(entry.getKey()));
+ map.put(entry.getKey(), SystemSettingsDAO.getBooleanValue(entry.getKey()));
} else if (entry.getValue() instanceof String) {
- map.put(entry.getKey(), dao.getValue(entry.getKey()));
+ map.put(entry.getKey(), SystemSettingsDAO.getValue(entry.getKey()));
}
}
@@ -42,19 +43,19 @@ public void jsonDeserialize(JsonReader reader, JsonObject json)
Set> defaultValues = SystemSettingsDAO.DEFAULT_VALUES
.entrySet();
- SystemSettingsDAO dao = new SystemSettingsDAO();
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
for (Entry entry : defaultValues) {
String key = entry.getKey();
if (entry.getValue() instanceof Integer) {
- dao.setIntValue(key, json.getInt(key));
+ systemSettingsDAO.setIntValue(key, json.getInt(key));
} else if (entry.getValue() instanceof Boolean) {
- dao.setBooleanValue(key, json.getBoolean(key));
+ systemSettingsDAO.setBooleanValue(key, json.getBoolean(key));
} else if (entry.getValue() instanceof String) {
- dao.setValue(key, json.getString(key));
+ systemSettingsDAO.setValue(key, json.getString(key));
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/com/serotonin/mango/MangoContextListener.java b/src/com/serotonin/mango/MangoContextListener.java
index 08a372f303..8249f650c9 100644
--- a/src/com/serotonin/mango/MangoContextListener.java
+++ b/src/com/serotonin/mango/MangoContextListener.java
@@ -67,6 +67,7 @@
import org.scada_lts.cache.PointHierarchyCache;
import org.scada_lts.cache.ViewHierarchyCache;
import org.scada_lts.config.ScadaVersion;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
import org.scada_lts.ds.polling.PollingDataSourceUtils;
import org.scada_lts.mango.adapter.MangoScadaConfig;
@@ -155,8 +156,8 @@ private void initialized(ServletContextEvent evt) {
+ knownContextPath + " to " + contextPath
+ ". Are there two instances of Scada-LTS running?");
}
- new SystemSettingsDAO().setValue(
- SystemSettingsDAO.SERVLET_CONTEXT_PATH, ctx.getContextPath());
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setValue(SystemSettingsDAO.SERVLET_CONTEXT_PATH, ctx.getContextPath());
eventManagerInitialize(ctx);
utilitiesInitialize(ctx);
diff --git a/src/com/serotonin/mango/db/DBConvert.java b/src/com/serotonin/mango/db/DBConvert.java
index b40cb5fdd0..03e3a982d5 100644
--- a/src/com/serotonin/mango/db/DBConvert.java
+++ b/src/com/serotonin/mango/db/DBConvert.java
@@ -46,7 +46,7 @@ public void setTarget(DatabaseAccess target) {
}
public void execute() throws SQLException {
- LOG.warn("Running database conversion from " + source.getType().name() + " to " + target.getType().name());
+ LOG.warn("Running database conversion from " + source.getTypeKey() + " to " + target.getTypeKey());
// Create the connections
Connection sourceConn = source.getDataSource().getConnection();
diff --git a/src/com/serotonin/mango/db/DatabaseAccess.java b/src/com/serotonin/mango/db/DatabaseAccess.java
index 1b4bb05065..e3299043d3 100644
--- a/src/com/serotonin/mango/db/DatabaseAccess.java
+++ b/src/com/serotonin/mango/db/DatabaseAccess.java
@@ -13,11 +13,17 @@
*/
package com.serotonin.mango.db;
+import br.org.scadabr.db.configuration.ConfigurationDB;
+
import java.io.File;
+import java.io.InputStream;
import java.io.OutputStream;
+import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
+import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Types;
import java.util.LinkedList;
import java.util.MissingResourceException;
@@ -26,7 +32,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
+import org.scada_lts.web.beans.ApplicationBeans;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.datasource.DataSourceUtils;
@@ -43,51 +51,237 @@
abstract public class DatabaseAccess {
private final static Log log = LogFactory.getLog(DatabaseAccess.class);
+ public static final class StorageStatistics {
+ private final boolean databaseSizeKnown;
+ private final Double databaseSizeMb;
+ private final Long databaseSizeBytes;
+ private final int filedataCount;
+ private final long filedataSizeBytes;
+ private final Double totalSizeMb;
+ private final Long totalSizeBytes;
+
+ private StorageStatistics(boolean databaseSizeKnown, Double databaseSizeMb, Long databaseSizeBytes,
+ int filedataCount, long filedataSizeBytes, Double totalSizeMb, Long totalSizeBytes) {
+ this.databaseSizeKnown = databaseSizeKnown;
+ this.databaseSizeMb = databaseSizeMb;
+ this.databaseSizeBytes = databaseSizeBytes;
+ this.filedataCount = filedataCount;
+ this.filedataSizeBytes = filedataSizeBytes;
+ this.totalSizeMb = totalSizeMb;
+ this.totalSizeBytes = totalSizeBytes;
+ }
+
+ public static StorageStatistics fromFilesystem(long databaseSizeBytes, int filedataCount, long filedataSizeBytes) {
+ return new StorageStatistics(
+ true,
+ null,
+ databaseSizeBytes,
+ filedataCount,
+ filedataSizeBytes,
+ null,
+ databaseSizeBytes + filedataSizeBytes
+ );
+ }
+
+ public static StorageStatistics fromDatabaseSizeMb(double databaseSizeMb) {
+ return new StorageStatistics(
+ true,
+ databaseSizeMb,
+ null,
+ 0,
+ 0,
+ databaseSizeMb,
+ null
+ );
+ }
+
+ public static StorageStatistics unknownDatabaseSize(int filedataCount, long filedataSizeBytes, long totalSizeBytes) {
+ return new StorageStatistics(
+ false,
+ null,
+ null,
+ filedataCount,
+ filedataSizeBytes,
+ null,
+ totalSizeBytes
+ );
+ }
+
+ public boolean isDatabaseSizeKnown() {
+ return databaseSizeKnown;
+ }
+
+ public Double getDatabaseSizeMb() {
+ return databaseSizeMb;
+ }
+
+ public Long getDatabaseSizeBytes() {
+ return databaseSizeBytes;
+ }
+
+ public int getFiledataCount() {
+ return filedataCount;
+ }
+
+ public long getFiledataSizeBytes() {
+ return filedataSizeBytes;
+ }
+
+ public Double getTotalSizeMb() {
+ return totalSizeMb;
+ }
+
+ public Long getTotalSizeBytes() {
+ return totalSizeBytes;
+ }
+ }
+
public enum DatabaseType {
DERBY {
@Override
DatabaseAccess getImpl() {
return new DerbyAccess();
}
+
+ @Override
+ public void applyConfiguration() {
+ ConfigurationDB.useDerbyDB();
+ }
},
MSSQL {
@Override
DatabaseAccess getImpl() {
return new MSSQLAccess();
}
+
+ @Override
+ public void applyConfiguration() {
+ ConfigurationDB.useMssqlDB();
+ }
},
MYSQL {
@Override
DatabaseAccess getImpl() {
return new MySQLAccess();
}
+
+ @Override
+ public InputStream getBinaryStream(ResultSet rs, int columnIndex) throws SQLException {
+ Blob blob = rs.getBlob(columnIndex);
+ return blob == null ? null : blob.getBinaryStream();
+ }
+
+ @Override
+ public InputStream getBinaryStream(ResultSet rs, String columnLabel) throws SQLException {
+ Blob blob = rs.getBlob(columnLabel);
+ return blob == null ? null : blob.getBinaryStream();
+ }
+
+ @Override
+ public StorageStatistics getStorageStatistics(long dbSizeBytes, int filedataCount, long filedataSizeBytes,
+ java.util.function.DoubleSupplier databaseSizeSupplier) {
+ double size = databaseSizeSupplier.getAsDouble();
+ if (size >= 0) {
+ return StorageStatistics.fromDatabaseSizeMb(size);
+ }
+ return StorageStatistics.unknownDatabaseSize(filedataCount, filedataSizeBytes, dbSizeBytes + filedataSizeBytes);
+ }
+
+ @Override
+ public void applyConfiguration() {
+ ConfigurationDB.useMysqlDB();
+ }
},
POSTGRES {
@Override
DatabaseAccess getImpl() {
return new PostgreSQLAccess();
}
+
+ @Override
+ public int getBinarySqlType() {
+ return Types.BINARY;
+ }
+
+ @Override
+ public StorageStatistics getStorageStatistics(long dbSizeBytes, int filedataCount, long filedataSizeBytes,
+ java.util.function.DoubleSupplier databaseSizeSupplier) {
+ double size = databaseSizeSupplier.getAsDouble();
+ if (size >= 0) {
+ return StorageStatistics.fromDatabaseSizeMb(size);
+ }
+ return StorageStatistics.unknownDatabaseSize(filedataCount, filedataSizeBytes, dbSizeBytes + filedataSizeBytes);
+ }
+
+ @Override
+ public void applyConfiguration() {
+ ConfigurationDB.usePostgresDB();
+ }
},
ORACLE11G {
@Override
DatabaseAccess getImpl() {
return new Oracle11GAccess();
}
+
+ @Override
+ public void applyConfiguration() {
+ ConfigurationDB.useOracle11gDB();
+ }
};
+ public String getKey() {
+ return name().toLowerCase();
+ }
+
+ public static DatabaseType from(String dbType) {
+ if (dbType == null) {
+ throw new IllegalArgumentException("Unknown database type: null");
+ }
+
+ String normalized = dbType.trim().toLowerCase();
+ switch (normalized) {
+ case "postgresql":
+ case "pgsql":
+ case "pg":
+ return POSTGRES;
+ case "mssqlserver":
+ case "mssql":
+ return MSSQL;
+ case "mysqlserver":
+ case "mysql":
+ return MYSQL;
+ default:
+ return DatabaseType.valueOf(normalized.toUpperCase());
+ }
+ }
+
+ public InputStream getBinaryStream(ResultSet rs, int columnIndex) throws SQLException {
+ return rs.getBinaryStream(columnIndex);
+ }
+
+ public InputStream getBinaryStream(ResultSet rs, String columnLabel) throws SQLException {
+ return rs.getBinaryStream(columnLabel);
+ }
+
+ public int getBinarySqlType() {
+ return Types.BLOB;
+ }
+
abstract DatabaseAccess getImpl();
+
+ public StorageStatistics getStorageStatistics(long dbSizeBytes, int filedataCount, long filedataSizeBytes,
+ java.util.function.DoubleSupplier databaseSizeSupplier) {
+ return StorageStatistics.fromFilesystem(dbSizeBytes, filedataCount, filedataSizeBytes);
+ }
+
+ public abstract void applyConfiguration();
}
public static DatabaseAccess createDatabaseAccess() {
-
String type = Common.getEnvironmentProfile().getString("db.type",
"derby");
- DatabaseType dt = DatabaseType.valueOf(type.toUpperCase());
-
- if (dt == null)
- throw new IllegalArgumentException("Unknown database type: " + type);
-
- return dt.getImpl();
+ return DatabaseType.from(type).getImpl();
}
public static DatabaseAccess getDatabaseAccess() {
@@ -115,13 +309,11 @@ public void initialize(ServletContext ctx) {
if (!StringUtils.isEmpty(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);
-
- DatabaseAccess sourceAccess = convertType.getImpl();
+ DatabaseAccess sourceAccess = resolveDatabaseAccess(DatabaseType.from(convertTypeStr));
+ if (sourceAccess == this) {
+ throw new IllegalStateException(
+ "convert.db.type must be different from db.type.");
+ }
sourceAccess.initializeImpl("convert.");
DBConvert convert = new DBConvert();
@@ -150,7 +342,8 @@ public void initialize(ServletContext ctx) {
new UserDao().saveUser(user);
// Record the current version.
- new SystemSettingsDAO().setValue(
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setValue(
SystemSettingsDAO.DATABASE_SCHEMA_VERSION,
Common.getVersion());
}
@@ -186,6 +379,26 @@ private void initDataSource() {
abstract public DatabaseType getType();
+ public String getTypeKey() {
+ return getType().getKey();
+ }
+
+ public String getIdQuery() {
+ return "SELECT @@identity";
+ }
+
+ public InputStream getBinaryStream(ResultSet rs, int columnIndex) throws SQLException {
+ return getType().getBinaryStream(rs, columnIndex);
+ }
+
+ public InputStream getBinaryStream(ResultSet rs, String columnLabel) throws SQLException {
+ return getType().getBinaryStream(rs, columnLabel);
+ }
+
+ public int getBinarySqlType() {
+ return getType().getBinarySqlType();
+ }
+
abstract public void terminate();
abstract public DataSource getDataSource();
@@ -262,4 +475,13 @@ public PreparedStatement prepareStatement(Connection connection,
return connection.prepareStatement(sql, 1);
}
+ private static DatabaseAccess resolveDatabaseAccess(DatabaseType dbType) {
+ String beanName = "databaseAccess-" + dbType.getKey();
+ DatabaseAccess access = ApplicationBeans.getBean(beanName, DatabaseAccess.class);
+ if (access == null) {
+ throw new IllegalStateException("DB plugin not found for db.type=" + dbType.getKey()
+ + ". Expected bean '" + beanName + "'.");
+ }
+ return access;
+ }
}
diff --git a/src/com/serotonin/mango/db/DerbyAccess.java b/src/com/serotonin/mango/db/DerbyAccess.java
index 535e7d4c45..5866955c39 100644
--- a/src/com/serotonin/mango/db/DerbyAccess.java
+++ b/src/com/serotonin/mango/db/DerbyAccess.java
@@ -48,7 +48,7 @@
import static org.scada_lts.utils.PathSecureUtils.FileSystemPaths.getAbsoluteResourcePath;
public class DerbyAccess extends DatabaseAccess {
- private final Log log = LogFactory.getLog(DerbyAccess.class);
+ private static final Log log = LogFactory.getLog(DerbyAccess.class);
private static final double LARGEST_POSITIVE = 1.79769E+308;
private static final double SMALLEST_POSITIVE = 2.225E-307;
diff --git a/src/com/serotonin/mango/db/PostgreSQLAccess.java b/src/com/serotonin/mango/db/PostgreSQLAccess.java
index 9d87632a5c..05e3d578df 100644
--- a/src/com/serotonin/mango/db/PostgreSQLAccess.java
+++ b/src/com/serotonin/mango/db/PostgreSQLAccess.java
@@ -18,16 +18,13 @@
*/
package com.serotonin.mango.db;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import java.sql.*;
import javax.servlet.ServletContext;
+import net.bull.javamelody.internal.common.LOG;
import org.apache.commons.dbcp.BasicDataSource;
+import org.flywaydb.core.Flyway;
import org.springframework.dao.DataAccessException;
import com.serotonin.db.spring.ExtendedJdbcTemplate;
@@ -62,8 +59,13 @@ protected String getUrl(String propertyPrefix) {
}
@Override
- public DatabaseAccess.DatabaseType getType() {
- return DatabaseAccess.DatabaseType.POSTGRES;
+ public DatabaseType getType() {
+ return DatabaseType.POSTGRES;
+ }
+
+ @Override
+ public String getIdQuery() {
+ return "SELECT LASTVAL()";
}
@Override
@@ -73,46 +75,68 @@ protected String getDriverClassName() {
@Override
protected boolean newDatabaseCheck(ExtendedJdbcTemplate ejt, ServletContext ctx) {
+
+ boolean schemaExists = true;
+ boolean baselineNotExist = false;
+
+ try {
+ ejt.execute("SELECT count(*) FROM users");
+ LOG.info("schemaExists: " + schemaExists);
+ } catch (DataAccessException e) {
+ schemaExists = false;
+ LOG.info("schemaExists: " + schemaExists);
+ }
+
+ try {
+ ejt.execute("SELECT count(*) FROM schema_version");
+ LOG.info("baselineNotExist: " + baselineNotExist);
+ } catch (DataAccessException e) {
+ baselineNotExist = true;
+ LOG.info("baselineNotExist: " + baselineNotExist);
+ }
+
try {
- //ejt.execute("select count(*) from users");
- Class.forName(getDriverClassName());
- Connection conn = DriverManager.getConnection(Common.getEnvironmentProfile().getString("db.url.public"),
- Common.getEnvironmentProfile().getString("db.username"),
- Common.getEnvironmentProfile().getString("db.password"));
- ResultSet res = conn.createStatement().executeQuery("SELECT 1 from pg_database WHERE datname='scadabr'");
- if (res.next()){
- //se possui registros então é porque a base de dados existe
- conn.close();
- return false;
+ Flyway flyway = null;
+
+ if (schemaExists) {
+ if (baselineNotExist) {
+ flyway = Flyway.configure()
+ .baselineOnMigrate(true)
+ .dataSource(getDataSource())
+ .locations("org.scada_lts.dao.migration.postgres")
+ .table("schema_version")
+ .load();
+
+ flyway.baseline();
+ flyway.migrate();
+ }
+ } else {
+ if (baselineNotExist) {
+ flyway = Flyway.configure()
+ .baselineOnMigrate(true)
+ .dataSource(getDataSource())
+ .locations("org.scada_lts.dao.migration.postgres")
+ .table("schema_version")
+ .load();
+
+ flyway.migrate();
+ }
}
- else{
- //como a base de dados não existe então ela deverá ser criada
- conn.createStatement().executeUpdate("CREATE DATABASE scadabr WITH OWNER = postgres ENCODING = 'UTF8'");
- conn.close();
- //uma vez com o banco de dados criado procederemos com a criação das tabelas
- conn = DriverManager.getConnection(Common.getEnvironmentProfile().getString("db.url"),
- Common.getEnvironmentProfile().getString("db.username"),
- Common.getEnvironmentProfile().getString("db.password"));
- createSchema("/WEB-INF/db/createTables-postgresql.sql", ctx);
- conn.close();
- return true;
+
+ if (flyway == null) {
+ flyway = Flyway.configure()
+ .dataSource(getDataSource())
+ .locations("org.scada_lts.dao.migration.postgres")
+ .table("schema_version")
+ .load();
}
- } catch (SQLException ex) {
- //Logger.getLogger(PostgreSQLAccess.class.getName()).log(Level.SEVERE, null, ex);
- } catch (ClassNotFoundException ex) {
- Logger.getLogger(PostgreSQLAccess.class.getName()).log(Level.SEVERE, null, ex);
- }
- catch (DataAccessException e) {
-// if (e.getCause() instanceof SQLException) {
-// SQLException se = (SQLException) e.getCause();
-// if ("42S02".equals(se.getSQLState())) {
-// // This state means a missing table. Assume that the schema needs to be created.
-// createSchema("/WEB-INF/db/createTables-postgresql.sql");
-// return true;
-// }
-// }
-// throw e;
+
+ flyway.migrate();
+
+ } catch (Exception e) {
+ LOG.warn("Flyway migration failed", e);
}
+
return false;
}
@@ -132,4 +156,12 @@ public double applyBounds(double value) {
public void executeCompress(ExtendedJdbcTemplate ejt) {
// no op
}
+
+ @Override
+ public PreparedStatement prepareStatement(Connection connection, String sql, String generatedKey) throws SQLException {
+ if (!sql.toLowerCase().contains("returning")) {
+ sql += " RETURNING " + generatedKey;
+ }
+ return connection.prepareStatement(sql);
+ }
}
diff --git a/src/com/serotonin/mango/db/dao/DataSourceDao.java b/src/com/serotonin/mango/db/dao/DataSourceDao.java
index 2185e61073..4d87b8b244 100644
--- a/src/com/serotonin/mango/db/dao/DataSourceDao.java
+++ b/src/com/serotonin/mango/db/dao/DataSourceDao.java
@@ -20,7 +20,6 @@
import java.io.InputStream;
import java.io.Serializable;
-import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
@@ -33,7 +32,7 @@
import org.springframework.dao.DataAccessException;
import com.serotonin.db.spring.GenericResultSetExtractor;
-import com.serotonin.mango.Common;
+import com.serotonin.mango.db.DatabaseAccess;
import com.serotonin.mango.vo.dataSource.DataSourceVO;
import com.serotonin.util.SerializationHelper;
@@ -83,19 +82,9 @@ public Serializable extractData(ResultSet rs)
if (!rs.next())
return null;
- InputStream is;
-
- if (Common.getEnvironmentProfile().getString("db.type")
- .equals("postgres")) {
- Blob blob = rs.getBlob(1);
- is = blob.getBinaryStream();
- if (blob == null)
- return null;
- } else {
- is = rs.getBinaryStream(1);
- if (is == null)
- return null;
- }
+ InputStream is = DatabaseAccess.getDatabaseAccess().getBinaryStream(rs, 1);
+ if (is == null)
+ return null;
return (Serializable) SerializationHelper
.readObjectInContext(is);
@@ -108,8 +97,7 @@ public void savePersistentData(int id, Object data) {
"update dataSources set rtdata=? where id=?",
new Object[] { SerializationHelper.writeObject(data), id },
new int[] {
- Common.getEnvironmentProfile().getString("db.type")
- .equals("postgres") ? Types.BINARY : Types.BLOB,
+ DatabaseAccess.getDatabaseAccess().getBinarySqlType(),
Types.INTEGER });
}
}
diff --git a/src/com/serotonin/mango/db/dao/ReportDao.java b/src/com/serotonin/mango/db/dao/ReportDao.java
index de182182f8..cce9c8439e 100644
--- a/src/com/serotonin/mango/db/dao/ReportDao.java
+++ b/src/com/serotonin/mango/db/dao/ReportDao.java
@@ -21,7 +21,7 @@
import java.util.List;
import java.util.ResourceBundle;
-import org.scada_lts.dao.report.ReportInstancePointDAO;
+import org.scada_lts.dao.report.IReportInstancePointDAO;
import org.scada_lts.mango.adapter.MangoReport;
import org.scada_lts.mango.service.ReportService;
@@ -101,7 +101,7 @@ public void saveReportInstance(ReportInstance instance) {
* This method should only be called by the ReportWorkItem.
*/
- public int runReport(final ReportInstance instance, List points, ResourceBundle bundle) {
+ public int runReport(final ReportInstance instance, List points, ResourceBundle bundle) {
return reportService.runReport(instance, points, bundle);
}
diff --git a/src/com/serotonin/mango/db/upgrade/DBUpgrade.java b/src/com/serotonin/mango/db/upgrade/DBUpgrade.java
index bbecff6cdf..de08be9099 100644
--- a/src/com/serotonin/mango/db/upgrade/DBUpgrade.java
+++ b/src/com/serotonin/mango/db/upgrade/DBUpgrade.java
@@ -29,6 +29,7 @@
import com.serotonin.ShouldNeverHappenException;
import com.serotonin.mango.Common;
import com.serotonin.mango.db.DatabaseAccess;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
import com.serotonin.util.StringUtils;
@@ -85,7 +86,8 @@ public static void checkUpgrade() {
LOG.warn("Upgrading instance from " + schemaVersion + " to "
+ upgrade.getNewSchemaVersion());
upgrade.upgrade();
- new SystemSettingsDAO().setValue(
+ ISystemSettingsDAO systemSettingsDAO = org.scada_lts.web.beans.ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setValue(
SystemSettingsDAO.DATABASE_SCHEMA_VERSION,
upgrade.getNewSchemaVersion());
} catch (Exception e) {
@@ -116,7 +118,7 @@ protected void runScript(String[] script, OutputStream out)
protected void runScript(Map scripts,
final OutputStream out) throws Exception {
DatabaseAccess da = Common.ctx.getDatabaseAccess();
- String[] script = scripts.get(da.getType().name());
+ String[] script = scripts.get(da.getTypeKey());
if (script == null)
script = scripts.get(DEFAULT_DATABASE_TYPE);
runScript(script, out);
diff --git a/src/com/serotonin/mango/db/upgrade/Upgrade1_12_4.java b/src/com/serotonin/mango/db/upgrade/Upgrade1_12_4.java
index 4004ccf287..3848bb4314 100644
--- a/src/com/serotonin/mango/db/upgrade/Upgrade1_12_4.java
+++ b/src/com/serotonin/mango/db/upgrade/Upgrade1_12_4.java
@@ -29,6 +29,7 @@
/**
* @author Matthew Lohbihler
*/
+@Deprecated
public class Upgrade1_12_4 extends DBUpgrade {
private final Log log = LogFactory.getLog(getClass());
diff --git a/src/com/serotonin/mango/rt/RuntimeManager.java b/src/com/serotonin/mango/rt/RuntimeManager.java
index e89cfed522..c386ed98e2 100644
--- a/src/com/serotonin/mango/rt/RuntimeManager.java
+++ b/src/com/serotonin/mango/rt/RuntimeManager.java
@@ -37,10 +37,11 @@
import com.serotonin.mango.vo.mailingList.MailingList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import org.scada_lts.dao.PointEventDetectorDAO;
-import org.scada_lts.dao.event.EventDAO;
+import org.scada_lts.dao.IPointEventDetectorDAO;
+import org.scada_lts.dao.event.IEventDAO;
import org.scada_lts.dao.event.ScheduledExecuteInactiveEventDAO;
import org.scada_lts.mango.service.*;
+import org.scada_lts.web.beans.ApplicationBeans;
import org.scada_lts.service.CommunicationChannel;
import org.scada_lts.service.InactiveEventsProvider;
import org.scada_lts.service.ScheduledExecuteInactiveEventService;
@@ -462,7 +463,8 @@ public void saveDataPoint(DataPointVO point) {
if (!ped.getDef().supports(dataType))
// Remove the detector.
peds.remove();
- AuditEventUtils.raiseAuditDetectorEvent(point, ped, new PointEventDetectorDAO());
+ IPointEventDetectorDAO pointEventDetectorDAO = ApplicationBeans.getPointEventDetectorDaoBean();
+ AuditEventUtils.raiseAuditDetectorEvent(point, ped, pointEventDetectorDAO);
}
new DataPointDao().saveDataPoint(point);
@@ -1000,9 +1002,10 @@ private void stopMaintenanceEvent(int id) {
}
private void startSendEmailForInactiveEvent(MailingList mailingList, ScheduledExecuteInactiveEventService inactiveEmailsService) {
+ IEventDAO eventDAO = ApplicationBeans.getEventDaoBean();
CommunicationChannel channel = CommunicationChannel.newEmailChannel(mailingList, new SystemSettingsService());
ScheduledExecuteInactiveEventRT sendEmail = new ScheduledExecuteInactiveEventRT(inactiveEmailsService,
- InactiveEventsProvider.newInstance(new EventDAO(), ScheduledExecuteInactiveEventDAO.getInstance(),
+ InactiveEventsProvider.newInstance(eventDAO, ScheduledExecuteInactiveEventDAO.getInstance(),
channel, 600),
new DataPointService(), new DataSourceService(), 300);
sendEmail.initialize();
@@ -1010,9 +1013,10 @@ private void startSendEmailForInactiveEvent(MailingList mailingList, ScheduledEx
}
private void startSendSmsForInactiveEvent(MailingList mailingList, ScheduledExecuteInactiveEventService inactiveEmailsService) {
+ IEventDAO eventDAO = ApplicationBeans.getEventDaoBean();
CommunicationChannel channel = CommunicationChannel.newSmsChannel(mailingList, new SystemSettingsService());
ScheduledExecuteInactiveEventRT sendSms = new ScheduledExecuteInactiveEventRT(inactiveEmailsService,
- InactiveEventsProvider.newInstance(new EventDAO(), ScheduledExecuteInactiveEventDAO.getInstance(),
+ InactiveEventsProvider.newInstance(eventDAO, ScheduledExecuteInactiveEventDAO.getInstance(),
channel, 600),
new DataPointService(), new DataSourceService(), 300);
sendSms.initialize();
diff --git a/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java b/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java
index 8e594db00f..90a8ab15b9 100644
--- a/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java
+++ b/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java
@@ -29,8 +29,8 @@
import com.serotonin.ShouldNeverHappenException;
import com.serotonin.io.StreamUtils;
-import com.serotonin.mango.Common;
import com.serotonin.mango.DataTypes;
+import com.serotonin.mango.db.DatabaseAccess;
import com.serotonin.mango.rt.dataImage.DataPointRT;
import com.serotonin.mango.rt.dataImage.PointValueTime;
import com.serotonin.mango.rt.dataImage.SetPointSource;
@@ -282,12 +282,7 @@ else if (dataType == DataTypes.NUMERIC)
return new NumericValue(rs.getDouble(fieldName));
else if (dataType == DataTypes.IMAGE) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
- if (Common.getEnvironmentProfile().getString("db.type").equals("postgres")){
- StreamUtils.transfer(rs.getBinaryStream(fieldName),out);
- }
- else{
- StreamUtils.transfer(rs.getBlob(fieldName).getBinaryStream(),out);
- }
+ StreamUtils.transfer(DatabaseAccess.getDatabaseAccess().getBinaryStream(rs, fieldName), out);
return new ImageValue(out.toByteArray(), ImageValue.TYPE_JPG);
} else
throw new ShouldNeverHappenException("What's this?: "
diff --git a/src/com/serotonin/mango/rt/event/type/AuditEventType.java b/src/com/serotonin/mango/rt/event/type/AuditEventType.java
index faea1b4758..25911c7bba 100644
--- a/src/com/serotonin/mango/rt/event/type/AuditEventType.java
+++ b/src/com/serotonin/mango/rt/event/type/AuditEventType.java
@@ -38,6 +38,8 @@
import com.serotonin.mango.vo.event.EventTypeVO;
import com.serotonin.util.StringUtils;
import com.serotonin.web.i18n.LocalizableMessage;
+import org.scada_lts.dao.ISystemSettingsDAO;
+import org.scada_lts.web.beans.ApplicationBeans;
import org.scada_lts.ds.polling.protocol.opcua.vo.OpcUaDataType;
@JsonRemoteEntity
@@ -105,8 +107,8 @@ public static void setEventTypeAlarmLevel(int type, int alarmLevel) {
EventTypeVO et = getEventType(type);
et.setAlarmLevel(alarmLevel);
- SystemSettingsDAO dao = new SystemSettingsDAO();
- dao.setIntValue(AUDIT_SETTINGS_PREFIX + type, alarmLevel);
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setIntValue(AUDIT_SETTINGS_PREFIX + type, alarmLevel);
}
static void raiseAddedEvent(int auditEventTypeId, ChangeComparable> o) {
diff --git a/src/com/serotonin/mango/rt/event/type/AuditEventUtils.java b/src/com/serotonin/mango/rt/event/type/AuditEventUtils.java
index 687865f168..c6ca3f9bfe 100644
--- a/src/com/serotonin/mango/rt/event/type/AuditEventUtils.java
+++ b/src/com/serotonin/mango/rt/event/type/AuditEventUtils.java
@@ -7,7 +7,7 @@
import com.serotonin.mango.vo.event.PointEventDetectorVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.scada_lts.dao.PointEventDetectorDAO;
+import org.scada_lts.dao.IPointEventDetectorDAO;
import java.util.List;
import java.util.Optional;
@@ -51,7 +51,7 @@ public static void raiseDeletedEvent(int auditEventTypeId, ChangeComparable> o
}
}
- public static void raiseAuditDetectorEvent(DataPointVO point, PointEventDetectorVO ped, PointEventDetectorDAO detectorDAO) {
+ public static void raiseAuditDetectorEvent(DataPointVO point, PointEventDetectorVO ped, IPointEventDetectorDAO detectorDAO) {
try {
List peds = detectorDAO.getPointEventDetectors(point);
getPointEventDetector(peds, ped).map(fromPed -> {
diff --git a/src/com/serotonin/mango/rt/event/type/SystemEventType.java b/src/com/serotonin/mango/rt/event/type/SystemEventType.java
index 737b9908e5..23d9cfe425 100644
--- a/src/com/serotonin/mango/rt/event/type/SystemEventType.java
+++ b/src/com/serotonin/mango/rt/event/type/SystemEventType.java
@@ -31,7 +31,9 @@
import com.serotonin.mango.util.LoggingUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
+import org.scada_lts.web.beans.ApplicationBeans;
import com.serotonin.mango.rt.event.AlarmLevels;
import com.serotonin.mango.util.ExportCodes;
import com.serotonin.mango.vo.event.EventTypeVO;
@@ -144,8 +146,8 @@ public static void setEventTypeAlarmLevel(int type, int alarmLevel) {
if(et != null) {
et.setAlarmLevel(alarmLevel);
- SystemSettingsDAO dao = new SystemSettingsDAO();
- dao.setIntValue(SYSTEM_SETTINGS_PREFIX + type, alarmLevel);
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setIntValue(SYSTEM_SETTINGS_PREFIX + type, alarmLevel);
} else {
LOG.warn(LoggingUtils.eventTypeInfo(type, alarmLevel));
}
diff --git a/src/com/serotonin/mango/rt/maint/work/ReportWorkItem.java b/src/com/serotonin/mango/rt/maint/work/ReportWorkItem.java
index 6211de6b57..eda3faea0d 100644
--- a/src/com/serotonin/mango/rt/maint/work/ReportWorkItem.java
+++ b/src/com/serotonin/mango/rt/maint/work/ReportWorkItem.java
@@ -53,7 +53,7 @@
import com.serotonin.util.ColorUtils;
import com.serotonin.util.StringUtils;
import com.serotonin.web.i18n.LocalizableMessage;
-import org.scada_lts.dao.report.ReportInstancePointDAO;
+import org.scada_lts.dao.report.IReportInstancePointDAO;
import org.scada_lts.mango.service.SystemSettingsService;
import static com.serotonin.mango.util.LoggingUtils.*;
@@ -116,7 +116,7 @@ public void work() {
// Create a list of DataPointVOs to which the user has permission.
DataPointDao dataPointDao = new DataPointDao();
- List points = new ArrayList(
+ List points = new ArrayList(
reportConfig.getPoints().size());
for (ReportPointVO reportPoint : reportConfig.getPoints()) {
DataPointVO point = dataPointDao.getDataPoint(reportPoint
@@ -134,7 +134,7 @@ public void work() {
// validated on save, so just let it go
// as null.
}
- points.add(new ReportInstancePointDAO.PointInfo(point, colour, reportPoint
+ points.add(new IReportInstancePointDAO.PointInfo(point, colour, reportPoint
.isConsolidatedChart()));
}
}
diff --git a/src/com/serotonin/mango/util/freemarker/MangoEmailContent.java b/src/com/serotonin/mango/util/freemarker/MangoEmailContent.java
index d50cd55962..fdcaa94a7a 100644
--- a/src/com/serotonin/mango/util/freemarker/MangoEmailContent.java
+++ b/src/com/serotonin/mango/util/freemarker/MangoEmailContent.java
@@ -14,10 +14,8 @@ public class MangoEmailContent extends TemplateEmailContent {
public static final int CONTENT_TYPE_HTML = 1;
public static final int CONTENT_TYPE_TEXT = 2;
- private static final SystemSettingsDAO SYSTEM_SETTINGS_DAO = new SystemSettingsDAO();
-
public MangoEmailContent(String templateName, Object model, String encoding) throws TemplateException, IOException {
- this(templateName, model, encoding, SYSTEM_SETTINGS_DAO.getIntValue(SystemSettingsDAO.EMAIL_CONTENT_TYPE));
+ this(templateName, model, encoding, SystemSettingsDAO.getIntValue(SystemSettingsDAO.EMAIL_CONTENT_TYPE));
}
private MangoEmailContent(String templateName, Object model, String encoding, int type) throws TemplateException,
diff --git a/src/com/serotonin/mango/vo/User.java b/src/com/serotonin/mango/vo/User.java
index 1a1588ad95..61821a56f0 100644
--- a/src/com/serotonin/mango/vo/User.java
+++ b/src/com/serotonin/mango/vo/User.java
@@ -50,7 +50,7 @@
import com.serotonin.util.StringUtils;
import com.serotonin.web.dwr.DwrResponseI18n;
import com.serotonin.web.i18n.LocalizableMessage;
-import org.scada_lts.dao.UsersProfileDAO;
+import org.scada_lts.dao.IUsersProfileDAO;
import org.scada_lts.mango.service.UsersProfileService;
import org.scada_lts.web.beans.ApplicationBeans;
@@ -587,7 +587,7 @@ public void jsonDeserializePermissions(JsonReader reader, JsonObject json)
}
}
- UsersProfileDAO usersProfileDAO = new UsersProfileDAO();
+ IUsersProfileDAO usersProfileDAO = ApplicationBeans.getUsersProfileDaoBean();
String userProfileXid = json.getString("userProfileXid");
Integer userProfileId = json.getInt("userProfile");
if (userProfileXid != null && !userProfileXid.isEmpty()) {
diff --git a/src/com/serotonin/mango/vo/report/ReportPointVO.java b/src/com/serotonin/mango/vo/report/ReportPointVO.java
index 6236906bc0..8a7bee343f 100644
--- a/src/com/serotonin/mango/vo/report/ReportPointVO.java
+++ b/src/com/serotonin/mango/vo/report/ReportPointVO.java
@@ -23,6 +23,7 @@
public class ReportPointVO implements Serializable, JsonSerializable {
private int pointId;
+ @JsonRemoteProperty
private String pointXid;
@JsonRemoteProperty
private String colour;
@@ -34,6 +35,7 @@ public static ReportPointVO newInstance(HashMap dp) {
reportPointVO.setPointId((Integer) dp.get("pointId"));
reportPointVO.setColour((String) dp.get("colour"));
reportPointVO.setConsolidatedChart((Boolean) dp.get("consolidatedChart"));
+ reportPointVO.setPointXid((String) dp.get("pointXid"));
return reportPointVO;
}
diff --git a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java
index 2844271da9..7e2ca59e7a 100644
--- a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java
+++ b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java
@@ -3181,4 +3181,4 @@ public DwrResponseI18n validateAndSaveDataPoint(DataPointVO dp) {
return response;
}
-}
\ No newline at end of file
+}
diff --git a/src/com/serotonin/mango/web/dwr/EmportDwr.java b/src/com/serotonin/mango/web/dwr/EmportDwr.java
index fefc49f77e..0f901a1fe2 100644
--- a/src/com/serotonin/mango/web/dwr/EmportDwr.java
+++ b/src/com/serotonin/mango/web/dwr/EmportDwr.java
@@ -49,7 +49,7 @@
import com.serotonin.mango.db.dao.ScheduledEventDao;
import com.serotonin.mango.vo.event.PointEventDetectorVO;
import org.scada_lts.dao.PointEventDetectorDAO;
-import org.scada_lts.dao.SystemSettingsDAO;
+import org.scada_lts.dao.ISystemSettingsDAO;
import com.serotonin.mango.db.dao.UserDao;
import com.serotonin.mango.db.dao.WatchListDao;
import com.serotonin.mango.rt.RuntimeManager;
@@ -112,7 +112,7 @@ public String createExportData(int prettyIndent, boolean graphicalViews,
public static String exportJSON(String xid){
Map data = new LinkedHashMap();
DataPointVO dataPoints = new DataPointDao().getDataPointByXid(xid);
- List detectors = new PointEventDetectorDAO().getPointEventDetectors(dataPoints);
+ List detectors = ApplicationBeans.getPointEventDetectorDaoBean().getPointEventDetectors(dataPoints);
dataPoints.setEventDetectors(detectors);
data.put(DATA_POINTS, dataPoints == null?"In the database there is no data point with given xid "+xid:dataPoints);
JsonWriter writer = new JsonWriter();
@@ -132,7 +132,7 @@ public static Map exportDataPointBy(String xid) {
if(dataPoint == null) {
data.put(DATA_POINTS, "In the database there is no data point with given xid ");
} else {
- List detectors = new PointEventDetectorDAO().getPointEventDetectors(dataPoint);
+ List detectors = ApplicationBeans.getPointEventDetectorDaoBean().getPointEventDetectors(dataPoint);
dataPoint.setEventDetectors(detectors);
data.put(DATA_POINTS, dataPoint);
}
@@ -309,7 +309,8 @@ public boolean loadProject() {
try {
Permissions.ensureAdmin(user);
stopRunningDataSources();
- new SystemSettingsDAO().resetDataBase();
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.resetDataBase();
importer.importProject();
} catch (Exception e) {
e.printStackTrace();
@@ -334,4 +335,4 @@ private void stopRunningDataSources() {
}
}
-}
\ No newline at end of file
+}
diff --git a/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java b/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java
index 70fa064ec7..a43f2dbc90 100644
--- a/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java
+++ b/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java
@@ -23,9 +23,11 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.serotonin.InvalidArgumentException;
import com.serotonin.mango.Common;
+import com.serotonin.mango.db.DatabaseAccess;
import com.serotonin.mango.db.dao.DataPointDao;
import com.serotonin.mango.web.email.IMsgSubjectContent;
import com.serotonin.mango.web.mvc.controller.ScadaLocaleUtils;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
import com.serotonin.mango.rt.event.type.AuditEventType;
import com.serotonin.mango.rt.event.type.SystemEventType;
@@ -44,6 +46,7 @@
import org.scada_lts.mango.service.EventService;
import org.scada_lts.mango.service.SystemSettingsService;
import org.scada_lts.utils.ColorUtils;
+import org.scada_lts.web.beans.ApplicationBeans;
import org.scada_lts.web.mvc.api.AggregateSettings;
import org.scada_lts.web.mvc.api.json.JsonSettingsHttp;
import org.scada_lts.web.mvc.api.json.JsonSettingsScadaConfig;
@@ -228,28 +231,39 @@ public Map getDatabaseSize() {
DirectoryInfo dbInfo = DirectoryUtils
.getDirectorySize(dataDirectory);
dbSize = dbInfo.getSize();
- data.put("databaseSize", DirectoryUtils.bytesDescription(dbSize));
- } else
- data.put("databaseSize", "(" + getMessage("common.unknown") + ")");
+ }
// Filedata data
DirectoryInfo fileDatainfo = DirectoryUtils.getDirectorySize(new File(
Common.getFiledataPath()));
long filedataSize = fileDatainfo.getSize();
- data.put("filedataCount", fileDatainfo.getCount());
- data.put("filedataSize", DirectoryUtils.bytesDescription(filedataSize));
-
- data.put("totalSize",
- DirectoryUtils.bytesDescription(dbSize + filedataSize));
-
- if (checkTypeDB().equals("mysql")) {
- double size = new SystemSettingsDAO().getDataBaseSize();
- data.put("databaseSize", size + " MB");
- data.put("filedataCount", 0);
- data.put("filedataSize", 0);
- data.put("totalSize", size + " MB");
- data.put("filedataCount", 0);
- data.put("filedataCount", 0);
+
+
+ DatabaseAccess.DatabaseType dbType = resolveDatabaseType();
+ DatabaseAccess.StorageStatistics storageStatistics = dbType.getStorageStatistics(
+ dbSize,
+ fileDatainfo.getCount(),
+ filedataSize,
+ () -> ApplicationBeans.getSystemSettingsDaoBean().getDatabaseSize()
+ );
+
+ if (storageStatistics.isDatabaseSizeKnown()) {
+ if (storageStatistics.getDatabaseSizeMb() != null) {
+ data.put("databaseSize", storageStatistics.getDatabaseSizeMb() + " MB");
+ } else if (storageStatistics.getDatabaseSizeBytes() != null) {
+ data.put("databaseSize", DirectoryUtils.bytesDescription(storageStatistics.getDatabaseSizeBytes()));
+ }
+ } else {
+ data.put("databaseSize", "(" + getMessage("common.unknown") + ")");
+ }
+
+ data.put("filedataCount", storageStatistics.getFiledataCount());
+ data.put("filedataSize", DirectoryUtils.bytesDescription(storageStatistics.getFiledataSizeBytes()));
+
+ if (storageStatistics.getTotalSizeMb() != null) {
+ data.put("totalSize", storageStatistics.getTotalSizeMb() + " MB");
+ } else if (storageStatistics.getTotalSizeBytes() != null) {
+ data.put("totalSize", DirectoryUtils.bytesDescription(storageStatistics.getTotalSizeBytes()));
}
// Point history counts.
@@ -272,19 +286,19 @@ public void saveEmailSettings(String host, int port, String from,
String name, boolean auth, String username, String password,
boolean tls, int contentType) {
Permissions.ensureAdmin();
- SystemSettingsDAO SystemSettingsDAO = new SystemSettingsDAO();
- SystemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_SMTP_HOST, host);
- SystemSettingsDAO.setIntValue(SystemSettingsDAO.EMAIL_SMTP_PORT, port);
- SystemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_FROM_ADDRESS, from);
- SystemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_FROM_NAME, name);
- SystemSettingsDAO.setBooleanValue(
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_SMTP_HOST, host);
+ systemSettingsDAO.setIntValue(SystemSettingsDAO.EMAIL_SMTP_PORT, port);
+ systemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_FROM_ADDRESS, from);
+ systemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_FROM_NAME, name);
+ systemSettingsDAO.setBooleanValue(
SystemSettingsDAO.EMAIL_AUTHORIZATION, auth);
- SystemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_SMTP_USERNAME,
+ systemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_SMTP_USERNAME,
username);
- SystemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_SMTP_PASSWORD,
+ systemSettingsDAO.setValue(SystemSettingsDAO.EMAIL_SMTP_PASSWORD,
password);
- SystemSettingsDAO.setBooleanValue(SystemSettingsDAO.EMAIL_TLS, tls);
- SystemSettingsDAO.setIntValue(SystemSettingsDAO.EMAIL_CONTENT_TYPE,
+ systemSettingsDAO.setBooleanValue(SystemSettingsDAO.EMAIL_TLS, tls);
+ systemSettingsDAO.setIntValue(SystemSettingsDAO.EMAIL_CONTENT_TYPE,
contentType);
}
@@ -395,7 +409,7 @@ public void saveDataRetentionSettings(int eventPurgePeriodType,
int futureDateLimitPeriodType, int futureDateLimitPeriods,
int defaultPurgePeriod, int defaultPurgePeriodType, int valuesLimitForPurge) {
Permissions.ensureAdmin();
- SystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO();
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
systemSettingsDAO
.setIntValue(SystemSettingsDAO.EVENT_PURGE_PERIOD_TYPE,
eventPurgePeriodType);
@@ -457,14 +471,14 @@ public DwrResponseI18n saveColourSettings(String chartBackgroundColour,
}
if (!response.getHasMessages()) {
- SystemSettingsDAO SystemSettingsDAO = new SystemSettingsDAO();
- SystemSettingsDAO.setValue(
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setValue(
SystemSettingsDAO.CHART_BACKGROUND_COLOUR,
chartBackgroundColour);
- SystemSettingsDAO.setValue(
+ systemSettingsDAO.setValue(
SystemSettingsDAO.PLOT_BACKGROUND_COLOUR,
plotBackgroundColour);
- SystemSettingsDAO.setValue(SystemSettingsDAO.PLOT_GRIDLINE_COLOUR,
+ systemSettingsDAO.setValue(SystemSettingsDAO.PLOT_GRIDLINE_COLOUR,
plotGridlineColour);
}
@@ -475,7 +489,7 @@ public DwrResponseI18n saveColourSettings(String chartBackgroundColour,
public void saveInfoSettings(String newVersionNotificationLevel,
String instanceDescription,String topDescriptionPrefix, String topDescription) {
Permissions.ensureAdmin();
- SystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO();
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
systemSettingsDAO.setValue(
SystemSettingsDAO.NEW_VERSION_NOTIFICATION_LEVEL,
newVersionNotificationLevel);
@@ -539,14 +553,39 @@ public void useMysqlDB() {
}
+ public void usePostgresDB() {
+ Permissions.ensureAdmin();
+ ConfigurationDB.usePostgresDB();
+ }
+
+
public void useMssqlDB() {
Permissions.ensureAdmin();
ConfigurationDB.useMssqlDB();
}
+ public void useOracle11gDB() {
+ Permissions.ensureAdmin();
+ ConfigurationDB.useOracle11gDB();
+ }
+
+
+ private DatabaseAccess.DatabaseType resolveDatabaseType() {
+ try {
+ DatabaseAccess databaseAccess = DatabaseAccess.getDatabaseAccess();
+ if (databaseAccess != null) {
+ return databaseAccess.getType();
+ }
+ } catch (Exception ignore) {
+ // fallback to env.properties
+ }
+ return DatabaseAccess.DatabaseType.from(Common.getEnvironmentProfile().getString("db.type", "mysql"));
+ }
+
+
public String checkTypeDB() {
- return Common.getEnvironmentProfile().getString("db.type", "derby");
+ return resolveDatabaseType().getKey();
}
diff --git a/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java b/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java
index 974e9faf9f..f4a3065be7 100644
--- a/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java
+++ b/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java
@@ -9,7 +9,9 @@
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
+import org.scada_lts.dao.ISystemSettingsDAO;
import org.scada_lts.dao.SystemSettingsDAO;
+import org.scada_lts.web.beans.ApplicationBeans;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
@@ -79,7 +81,8 @@ public static void setSystemLanguage(String language) {
if (locale == null)
throw new IllegalArgumentException(
"Locale for given language not found: " + language);
- new SystemSettingsDAO().setValue(SystemSettingsDAO.LANGUAGE, language);
+ ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean();
+ systemSettingsDAO.setValue(SystemSettingsDAO.LANGUAGE, language);
}
public static List getLanguages() {
diff --git a/src/org/scada_lts/cache/PointHierarchyCache.java b/src/org/scada_lts/cache/PointHierarchyCache.java
index 10a831e6ce..d6f1ebab6f 100644
--- a/src/org/scada_lts/cache/PointHierarchyCache.java
+++ b/src/org/scada_lts/cache/PointHierarchyCache.java
@@ -25,8 +25,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.scada_lts.config.ScadaConfig;
-import org.scada_lts.dao.HierarchyDAO;
-import org.scada_lts.dao.pointhierarchy.PointHierarchyDAO;
+import org.scada_lts.dao.IHierarchyDAO;
+import org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO;
import org.scada_lts.dao.model.pointhierarchy.PointHierarchyComparator;
import org.scada_lts.dao.model.pointhierarchy.PointHierarchyDataSource;
import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode;
@@ -99,12 +99,14 @@ public void updateData() throws Exception {
}
cache.clear();
- List lstHierarchy = new HierarchyDAO().getHierarchy();
+ IHierarchyDAO hierarchyDAO = ApplicationBeans.getHierarchyDAOBean();
+ List lstHierarchy = hierarchyDAO.getHierarchy();
for (PointHierarchyNode ph : lstHierarchy) {
addFolder(ph);
}
- List lstPointHierarchy = new PointHierarchyDAO().getPointsHierarchy();
+ IPointHierarchyDAO pointHierarchyDAO = ApplicationBeans.getPointHierarchyDaoBean();
+ List lstPointHierarchy = pointHierarchyDAO.getPointsHierarchy();
Collections.sort(lstPointHierarchy, PointHierarchyComparator.getInst());
for (PointHierarchyNode ph : lstPointHierarchy) {
diff --git a/src/org/scada_lts/cache/ViewHierarchyCache.java b/src/org/scada_lts/cache/ViewHierarchyCache.java
index 5082764390..87c7cf62c1 100644
--- a/src/org/scada_lts/cache/ViewHierarchyCache.java
+++ b/src/org/scada_lts/cache/ViewHierarchyCache.java
@@ -21,7 +21,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.scada_lts.dao.model.viewshierarchy.ViewHierarchyNode;
import org.scada_lts.service.ViewHierarchyService;
import org.scada_lts.service.model.ViewHierarchyJSON;
@@ -45,7 +44,9 @@ private ViewHierarchyCache() {
private void initial() {
LOG.info("Initial ViewHierarchyCache");
- cache = new ViewHierarchyService().getAll();
+ ViewHierarchyService service = new ViewHierarchyService();
+
+ cache = service.getAll();
}
public static ViewHierarchyCache getInstance() {
@@ -62,7 +63,7 @@ public List getAll() {
}
public void refresh() {
- cache = new ViewHierarchyService().getAll();
+ cache = new ViewHierarchyService().getAll();
}
}
diff --git a/src/org/scada_lts/dao/DAO.java b/src/org/scada_lts/dao/DAO.java
index a98526802a..37f37536ee 100644
--- a/src/org/scada_lts/dao/DAO.java
+++ b/src/org/scada_lts/dao/DAO.java
@@ -23,15 +23,13 @@
import javax.sql.DataSource;
+import com.serotonin.mango.db.DatabaseAccess;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.scada_lts.web.beans.ApplicationBeans;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
-import com.serotonin.mango.Common;
-
-
/**
* Data Abstract Object
*
@@ -45,13 +43,18 @@ public class DAO {
private JdbcTemplate jdbcTemplate;
private static DAO instance;
private boolean test =false;
-
+ private static String idQuery;
+
+
private DAO() {
try {
LOG.trace("Create DAO");
DataSource ds = ApplicationBeans.getBean("databaseSource", DataSource.class);
namedParamJdbcTemplate = new NamedParameterJdbcTemplate(ds);
jdbcTemplate = new JdbcTemplate(ds);
+
+ DatabaseAccess databaseAccess = ApplicationBeans.getBean("databaseAccess", DatabaseAccess.class);
+ idQuery = databaseAccess.getIdQuery();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
@@ -62,7 +65,7 @@ private DAO() {
* @return Method queryForObject() can also return "null"
*/
public int getId() {
- return jdbcTemplate.queryForObject("select @@identity", Integer.class);
+ return jdbcTemplate.queryForObject(idQuery, Integer.class);
}
public static DAO getInstance() {
@@ -169,5 +172,5 @@ public boolean isTest() {
public void setTest(boolean test) {
this.test = test;
}
-
+
}
diff --git a/src/org/scada_lts/dao/DataPointDAO.java b/src/org/scada_lts/dao/DataPointDAO.java
index ff878a154b..9a907126d0 100644
--- a/src/org/scada_lts/dao/DataPointDAO.java
+++ b/src/org/scada_lts/dao/DataPointDAO.java
@@ -22,7 +22,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Set;
-import java.util.stream.Collectors;
import com.serotonin.mango.view.ShareUser;
import org.apache.commons.lang3.StringUtils;
@@ -50,7 +49,7 @@
*
* @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu
*/
-public class DataPointDAO {
+public class DataPointDAO implements IDataPointDAO {
private static final Log LOG = LogFactory.getLog(DataPointDAO.class);
@@ -242,6 +241,7 @@ public DataPointVO mapRow(ResultSet resultSet, int rowNum) throws SQLException {
}
}
+ @Override
public DataPointVO getDataPoint(int id) {
if (LOG.isTraceEnabled()) {
@@ -258,6 +258,7 @@ public DataPointVO getDataPoint(int id) {
}
}
+ @Override
public DataPointVO getDataPoint(String xid) {
if (LOG.isTraceEnabled()) {
@@ -274,6 +275,7 @@ public DataPointVO getDataPoint(String xid) {
}
+ @Override
public List getDataPoints() {
if (LOG.isTraceEnabled()) {
@@ -287,6 +289,7 @@ public List getDataPoints() {
}
}
+ @Override
public List filtered(String filter, Object[] argsFilter, long limit) {
String myLimit="";
Object[] args;
@@ -301,6 +304,7 @@ public List filtered(String filter, Object[] argsFilter, long limit
}
+ @Override
public List getDataPoints(int dataSourceId) {
if (LOG.isTraceEnabled()) {
@@ -327,6 +331,7 @@ public List getDataPointByKeyword(String[] keywords) {
return DAO.getInstance().getJdbcTemp().query(templateSelectWhereSearch, new DataPointRowMapper(), args.toArray());
}
+ @Override
public List getPlcDataPoints(int dataSourceId) {
String templateSelectPlcWhereId = DATA_POINT_SELECT_PLC + " where (dp." + COLUMN_NAME_DATA_SOURCE_ID + "=? AND dp.plcAlarmLevel>0)";
@@ -335,6 +340,7 @@ public List getPlcDataPoints(int dataSourceId) {
}
+ @Override
public List getDataPointsIds(int dataSourceId) {
if (LOG.isTraceEnabled()) {
@@ -344,7 +350,8 @@ public List getDataPointsIds(int dataSourceId) {
return DAO.getInstance().getJdbcTemp().queryForList(DATA_POINT_SELECT_ID, new Object[] {dataSourceId}, Integer.class);
}
- @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class)
+ @Override
public int insert(final DataPointVO dataPoint) {
if (LOG.isTraceEnabled()) {
@@ -380,6 +387,7 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S
* @param entity Object to create
* @return DataPointVO entity with unique ID number
*/
+ @Override
public DataPointVO create(DataPointVO entity) {
KeyHolder keyHolder = new GeneratedKeyHolder();
DAO.getInstance().getJdbcTemp().update(connection -> {
@@ -397,11 +405,13 @@ public DataPointVO create(DataPointVO entity) {
return entity;
}
+ @Override
public DataPointVO getById(int id) throws EmptyResultDataAccessException {
return getDataPoint(id);
}
- @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class)
+ @Override
public int update(DataPointVO dataPoint) {
if (LOG.isTraceEnabled()) {
@@ -424,7 +434,8 @@ public int update(DataPointVO dataPoint) {
}
}
- @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class)
+ @Override
public int delete(int id) {
if (LOG.isTraceEnabled()) {
@@ -444,7 +455,8 @@ public int delete(int id) {
}
}
- @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class)
+ @Override
public void deleteWithIn(String dataPointIdList) {
if (LOG.isTraceEnabled()) {
@@ -462,7 +474,8 @@ public void deleteWithIn(String dataPointIdList) {
DAO.getInstance().getJdbcTemp().update(queryBuilder.toString(), (Object[]) parameters);
}
- @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class)
+ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class)
+ @Override
public void deleteEventHandler(String dataPointIdList) {
if (LOG.isTraceEnabled()) {
@@ -496,12 +509,14 @@ public List selectDataPointIdentifiersWithAccess(int user
.build());
}
+ @Override
public List selectDataPointsWithAccess(int userId, int profileId) {
return DAO.getInstance().getJdbcTemp().query(DATA_POINT_SELECT + " where " + DATA_POINT_FILTERED_BASE_ON_USER_ID_USERS_PROFILE_ID_ORDER_BY_DP_NAME,
new Object[] { userId, ShareUser.ACCESS_NONE, profileId ,ShareUser.ACCESS_NONE, userId, profileId },
new DataPointRowMapper());
}
+ @Override
public List selectDataPointIdentifiersWithAccess(int userId, int profileId) {
return DAO.getInstance().getJdbcTemp().query(DATA_POINT_IDENTIFIER_SELECT + " where " + DATA_POINT_FILTERED_BASE_ON_USER_ID_USERS_PROFILE_ID_ORDER_BY_DP_NAME,
new Object[] { userId, ShareUser.ACCESS_NONE, profileId, ShareUser.ACCESS_NONE, userId, profileId },
@@ -512,6 +527,7 @@ public List selectDataPointIdentifiersWithAccess(int user
.build());
}
+ @Override
public List findIdentifiers() {
ScadaObjectIdentifierRowMapper mapper = new ScadaObjectIdentifierRowMapper.Builder()
.nameColumnName(COLUMN_NAME_DATAPOINT_NAME)
@@ -522,6 +538,7 @@ public List findIdentifiers() {
.query(mapper.selectScadaObjectIdFrom(TABLE_NAME), mapper);
}
+ @Override
public List findIdentifiers(int dataSourceId) {
if (LOG.isTraceEnabled()) {
@@ -536,6 +553,7 @@ public List findIdentifiers(int dataSourceId) {
.build());
}
+ @Override
public List getDataPoints(String dataSourceXid) {
if (LOG.isTraceEnabled()) {
@@ -548,7 +566,7 @@ public List getDataPoints(String dataSourceXid) {
public List getDataPointsWithLimit(Set excludeIds, int offset, int limit) {
StringBuilder templateSelectWhereId = new StringBuilder(DATA_POINT_SELECT + " WHERE 1=1 ");
- List args = new ArrayList<>();
+ List