From d308d8feb31a1e677eb2edb2be5f4644a32ab007 Mon Sep 17 00:00:00 2001 From: patrykb0802 Date: Thu, 12 Mar 2026 12:10:49 +0100 Subject: [PATCH 1/7] #3249 Refactor DAO layer for modular architecture - introduce and complete DAO interface contracts across core modules - align DAO implementations, caches and services with interface-based access - replace scattered DAO factory usage with centralized database-aware bean resolution --- WebContent/WEB-INF/applicationContext.xml | 165 ++++++++++++++++-- .../util/SystemSettingsJSONWrapper.java | 19 +- .../serotonin/mango/MangoContextListener.java | 5 +- src/com/serotonin/mango/db/DBConvert.java | 2 +- .../serotonin/mango/db/DatabaseAccess.java | 54 +++++- src/com/serotonin/mango/db/DerbyAccess.java | 6 +- src/com/serotonin/mango/db/MSSQLAccess.java | 4 +- src/com/serotonin/mango/db/MySQLAccess.java | 4 +- .../serotonin/mango/db/Oracle11GAccess.java | 4 +- .../serotonin/mango/db/PostgreSQLAccess.java | 120 ++++++++----- .../serotonin/mango/db/dao/DataSourceDao.java | 22 +-- src/com/serotonin/mango/db/dao/ReportDao.java | 4 +- .../serotonin/mango/db/upgrade/DBUpgrade.java | 6 +- .../mango/db/upgrade/Upgrade1_12_4.java | 1 + .../rt/dataSource/sql/SqlDataSourceRT.java | 9 +- .../mango/rt/event/type/AuditEventType.java | 6 +- .../mango/rt/event/type/SystemEventType.java | 6 +- .../mango/rt/maint/work/ReportWorkItem.java | 6 +- .../util/freemarker/MangoEmailContent.java | 4 +- src/com/serotonin/mango/vo/User.java | 4 +- .../mango/vo/report/ReportPointVO.java | 2 + .../serotonin/mango/web/dwr/EmportDwr.java | 7 +- .../mango/web/dwr/SystemSettingsDwr.java | 66 ++++--- .../web/mvc/controller/ScadaLocaleUtils.java | 5 +- .../cache/DataSourcePointsCache.java | 8 +- .../scada_lts/cache/PointHierarchyCache.java | 10 +- .../cache/UpdateDataSourcesPoints.java | 7 +- .../scada_lts/cache/ViewHierarchyCache.java | 8 +- src/org/scada_lts/dao/DAO.java | 15 +- src/org/scada_lts/dao/DataPointDAO.java | 40 +++-- src/org/scada_lts/dao/DataPointUserDAO.java | 2 +- src/org/scada_lts/dao/DataSourceDAO.java | 37 ++-- .../dao/EventDetectorTemplateDAO.java | 2 +- src/org/scada_lts/dao/FlexProjectDAO.java | 2 +- src/org/scada_lts/dao/HierarchyDAO.java | 2 +- src/org/scada_lts/dao/IDataPointDAO.java | 77 ++++++++ src/org/scada_lts/dao/IDataPointUserDAO.java | 29 +++ src/org/scada_lts/dao/IDataSourceDAO.java | 71 ++++++++ .../dao/IEventDetectorTemplateDAO.java | 14 ++ src/org/scada_lts/dao/IFlexProjectDAO.java | 18 ++ src/org/scada_lts/dao/IHierarchyDAO.java | 6 + .../scada_lts/dao/IMaintenanceEventDAO.java | 29 +++ src/org/scada_lts/dao/IPendingEventsDAO.java | 17 ++ src/org/scada_lts/dao/IPointLinkDAO.java | 28 +++ src/org/scada_lts/dao/IPublisherDAO.java | 27 +++ src/org/scada_lts/dao/IScheduledEventDAO.java | 26 +++ src/org/scada_lts/dao/IScriptDAO.java | 33 ++++ src/org/scada_lts/dao/ISynopticPanelDAO.java | 21 +++ src/org/scada_lts/dao/ISystemSettingsDAO.java | 12 ++ src/org/scada_lts/dao/IUsersProfileDAO.java | 2 + src/org/scada_lts/dao/IViewDAO.java | 27 ++- src/org/scada_lts/dao/IViewHierarchyDAO.java | 28 +++ .../scada_lts/dao/MaintenanceEventDAO.java | 18 +- src/org/scada_lts/dao/PendingEventsDAO.java | 2 +- src/org/scada_lts/dao/PointLinkDAO.java | 55 +++--- src/org/scada_lts/dao/PublisherDAO.java | 16 +- src/org/scada_lts/dao/ScheduledEventDAO.java | 14 +- src/org/scada_lts/dao/ScriptDAO.java | 33 ++-- src/org/scada_lts/dao/SynopticPanelDAO.java | 2 +- src/org/scada_lts/dao/SystemSettingsDAO.java | 5 +- src/org/scada_lts/dao/ViewHierarchyDAO.java | 11 +- .../scada_lts/dao/alarms/AlarmsService.java | 2 +- .../{AlarmsDAO.java => IAlarmsDAO.java} | 8 +- .../scada_lts/dao/alarms/PlcAlarmsDAO.java | 2 +- .../dao/alarms/PlcAlarmsService.java | 4 +- .../dao/cache/PointEventDetectorCache.java | 6 +- .../cache/PointEventDetectorDaoWithCache.java | 27 ++- src/org/scada_lts/dao/cache/UserCache.java | 6 +- .../scada_lts/dao/cache/UserCommentCache.java | 6 +- .../dao/cache/UserCommentDaoWithCache.java | 5 +- .../dao/cache/UsersProfileCache.java | 6 +- src/org/scada_lts/dao/cache/ViewCache.java | 7 +- .../scada_lts/dao/cache/ViewDaoWithCache.java | 27 ++- .../dao/event/CompoundEventDetectorDAO.java | 9 +- src/org/scada_lts/dao/event/EventDAO.java | 93 ++++++---- .../dao/event/ICompoundEventDetectorDAO.java | 23 +++ src/org/scada_lts/dao/event/IEventDAO.java | 117 +++++++++++++ .../scada_lts/dao/event/IUserEventDAO.java | 16 ++ src/org/scada_lts/dao/event/UserEventDAO.java | 3 +- .../dao/mailingList/IMailingListDAO.java | 29 +++ .../mailingList/IMailingListInactiveDAO.java | 14 ++ .../mailingList/IMailingListMemberDAO.java | 17 ++ .../dao/mailingList/MailingListDAO.java | 16 +- .../mailingList/MailingListInactiveDAO.java | 2 +- .../dao/mailingList/MailingListMemberDAO.java | 2 +- .../mysql/V2_7_0_2__FixViewPermissions.java | 4 +- .../pointhierarchy/IPointHierarchyDAO.java | 34 ++++ .../pointhierarchy/IPointHierarchyXidDAO.java | 24 +++ .../dao/pointhierarchy/PointHierarchyDAO.java | 12 +- .../pointhierarchy/PointHierarchyXidDAO.java | 2 +- .../IPointValueAdnnotationsDAO.java | 11 ++ .../pointvalues/IPointValueAmChartDAO.java | 24 +++ .../dao/pointvalues/IPointValueDAO.java | 8 + .../PointValueAdnnotationsDAO.java | 15 +- .../dao/pointvalues/PointValueAmChartDAO.java | 2 +- .../dao/pointvalues/PointValueDAO.java | 37 +++- src/org/scada_lts/dao/report/IReportDAO.java | 30 ++++ .../dao/report/IReportInstanceDAO.java | 41 +++++ .../dao/report/IReportInstanceDataDAO.java | 18 ++ .../dao/report/IReportInstancePointDAO.java | 64 +++++++ .../report/IReportInstanceUserCommentDAO.java | 10 ++ src/org/scada_lts/dao/report/ReportDAO.java | 17 +- .../dao/report/ReportInstanceDAO.java | 24 ++- .../dao/report/ReportInstanceDataDAO.java | 9 +- .../dao/report/ReportInstancePointDAO.java | 59 +------ .../report/ReportInstanceUserCommentDAO.java | 2 +- .../dao/watchlist/IWatchListDAO.java | 65 +++++++ .../scada_lts/dao/watchlist/WatchListDAO.java | 28 ++- src/org/scada_lts/db/BinaryDataHandler.java | 14 ++ .../scada_lts/db/MysqlBinaryDataHandler.java | 27 +++ .../ReactivationConnectHttpRetriever.java | 5 +- .../factory/DatabaseAwareBeanFactory.java | 141 +++++++++++++++ .../scada_lts/mango/adapter/MangoReport.java | 4 +- .../service/CompoundEventDetectorService.java | 7 +- .../mango/service/DataPointService.java | 35 ++-- .../mango/service/DataSourceService.java | 16 +- .../scada_lts/mango/service/EventService.java | 11 +- .../mango/service/FlexProjectService.java | 5 +- .../mango/service/MailingListService.java | 13 +- .../service/MaintenanceEventService.java | 5 +- .../mango/service/PendingEventService.java | 6 +- .../mango/service/PointLinkService.java | 5 +- .../mango/service/PointValueService.java | 77 ++++---- .../mango/service/PublisherService.java | 5 +- .../mango/service/ReportService.java | 25 +-- .../mango/service/ScheduledEventService.java | 5 +- .../mango/service/ScriptService.java | 5 +- .../mango/service/SystemSettingsService.java | 29 ++- .../mango/service/WatchListService.java | 9 +- .../dao/OnlyMigrationDataPointService.java | 6 +- .../dao/OnlyMigrationDataSourceService.java | 6 +- .../DataPointProfilePermissionsService.java | 3 - .../DataPointUserPermissionsService.java | 6 +- .../DataSourceProfilePermissionsService.java | 2 - .../DataSourceUserPermissionsService.java | 6 +- .../service/GetDataPointsWithAccess.java | 6 +- .../service/GetDataSourcesWithAccess.java | 12 +- .../service/GetReportInstancesWithAccess.java | 6 +- .../service/GetReportsWithAccess.java | 6 +- .../service/GetWatchListsWithAccess.java | 5 +- .../ViewProfilePermissionsService.java | 2 - .../service/ViewUserPermissionsService.java | 2 - .../service/WatchListGetShareUsers.java | 6 +- .../WatchListProfilePermissionsService.java | 2 - .../WatchListUserPermissionsService.java | 6 +- .../service/SynopticPanelService.java | 5 +- .../service/ViewHierarchyService.java | 16 +- .../pointhierarchy/PointHierarchyService.java | 20 +-- .../PointHierarchyXidService.java | 11 +- .../scada_lts/utils/GetDataPointsUtils.java | 37 ++-- .../scada_lts/utils/PointHierarchyUtils.java | 22 +-- .../scada_lts/web/beans/ApplicationBeans.java | 93 ++++++++++ .../web/mvc/api/DataPointApiService.java | 12 +- .../web/mvc/api/dto/ObjectHierarchy.java | 4 +- .../web/mvc/api/dto/ObjectHierarchyType.java | 8 +- .../web/mvc/controller/SqlController.java | 9 +- .../scenarios/ScenarioWithAdministrador.java | 5 +- .../serotonin/mango/db/MySQLAccessTest.java | 8 +- .../RuntimeManagerCreateDataPointRtTest.java | 20 ++- .../rt/dataImage/PointValueCacheTest.java | 10 +- .../config/ConfigDataPointRtTest.java | 88 +++++----- .../AbstractStartStopDataPointsUtilsTest.java | 27 ++- .../util/SerializationHelperTest.java | 8 +- .../cache/DeletePointHierarchyCacheTest.java | 19 +- ...OnBaseParentIdPointHierarchyCacheTest.java | 18 +- .../dao/EventDetectorTemplateDaoTest.java | 2 +- test/org/scada_lts/dao/EventServiceTest.java | 21 +-- .../org/scada_lts/dao/FlexProjectDaoTest.java | 8 +- .../scada_lts/dao/ReportInstanceDaoTest.java | 18 +- .../scada_lts/dao/SystemSettingsDaoTest.java | 11 +- test/org/scada_lts/dao/UserEventDaoTest.java | 3 +- test/utils/PointValueDAOMemory.java | 20 +++ test/utils/ScriptTestUtils.java | 17 +- test/utils/mock/PowerMockUtils.java | 23 +++ 174 files changed, 2596 insertions(+), 770 deletions(-) create mode 100644 src/org/scada_lts/dao/IDataPointDAO.java create mode 100644 src/org/scada_lts/dao/IDataPointUserDAO.java create mode 100644 src/org/scada_lts/dao/IDataSourceDAO.java create mode 100644 src/org/scada_lts/dao/IEventDetectorTemplateDAO.java create mode 100644 src/org/scada_lts/dao/IFlexProjectDAO.java create mode 100644 src/org/scada_lts/dao/IHierarchyDAO.java create mode 100644 src/org/scada_lts/dao/IMaintenanceEventDAO.java create mode 100644 src/org/scada_lts/dao/IPendingEventsDAO.java create mode 100644 src/org/scada_lts/dao/IPointLinkDAO.java create mode 100644 src/org/scada_lts/dao/IPublisherDAO.java create mode 100644 src/org/scada_lts/dao/IScheduledEventDAO.java create mode 100644 src/org/scada_lts/dao/IScriptDAO.java create mode 100644 src/org/scada_lts/dao/ISynopticPanelDAO.java create mode 100644 src/org/scada_lts/dao/ISystemSettingsDAO.java create mode 100644 src/org/scada_lts/dao/IViewHierarchyDAO.java rename src/org/scada_lts/dao/alarms/{AlarmsDAO.java => IAlarmsDAO.java} (88%) create mode 100644 src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java create mode 100644 src/org/scada_lts/dao/event/IEventDAO.java create mode 100644 src/org/scada_lts/dao/event/IUserEventDAO.java create mode 100644 src/org/scada_lts/dao/mailingList/IMailingListDAO.java create mode 100644 src/org/scada_lts/dao/mailingList/IMailingListInactiveDAO.java create mode 100644 src/org/scada_lts/dao/mailingList/IMailingListMemberDAO.java create mode 100644 src/org/scada_lts/dao/pointhierarchy/IPointHierarchyDAO.java create mode 100644 src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java create mode 100644 src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java create mode 100644 src/org/scada_lts/dao/pointvalues/IPointValueAmChartDAO.java create mode 100644 src/org/scada_lts/dao/report/IReportDAO.java create mode 100644 src/org/scada_lts/dao/report/IReportInstanceDAO.java create mode 100644 src/org/scada_lts/dao/report/IReportInstanceDataDAO.java create mode 100644 src/org/scada_lts/dao/report/IReportInstancePointDAO.java create mode 100644 src/org/scada_lts/dao/report/IReportInstanceUserCommentDAO.java create mode 100644 src/org/scada_lts/dao/watchlist/IWatchListDAO.java create mode 100644 src/org/scada_lts/db/BinaryDataHandler.java create mode 100644 src/org/scada_lts/db/MysqlBinaryDataHandler.java create mode 100644 src/org/scada_lts/factory/DatabaseAwareBeanFactory.java diff --git a/WebContent/WEB-INF/applicationContext.xml b/WebContent/WEB-INF/applicationContext.xml index 3e69cf3c19..73669e9b7d 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,21 @@ - - - - - + + + + + + + + + + + + + + @@ -91,6 +102,11 @@ + + + + + @@ -168,10 +184,8 @@ - - @@ -187,8 +201,6 @@ - - @@ -211,16 +223,147 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - diff --git a/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java b/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java index 2f21e4d07d..339493c956 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..0b6427bee7 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..1ca2c381b9 100644 --- a/src/com/serotonin/mango/db/DatabaseAccess.java +++ b/src/com/serotonin/mango/db/DatabaseAccess.java @@ -26,7 +26,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,6 +45,7 @@ abstract public class DatabaseAccess { private final static Log log = LogFactory.getLog(DatabaseAccess.class); + @Deprecated public enum DatabaseType { DERBY { @Override @@ -78,6 +81,7 @@ DatabaseAccess getImpl() { abstract DatabaseAccess getImpl(); } + @Deprecated public static DatabaseAccess createDatabaseAccess() { String type = Common.getEnvironmentProfile().getString("db.type", @@ -115,13 +119,17 @@ 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) + String convertKey = normalizeDbKey(convertTypeStr); + if (StringUtils.isEmpty(convertKey)) { throw new IllegalArgumentException( - "Unknown convert database type: " + convertType); + "Unknown convert database type: " + convertTypeStr); + } - DatabaseAccess sourceAccess = convertType.getImpl(); + DatabaseAccess sourceAccess = resolveDatabaseAccess(convertKey); + if (sourceAccess == this) { + throw new IllegalStateException( + "convert.db.type must be different from db.type."); + } sourceAccess.initializeImpl("convert."); DBConvert convert = new DBConvert(); @@ -150,7 +158,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()); } @@ -165,7 +174,7 @@ public void initialize(ServletContext ctx) { } } catch (CannotGetJdbcConnectionException e) { log.fatal("Unable to connect to database of type " - + getType().name(), e); + + getTypeKey(), e); throw e; } @@ -184,7 +193,11 @@ private void initDataSource() { } } - abstract public DatabaseType getType(); + abstract public String getTypeKey(); + + public String getIdQuery() { + return "SELECT @@identity"; + } abstract public void terminate(); @@ -262,4 +275,29 @@ public PreparedStatement prepareStatement(Connection connection, return connection.prepareStatement(sql, 1); } + private static DatabaseAccess resolveDatabaseAccess(String dbKey) { + String normalized = normalizeDbKey(dbKey); + String beanName = "databaseAccess-" + normalized; + DatabaseAccess access = ApplicationBeans.getBean(beanName, DatabaseAccess.class); + if (access == null) { + throw new IllegalStateException("DB plugin not found for db.type=" + normalized + + ". Expected bean '" + beanName + "'."); + } + return access; + } + + private static String normalizeDbKey(String dbType) { + if (dbType == null) { + return ""; + } + String normalized = dbType.trim().toLowerCase(); + if ("postgresql".equals(normalized) || "pgsql".equals(normalized) || "pg".equals(normalized)) { + return "postgres"; + } + if ("sqlserver".equals(normalized) || "sql-server".equals(normalized)) { + return "mssql"; + } + return normalized; + } + } diff --git a/src/com/serotonin/mango/db/DerbyAccess.java b/src/com/serotonin/mango/db/DerbyAccess.java index 535e7d4c45..315ec2884d 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; @@ -58,8 +58,8 @@ public class DerbyAccess extends DatabaseAccess { private EmbeddedXADataSource40 dataSource; @Override - public DatabaseType getType() { - return DatabaseType.DERBY; + public String getTypeKey() { + return "derby"; } @Override diff --git a/src/com/serotonin/mango/db/MSSQLAccess.java b/src/com/serotonin/mango/db/MSSQLAccess.java index b13fc7e2da..dba6ba1ed6 100644 --- a/src/com/serotonin/mango/db/MSSQLAccess.java +++ b/src/com/serotonin/mango/db/MSSQLAccess.java @@ -29,8 +29,8 @@ public class MSSQLAccess extends BasePooledAccess { @Override - public DatabaseType getType() { - return DatabaseType.MSSQL; + public String getTypeKey() { + return "mssql"; } @Override diff --git a/src/com/serotonin/mango/db/MySQLAccess.java b/src/com/serotonin/mango/db/MySQLAccess.java index f2e288f263..1ce36e8e75 100644 --- a/src/com/serotonin/mango/db/MySQLAccess.java +++ b/src/com/serotonin/mango/db/MySQLAccess.java @@ -61,8 +61,8 @@ protected String getUrl(String propertyPrefix) { } @Override - public DatabaseType getType() { - return DatabaseType.MYSQL; + public String getTypeKey() { + return "mysql"; } @Override diff --git a/src/com/serotonin/mango/db/Oracle11GAccess.java b/src/com/serotonin/mango/db/Oracle11GAccess.java index db4d4d93cf..7071bca39b 100644 --- a/src/com/serotonin/mango/db/Oracle11GAccess.java +++ b/src/com/serotonin/mango/db/Oracle11GAccess.java @@ -67,8 +67,8 @@ protected void initializeImpl(String propertyPrefix, String dataSourceName) { } @Override - public DatabaseType getType() { - return DatabaseType.ORACLE11G; + public String getTypeKey() { + return "oracle11g"; } @Override diff --git a/src/com/serotonin/mango/db/PostgreSQLAccess.java b/src/com/serotonin/mango/db/PostgreSQLAccess.java index 9d87632a5c..1736e0bf41 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 String getTypeKey() { + return "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..36d8d046ba 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; @@ -28,12 +27,12 @@ import java.util.ResourceBundle; import org.scada_lts.dao.DAO; +import org.scada_lts.web.beans.ApplicationBeans; import org.scada_lts.mango.adapter.MangoDataSource; import org.scada_lts.mango.service.DataSourceService; import org.springframework.dao.DataAccessException; import com.serotonin.db.spring.GenericResultSetExtractor; -import com.serotonin.mango.Common; 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 = ApplicationBeans.getBinaryDataHandler().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, + ApplicationBeans.getBinaryDataHandler().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..d1bef2aaf0 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/dataSource/sql/SqlDataSourceRT.java b/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java index 8e594db00f..fcd41b6017 100644 --- a/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java +++ b/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java @@ -29,7 +29,6 @@ import com.serotonin.ShouldNeverHappenException; import com.serotonin.io.StreamUtils; -import com.serotonin.mango.Common; import com.serotonin.mango.DataTypes; import com.serotonin.mango.rt.dataImage.DataPointRT; import com.serotonin.mango.rt.dataImage.PointValueTime; @@ -46,6 +45,7 @@ import com.serotonin.mango.vo.dataSource.sql.SqlPointLocatorVO; import com.serotonin.util.StringUtils; import com.serotonin.web.i18n.LocalizableMessage; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.jdbc.core.*; import static com.serotonin.mango.util.SqlDataSourceUtils.addLimitIfWithout; @@ -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(ApplicationBeans.getBinaryDataHandler().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..f3cb8dd790 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/SystemEventType.java b/src/com/serotonin/mango/rt/event/type/SystemEventType.java index 737b9908e5..969f3abdd8 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..b91b93c0f6 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.getBean("usersProfileDAO", IUsersProfileDAO.class); 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/EmportDwr.java b/src/com/serotonin/mango/web/dwr/EmportDwr.java index fefc49f77e..9f314cc6c3 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; @@ -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..92fe4bb20a 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; @@ -242,14 +245,19 @@ public Map getDatabaseSize() { 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); + String dbType = checkTypeDB(); + if (dbType.equalsIgnoreCase("mysql") || dbType.equalsIgnoreCase("postgres")) { + double size = ApplicationBeans.getSystemSettingsDAOBean().getDataBaseSize(); + if (size >= 0) { + 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); + } else { + data.put("databaseSize", "(" + getMessage("common.unknown") + ")"); + } } // Point history counts. @@ -272,19 +280,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 +403,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 +465,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 +483,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); @@ -546,7 +554,15 @@ public void useMssqlDB() { public String checkTypeDB() { - return Common.getEnvironmentProfile().getString("db.type", "derby"); + try { + DatabaseAccess databaseAccess = DatabaseAccess.getDatabaseAccess(); + if (databaseAccess != null) { + return databaseAccess.getTypeKey(); + } + } catch (Exception ignore) { + // fallback to env.properties + } + return Common.getEnvironmentProfile().getString("db.type", "mysql"); } diff --git a/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java b/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java index f513c62672..fd244d8477 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/DataSourcePointsCache.java b/src/org/scada_lts/cache/DataSourcePointsCache.java index 960802e711..2564460ca8 100644 --- a/src/org/scada_lts/cache/DataSourcePointsCache.java +++ b/src/org/scada_lts/cache/DataSourcePointsCache.java @@ -4,7 +4,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.config.ScadaConfig; -import org.scada_lts.dao.DataPointDAO; +import org.scada_lts.dao.IDataPointDAO; import org.scada_lts.quartz.CronTriggerScheduler; import org.scada_lts.web.beans.ApplicationBeans; @@ -69,8 +69,10 @@ public boolean isCacheEnabled() { @Override public void cacheInitialize() { - - List dps = new DataPointDAO().getDataPoints(); + + IDataPointDAO dao = ApplicationBeans.getBean("dataPointDAO", IDataPointDAO.class); + + List dps = dao.getDataPoints(); dss = composeCashData(dps); diff --git a/src/org/scada_lts/cache/PointHierarchyCache.java b/src/org/scada_lts/cache/PointHierarchyCache.java index 10a831e6ce..785bfa2584 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.getBean("pointHierarchyDAO", IPointHierarchyDAO.class); + List lstPointHierarchy = pointHierarchyDAO.getPointsHierarchy(); Collections.sort(lstPointHierarchy, PointHierarchyComparator.getInst()); for (PointHierarchyNode ph : lstPointHierarchy) { diff --git a/src/org/scada_lts/cache/UpdateDataSourcesPoints.java b/src/org/scada_lts/cache/UpdateDataSourcesPoints.java index 2a3cf1462e..bc60ffbafc 100644 --- a/src/org/scada_lts/cache/UpdateDataSourcesPoints.java +++ b/src/org/scada_lts/cache/UpdateDataSourcesPoints.java @@ -7,7 +7,8 @@ import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.StatefulJob; -import org.scada_lts.dao.DataPointDAO; +import org.scada_lts.dao.IDataPointDAO; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.List; import java.util.Map; @@ -15,13 +16,15 @@ public class UpdateDataSourcesPoints implements StatefulJob{ private static final Log LOG = LogFactory.getLog(UpdateDataSourcesPoints.class); + private final IDataPointDAO dao = ApplicationBeans.getDataPointDAOBean(); + @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { try { LOG.trace("UpdateEventDetectors"); - List dps = new DataPointDAO().getDataPoints(); + List dps = dao.getDataPoints(); Map> dss = DataSourcePointsCache.getInstance().composeCashData(dps); DataSourcePointsCache.getInstance().setData(dss); } catch (Exception ex) { diff --git a/src/org/scada_lts/cache/ViewHierarchyCache.java b/src/org/scada_lts/cache/ViewHierarchyCache.java index 5082764390..a59ff5a7f0 100644 --- a/src/org/scada_lts/cache/ViewHierarchyCache.java +++ b/src/org/scada_lts/cache/ViewHierarchyCache.java @@ -21,9 +21,9 @@ 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; +import org.scada_lts.web.beans.ApplicationBeans; /** * Class responsible for buffering data of ViewHierarchy @@ -45,7 +45,9 @@ private ViewHierarchyCache() { private void initial() { LOG.info("Initial ViewHierarchyCache"); - cache = new ViewHierarchyService().getAll(); + ViewHierarchyService service = ApplicationBeans.getViewHierarchyServiceBean(); + + cache = service.getAll(); } public static ViewHierarchyCache getInstance() { @@ -62,7 +64,7 @@ public List getAll() { } public void refresh() { - cache = new ViewHierarchyService().getAll(); + cache = ApplicationBeans.getViewHierarchyServiceBean().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 args = new ArrayList<>(); if(excludeIds != null && !excludeIds.isEmpty()) { templateSelectWhereId.append(" AND").append(" dp.") .append(COLUMN_NAME_ID) @@ -556,7 +574,7 @@ public List getDataPointsWithLimit(Set excludeIds, int off .append("?, ".repeat(excludeIds.size() - 1)) .append("?").append(") "); - args.addAll(excludeIds.stream().map(Object::toString).collect(Collectors.toList())); + args.addAll(excludeIds); } if(limit > 0) { @@ -580,7 +598,7 @@ public List selectDataPoints(Set ids) { public List getDataPointByKeywords(Set keywords, Set excludeIds, boolean startsWith, int offset, int limit) { StringBuilder templateSelectWhereSearch = new StringBuilder(DATA_POINT_SELECT + " WHERE 1=1 "); - List args = new ArrayList<>(); + List args = new ArrayList<>(); for (String keyword : keywords) { if(StringUtils.isEmpty(keyword)) { continue; @@ -605,7 +623,7 @@ public List getDataPointByKeywords(Set keywords, Set ds1, DataSourceVO ds2) { } } + @Override public List> getDataSources() { if (LOG.isTraceEnabled()) { @@ -302,18 +303,21 @@ public List> getDataSources() { return objList; } + @Override public List getAllDataSources() { ScadaObjectIdentifierRowMapper mapper = ScadaObjectIdentifierRowMapper.withDefaultNames(); return DAO.getInstance().getJdbcTemp() .query(mapper.selectScadaObjectIdFrom(TABLE_NAME), mapper); } + @Override public List> getDataSourcesPlc() { List> list = DAO.getInstance().getJdbcTemp().query(DATA_SOURCE_PLC_SELECT, new DataSourceRowMapper()); return list; } - public List> getDataSourceBaseOfName( String partOfNameDS) { + @Override + public List> getDataSourceBaseOfName(String partOfNameDS) { if (LOG.isTraceEnabled()) { LOG.trace("getDataSources()"); } @@ -326,6 +330,7 @@ public List> getDataSourceBaseOfName( String partOfNameDS) { return objList; } + @Override public List getDataSourceUsersId(int id) { if (LOG.isTraceEnabled()) { @@ -335,6 +340,7 @@ public List getDataSourceUsersId(int id) { return DAO.getInstance().getJdbcTemp().queryForList(DATA_SOURCE_USER_SELECT_WHERE_DS_ID, new Object[]{id}, Integer.class); } + @Override public List getDataSourceIdFromDsUsers(int userId) { if (LOG.isTraceEnabled()) { @@ -345,6 +351,7 @@ public List getDataSourceIdFromDsUsers(int userId) { } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public void batchInsert(final List userIds, final int toDataSourceId) { if (LOG.isTraceEnabled()) { @@ -365,6 +372,7 @@ public int getBatchSize() { }); } + @Override public DataSourceVO getDataSource(int id) { if (LOG.isTraceEnabled()) { @@ -376,6 +384,7 @@ public DataSourceVO getDataSource(int id) { } + @Override public DataSourceVO getDataSource(String xid) { if (LOG.isTraceEnabled()) { @@ -390,6 +399,7 @@ public DataSourceVO getDataSource(String xid) { } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public int insert(final DataSourceVO dataSource) { if (LOG.isTraceEnabled()) { @@ -415,6 +425,7 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public void insertPermissions(final User user) { if (LOG.isTraceEnabled()) { @@ -436,6 +447,7 @@ public int getBatchSize() { } + @Override public DataSourceVO create(DataSourceVO entity) { if (LOG.isTraceEnabled()) { LOG.trace("insert(final DataSourceVO dataSource): dataSource" + dataSourceInfo(entity)); @@ -456,23 +468,18 @@ public DataSourceVO create(DataSourceVO entity) { return entity; } - @Deprecated - public List getSimpleList() { - ScadaObjectIdentifierRowMapper mapper = ScadaObjectIdentifierRowMapper.withDefaultNames(); - - return DAO.getInstance().getJdbcTemp() - .query(mapper.selectScadaObjectIdFrom(TABLE_NAME), mapper); - } - + @Override public List> getAll() { return getDataSources(); } + @Override public DataSourceVO getById(int id) throws EmptyResultDataAccessException { return getDataSource(id); } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public int update(final DataSourceVO dataSource) { if (LOG.isTraceEnabled()) { @@ -495,6 +502,7 @@ public int update(final DataSourceVO dataSource) { } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public int delete(int dataSourceId) { if (LOG.isTraceEnabled()) { @@ -514,6 +522,7 @@ public int delete(int dataSourceId) { } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public void deleteDataSourceUser(int userId) { if (LOG.isTraceEnabled()) { @@ -523,6 +532,7 @@ public void deleteDataSourceUser(int userId) { DAO.getInstance().getJdbcTemp().update(DATA_SOURCE_USER_DELETE_WHERE_USER_ID, new Object[]{userId}); } + @Override public List selectDataSourcePermissions(int userId) { if (LOG.isTraceEnabled()) { @@ -533,6 +543,7 @@ public List selectDataSourcePermissions(int userId) { new Object[]{userId}, (rs, rowNum) -> rs.getInt(COLUMN_NAME_DS_USER_ID)); } + @Override public int[] insertPermissions(int userId, List toInsert) { if (LOG.isTraceEnabled()) { LOG.trace("insertPermissions(int userId, List toInsert) user:" + userId + ""); @@ -548,6 +559,7 @@ public int[] insertPermissions(int userId, List toInsert) { .batchUpdate(DATA_SOURCE_USERS_INSERT_ON_DUPLICATE_KEY_UPDATE_ACCESS_TYPE, batchArgs, argTypes); } + @Override public int[] deletePermissions(int userId, List toDelete) { if (LOG.isTraceEnabled()) { @@ -564,6 +576,7 @@ public int[] deletePermissions(int userId, List toDelete) { .batchUpdate(DATA_SOURCE_USERS_DELETE_DATA_SOURCE_ID_AND_USER_ID, batchArgs, argTypes); } + @Override public List selectDataSourceShareUsers(int dataSourceId) { if (LOG.isTraceEnabled()) LOG.trace("selectDataSourceShareUsers(int dataSourceId) dataSourceId:" + dataSourceId); @@ -579,6 +592,7 @@ public List selectDataSourceShareUsers(int dataSourceId) { } } + @Override public List> getDataSources(int type) { if (LOG.isTraceEnabled()) { @@ -588,12 +602,14 @@ public List> getDataSources(int type) { new Object[]{type}, new DataSourceRowMapper()); } + @Override public List> selectDataSourcesWithAccess(int userId, int profileId) { return DAO.getInstance().getJdbcTemp().query(DATA_SOURCE_DS_SELECT_JOIN_LEFT_DATA_POINT_DP + " where " + DATA_SOURCE_FILTERED_BASE_ON_USER_ID_USERS_PROFILE_ID_ORDER_BY_DS_NAME, new Object[] { userId, profileId, userId, ShareUser.ACCESS_NONE, profileId, ShareUser.ACCESS_NONE }, new DataSourceDAO.DataSourceRowMapper()); } + @Override public List selectDataSourceIdentifiersWithAccess(int userId, int profileId) { return DAO.getInstance().getJdbcTemp().query(DATA_SOURCE_DS_SELECT_JOIN_LEFT_DATA_POINT_DP_IDENTIFIER + " where " + DATA_SOURCE_FILTERED_BASE_ON_USER_ID_USERS_PROFILE_ID_ORDER_BY_DS_NAME, new Object[] { userId, profileId, userId, ShareUser.ACCESS_NONE, profileId, ShareUser.ACCESS_NONE }, @@ -604,6 +620,7 @@ public List selectDataSourceIdentifiersWithAccess(int use .build()); } + @Override public List findIdentifiers() { ScadaObjectIdentifierRowMapper mapper = ScadaObjectIdentifierRowMapper.withDefaultNames(); return DAO.getInstance().getJdbcTemp() diff --git a/src/org/scada_lts/dao/EventDetectorTemplateDAO.java b/src/org/scada_lts/dao/EventDetectorTemplateDAO.java index eb0e96226f..3106db75b1 100644 --- a/src/org/scada_lts/dao/EventDetectorTemplateDAO.java +++ b/src/org/scada_lts/dao/EventDetectorTemplateDAO.java @@ -46,7 +46,7 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ -public class EventDetectorTemplateDAO { +public class EventDetectorTemplateDAO implements IEventDetectorTemplateDAO { private static final Log LOG = LogFactory.getLog(EventDetectorTemplateDAO.class); diff --git a/src/org/scada_lts/dao/FlexProjectDAO.java b/src/org/scada_lts/dao/FlexProjectDAO.java index 7582433de5..bb99998120 100644 --- a/src/org/scada_lts/dao/FlexProjectDAO.java +++ b/src/org/scada_lts/dao/FlexProjectDAO.java @@ -46,7 +46,7 @@ * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class FlexProjectDAO { +public class FlexProjectDAO implements IFlexProjectDAO { private static final Log LOG = LogFactory.getLog(FlexProjectDAO.class); diff --git a/src/org/scada_lts/dao/HierarchyDAO.java b/src/org/scada_lts/dao/HierarchyDAO.java index 9a9e572539..a2212384c5 100644 --- a/src/org/scada_lts/dao/HierarchyDAO.java +++ b/src/org/scada_lts/dao/HierarchyDAO.java @@ -34,7 +34,7 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * person supporting and coreecting translation Jerzy Piejko */ -public class HierarchyDAO { +public class HierarchyDAO implements IHierarchyDAO { private static final Log LOG = LogFactory.getLog(HierarchyDAO.class); diff --git a/src/org/scada_lts/dao/IDataPointDAO.java b/src/org/scada_lts/dao/IDataPointDAO.java new file mode 100644 index 0000000000..585dd72d64 --- /dev/null +++ b/src/org/scada_lts/dao/IDataPointDAO.java @@ -0,0 +1,77 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.vo.DataPointVO; +import org.scada_lts.dao.model.ScadaObjectIdentifier; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; +import java.util.Set; + +public interface IDataPointDAO { + DataPointVO getDataPoint(int id); + + DataPointVO getDataPoint(String xid); + + List getDataPoints(); + + List filtered(String filter, Object[] argsFilter, long limit); + + List getDataPoints(int dataSourceId); + + List getDataPointByKeyword(String[] keywords); + + List getPlcDataPoints(int dataSourceId); + + List getDataPointsIds(int dataSourceId); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(DataPointVO dataPoint); + + DataPointVO create(DataPointVO entity); + + DataPointVO getById(int id) throws EmptyResultDataAccessException; + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int update(DataPointVO dataPoint); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int delete(int id); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void deleteWithIn(String dataPointIdList); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void deleteEventHandler(String dataPointIdList); + + List selectDataPointsWithAccess(int userId, int profileId); + + List selectDataPointsWithAccess(int userId); + + List selectDataPointIdentifiersWithAccess(int userId, int profileId); + + List selectDataPointIdentifiersWithAccess(int userId); + + List findIdentifiers(); + + List findIdentifiers(int dataSourceId); + + List getDataPoints(String dataSourceXid); + + List selectDataPoints(Set ids); + + List getDataPointsWithLimit(Set excludeIds, int offset, int limit); + + List getDataPointByKeywords(Set keywords, Set excludeIds, boolean startsWith, int offset, int limit); + + int selectDataPointIdWithAccessPrev(int userId, int profileId, String name); + + int selectDataPointIdWithAccessNext(int userId, int profileId, String name); + + int selectDataPointIdWithAccessPrev(String name); + + int selectDataPointIdWithAccessNext(String name); +} diff --git a/src/org/scada_lts/dao/IDataPointUserDAO.java b/src/org/scada_lts/dao/IDataPointUserDAO.java new file mode 100644 index 0000000000..1bcf6d67ba --- /dev/null +++ b/src/org/scada_lts/dao/IDataPointUserDAO.java @@ -0,0 +1,29 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.view.ShareUser; +import com.serotonin.mango.vo.User; +import com.serotonin.mango.vo.permission.DataPointAccess; +import com.serotonin.util.Tuple; + +import java.util.List; + +public interface IDataPointUserDAO { + + List> getDataPointUsers(int dataPointId); + + void insert(List> users, int dataPointId); + + void insertPermissions(User user); + + void delete(int userId); + + void deleteWhereDataPointId(int dataPointId); + + List selectDataPointPermissions(int userId); + + int[] insertPermissions(int userId, List toInsert); + + int[] deletePermissions(int userId, List toDelete); + + List selectDataPointShareUsers(int dataPointId); +} diff --git a/src/org/scada_lts/dao/IDataSourceDAO.java b/src/org/scada_lts/dao/IDataSourceDAO.java new file mode 100644 index 0000000000..e0a13733e2 --- /dev/null +++ b/src/org/scada_lts/dao/IDataSourceDAO.java @@ -0,0 +1,71 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.view.ShareUser; +import com.serotonin.mango.vo.User; +import com.serotonin.mango.vo.dataSource.DataSourceVO; +import org.scada_lts.dao.model.ScadaObjectIdentifier; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IDataSourceDAO { + List> getDataSources(); + + List getAllDataSources(); + + List> getDataSourcesPlc(); + + List> getDataSourceBaseOfName(String partOfNameDS); + + List getDataSourceUsersId(int id); + + List getDataSourceIdFromDsUsers(int userId); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void batchInsert(List userIds, int toDataSourceId); + + DataSourceVO getDataSource(int id); + + DataSourceVO getDataSource(String xid); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(DataSourceVO dataSource); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void insertPermissions(User user); + + DataSourceVO create(DataSourceVO entity); + + List> getAll(); + + DataSourceVO getById(int id) throws EmptyResultDataAccessException; + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int update(DataSourceVO dataSource); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int delete(int dataSourceId); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void deleteDataSourceUser(int userId); + + List selectDataSourcePermissions(int userId); + + int[] insertPermissions(int userId, List toInsert); + + int[] deletePermissions(int userId, List toDelete); + + List selectDataSourceShareUsers(int dataSourceId); + + List> getDataSources(int type); + + List> selectDataSourcesWithAccess(int userId, int profileId); + + List selectDataSourceIdentifiersWithAccess(int userId, int profileId); + + List findIdentifiers(); +} diff --git a/src/org/scada_lts/dao/IEventDetectorTemplateDAO.java b/src/org/scada_lts/dao/IEventDetectorTemplateDAO.java new file mode 100644 index 0000000000..c028246205 --- /dev/null +++ b/src/org/scada_lts/dao/IEventDetectorTemplateDAO.java @@ -0,0 +1,14 @@ +package org.scada_lts.dao; + +import br.org.scadabr.vo.eventDetectorTemplate.EventDetectorTemplateVO; + +import java.util.List; + +public interface IEventDetectorTemplateDAO { + + EventDetectorTemplateVO getEventDetectorTemplate(int id); + + List getEventDetectorTemplatesWithoutDetectors(); + + int insertEventDetectorTemplate(EventDetectorTemplateVO eventDetectorTemplate); +} diff --git a/src/org/scada_lts/dao/IFlexProjectDAO.java b/src/org/scada_lts/dao/IFlexProjectDAO.java new file mode 100644 index 0000000000..e4c068b2fc --- /dev/null +++ b/src/org/scada_lts/dao/IFlexProjectDAO.java @@ -0,0 +1,18 @@ +package org.scada_lts.dao; + +import br.org.scadabr.api.vo.FlexProject; + +import java.util.List; + +public interface IFlexProjectDAO { + + FlexProject getFlexProject(int id); + + int insert(String xid, String name, String description); + + void update(int id, String xid, String name, String description); + + void delete(int id); + + List getFlexProjects(); +} diff --git a/src/org/scada_lts/dao/IHierarchyDAO.java b/src/org/scada_lts/dao/IHierarchyDAO.java new file mode 100644 index 0000000000..8079e49aa6 --- /dev/null +++ b/src/org/scada_lts/dao/IHierarchyDAO.java @@ -0,0 +1,6 @@ +package org.scada_lts.dao; + +public interface IHierarchyDAO { + public abstract java.util.List getHierarchy(); +} + diff --git a/src/org/scada_lts/dao/IMaintenanceEventDAO.java b/src/org/scada_lts/dao/IMaintenanceEventDAO.java new file mode 100644 index 0000000000..32edbf308f --- /dev/null +++ b/src/org/scada_lts/dao/IMaintenanceEventDAO.java @@ -0,0 +1,29 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.vo.event.MaintenanceEventVO; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IMaintenanceEventDAO { + MaintenanceEventVO getMaintenanceEvent(int id); + + MaintenanceEventVO getMaintenanceEvent(String xid); + + List getMaintenanceEvents(); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(MaintenanceEventVO maintenanceEvent); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void update(MaintenanceEventVO maintenanceEvent); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void delete(int id); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void deleteMaintenanceEventsForDataSource(int dataSourceId); +} diff --git a/src/org/scada_lts/dao/IPendingEventsDAO.java b/src/org/scada_lts/dao/IPendingEventsDAO.java new file mode 100644 index 0000000000..780207be5c --- /dev/null +++ b/src/org/scada_lts/dao/IPendingEventsDAO.java @@ -0,0 +1,17 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.rt.event.EventInstance; +import com.serotonin.mango.rt.event.type.AlarmLevelType; +import com.serotonin.mango.vo.UserComment; + +import java.util.List; +import java.util.Map; + +public interface IPendingEventsDAO { + + List getPendingEvents(int userId, Map> commentsMap, + AlarmLevelType alarmLevel); + + List getPendingEvents(int userId, Map> commentsMap, + AlarmLevelType alarmLevel, int offset, int limit); +} diff --git a/src/org/scada_lts/dao/IPointLinkDAO.java b/src/org/scada_lts/dao/IPointLinkDAO.java new file mode 100644 index 0000000000..7563ee87ed --- /dev/null +++ b/src/org/scada_lts/dao/IPointLinkDAO.java @@ -0,0 +1,28 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.vo.link.PointLinkVO; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IPointLinkDAO { + PointLinkVO getPointLink(int id); + + PointLinkVO getPointLink(String xid); + + List getPointLinks(); + + List getPointLinksForPoint(int datapointId); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(PointLinkVO pointLink); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void update(PointLinkVO pointLink); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void delete(int id); +} diff --git a/src/org/scada_lts/dao/IPublisherDAO.java b/src/org/scada_lts/dao/IPublisherDAO.java new file mode 100644 index 0000000000..72fb84366b --- /dev/null +++ b/src/org/scada_lts/dao/IPublisherDAO.java @@ -0,0 +1,27 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.vo.publish.PublishedPointVO; +import com.serotonin.mango.vo.publish.PublisherVO; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IPublisherDAO { + PublisherVO getPublisher(int id); + + PublisherVO getPublisher(String xid); + + List> getPublishers(); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(PublisherVO publisher); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void update(PublisherVO publisher); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void delete(int id); +} diff --git a/src/org/scada_lts/dao/IScheduledEventDAO.java b/src/org/scada_lts/dao/IScheduledEventDAO.java new file mode 100644 index 0000000000..4a79efcef6 --- /dev/null +++ b/src/org/scada_lts/dao/IScheduledEventDAO.java @@ -0,0 +1,26 @@ +package org.scada_lts.dao; + +import com.serotonin.mango.vo.event.ScheduledEventVO; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IScheduledEventDAO { + ScheduledEventVO getScheduledEvent(int id); + + ScheduledEventVO getScheduledEvent(String xid); + + List getScheduledEvents(); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(ScheduledEventVO scheduledEventVO); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void update(ScheduledEventVO scheduledEventVO); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void delete(int id); +} diff --git a/src/org/scada_lts/dao/IScriptDAO.java b/src/org/scada_lts/dao/IScriptDAO.java new file mode 100644 index 0000000000..ecd319d61c --- /dev/null +++ b/src/org/scada_lts/dao/IScriptDAO.java @@ -0,0 +1,33 @@ +package org.scada_lts.dao; + +import br.org.scadabr.vo.scripting.ScriptVO; +import org.scada_lts.web.mvc.api.json.JsonScript; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IScriptDAO { + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + int insert(ScriptVO vo); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void update(ScriptVO vo); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void delete(int id); + + ScriptVO getScript(int id); + + List> getScripts(); + + ScriptVO getScript(String xid); + + String generateUniqueXid(); + + boolean isXidUnique(String xid, int excludeId); + + JsonScript findScriptsByPage(String query); +} diff --git a/src/org/scada_lts/dao/ISynopticPanelDAO.java b/src/org/scada_lts/dao/ISynopticPanelDAO.java new file mode 100644 index 0000000000..81ea89ad49 --- /dev/null +++ b/src/org/scada_lts/dao/ISynopticPanelDAO.java @@ -0,0 +1,21 @@ +package org.scada_lts.dao; + +import org.scada_lts.dao.model.ScadaObjectIdentifier; +import org.scada_lts.service.model.SynopticPanel; +import org.springframework.dao.EmptyResultDataAccessException; + +import java.util.List; + +public interface ISynopticPanelDAO extends CrudOperations { + SynopticPanel create(SynopticPanel entity); + + List getSimpleList(); + + List getAll(); + + SynopticPanel getById(int id) throws EmptyResultDataAccessException; + + SynopticPanel update(SynopticPanel entity); + + int delete(int id); +} diff --git a/src/org/scada_lts/dao/ISystemSettingsDAO.java b/src/org/scada_lts/dao/ISystemSettingsDAO.java new file mode 100644 index 0000000000..357aca1e5c --- /dev/null +++ b/src/org/scada_lts/dao/ISystemSettingsDAO.java @@ -0,0 +1,12 @@ +package org.scada_lts.dao; + +public interface ISystemSettingsDAO { + public abstract void setValue(java.lang.String arg0, java.lang.String arg1); + public abstract void setIntValue(java.lang.String arg0, int arg1); + public abstract void setBooleanValue(java.lang.String arg0, boolean arg1); + public abstract void removeValue(java.lang.String arg0); + public abstract java.lang.String getDatabaseSchemaVersion(java.lang.String arg0, java.lang.String arg1); + public abstract void resetDataBase(); + public abstract double getDataBaseSize(); +} + diff --git a/src/org/scada_lts/dao/IUsersProfileDAO.java b/src/org/scada_lts/dao/IUsersProfileDAO.java index 0af7bda2bd..a9fe1827f4 100644 --- a/src/org/scada_lts/dao/IUsersProfileDAO.java +++ b/src/org/scada_lts/dao/IUsersProfileDAO.java @@ -12,6 +12,8 @@ @Component public interface IUsersProfileDAO extends GenerateXid { + String generateUniqueXid(String prefix); + Optional selectProfileById(int profileId); Optional selectProfileByXid(String profileXid); diff --git a/src/org/scada_lts/dao/IViewDAO.java b/src/org/scada_lts/dao/IViewDAO.java index 7b63908db0..228344b9ac 100644 --- a/src/org/scada_lts/dao/IViewDAO.java +++ b/src/org/scada_lts/dao/IViewDAO.java @@ -3,6 +3,7 @@ import br.org.scadabr.vo.permission.ViewAccess; import com.serotonin.mango.view.ShareUser; import com.serotonin.mango.view.View; +import org.scada_lts.dao.model.BaseObjectIdentifier; import org.scada_lts.dao.model.ScadaObjectIdentifier; import java.util.List; @@ -11,10 +12,34 @@ public interface IViewDAO extends ScadaRepository { default void init() {} - View findByName(String name); + List findAll(); + + List filtered(String filter, String order, Object[] argsFilter, long limit); + + void update(View entity); + + void delete(View entity); + + void deleteViewForUser(int viewId); void deleteViewForUser(int viewId, int userId); + void batchUpdateInfoUsers(View view); + + List findIdentifiers(); + + List findBaseIdentifiers(); + + View save(View entity); + + void delete(Integer id); + + View findById(Integer id); + + View findByName(String name); + + View findByXid(String xid); + List selectViewIdentifiersWithAccess(int userId, int profileId); List selectViewWithAccess(int userId, int profileId); diff --git a/src/org/scada_lts/dao/IViewHierarchyDAO.java b/src/org/scada_lts/dao/IViewHierarchyDAO.java new file mode 100644 index 0000000000..cfd73406c4 --- /dev/null +++ b/src/org/scada_lts/dao/IViewHierarchyDAO.java @@ -0,0 +1,28 @@ +package org.scada_lts.dao; + +import org.scada_lts.dao.model.viewshierarchy.ViewHierarchyNode; +import org.scada_lts.dao.model.viewshierarchy.ViewInViewHierarchyNode; + +import java.util.List; + +public interface IViewHierarchyDAO extends GenericHierarchyDAO { + int ROOT_ID = -1; + + List getAll(); + + List getNode(long l); + + List getViewInHierarchyNode(); + + int add(ViewHierarchyNode node); + + int update(ViewHierarchyNode node); + + int moveFolder(int id, int newParentId); + + int moveView(int id, int newParentId); + + int delView(int id); + + int delFolder(int id); +} diff --git a/src/org/scada_lts/dao/MaintenanceEventDAO.java b/src/org/scada_lts/dao/MaintenanceEventDAO.java index 36e4d37dc5..f543256c40 100644 --- a/src/org/scada_lts/dao/MaintenanceEventDAO.java +++ b/src/org/scada_lts/dao/MaintenanceEventDAO.java @@ -44,7 +44,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class MaintenanceEventDAO { +public class MaintenanceEventDAO implements IMaintenanceEventDAO { private static final Log LOG = LogFactory.getLog(MaintenanceEventDAO.class); @@ -207,6 +207,7 @@ public MaintenanceEventVO mapRow(ResultSet rs, int rowNum) throws SQLException { } } + @Override public MaintenanceEventVO getMaintenanceEvent(int id) { if (LOG.isTraceEnabled()) { @@ -219,6 +220,7 @@ public MaintenanceEventVO getMaintenanceEvent(int id) { } + @Override public MaintenanceEventVO getMaintenanceEvent(String xid) { if (LOG.isTraceEnabled()) { @@ -236,6 +238,7 @@ public MaintenanceEventVO getMaintenanceEvent(String xid) { return maintenanceEvent; } + @Override public List getMaintenanceEvents() { if (LOG.isTraceEnabled()) { @@ -245,7 +248,8 @@ public List getMaintenanceEvents() { return DAO.getInstance().getJdbcTemp().query(MAINTENANCE_EVENT_SELECT, new MaintenanceEventRowMapper()); } - @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) + @Override + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) public int insert(final MaintenanceEventVO maintenanceEvent) { if (LOG.isTraceEnabled()) { @@ -279,7 +283,6 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S maintenanceEvent.getInactiveMinute(), maintenanceEvent.getInactiveSecond(), maintenanceEvent.getInactiveCron() - }).setValues(ps); return ps; } @@ -288,7 +291,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return keyHolder.getKey().intValue(); } - @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 update(MaintenanceEventVO maintenanceEvent) { if (LOG.isTraceEnabled()) { @@ -322,7 +326,8 @@ public void update(MaintenanceEventVO maintenanceEvent) { ); } - @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 delete(int id) { if (LOG.isTraceEnabled()) { @@ -336,7 +341,8 @@ public void 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 deleteMaintenanceEventsForDataSource(int dataSourceId) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/PendingEventsDAO.java b/src/org/scada_lts/dao/PendingEventsDAO.java index b77b7c2d7b..ebbc3b8fda 100644 --- a/src/org/scada_lts/dao/PendingEventsDAO.java +++ b/src/org/scada_lts/dao/PendingEventsDAO.java @@ -41,7 +41,7 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * person supporting and coreecting translation Jerzy Piejko */ -public class PendingEventsDAO { +public class PendingEventsDAO implements IPendingEventsDAO { private static final Log LOG = LogFactory.getLog(PendingEventsDAO.class); diff --git a/src/org/scada_lts/dao/PointLinkDAO.java b/src/org/scada_lts/dao/PointLinkDAO.java index 3fedf6c86f..3a6e3874ae 100644 --- a/src/org/scada_lts/dao/PointLinkDAO.java +++ b/src/org/scada_lts/dao/PointLinkDAO.java @@ -17,23 +17,16 @@ */ package org.scada_lts.dao; -import java.sql.Statement; import com.serotonin.mango.vo.link.PointLinkVO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; -import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @@ -44,7 +37,7 @@ * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ @Repository -public class PointLinkDAO { +public class PointLinkDAO implements IPointLinkDAO { private static final Log LOG = LogFactory.getLog(PointLinkDAO.class); @@ -78,7 +71,7 @@ public class PointLinkDAO { + COLUMN_NAME_EVENT_TYPE + ", " + COLUMN_NAME_DISABLED + ") " - + "values (?,?,?,?,?,?) "; + + "values (?,?,?,?,?,?) RETURNING id"; private static final String POINT_LINK_UPDATE = "" + "update pointLinks set " @@ -121,6 +114,7 @@ public PointLinkVO mapRow(ResultSet rs, int rowNum) throws SQLException { } } + @Override public PointLinkVO getPointLink(int id) { if (LOG.isTraceEnabled()) { @@ -138,6 +132,7 @@ public PointLinkVO getPointLink(int id) { return pointLinkVO; } + @Override public PointLinkVO getPointLink(String xid) { if (LOG.isTraceEnabled()) { @@ -155,6 +150,7 @@ public PointLinkVO getPointLink(String xid) { return pointLinkVO; } + @Override public List getPointLinks() { if (LOG.isTraceEnabled()) { @@ -164,6 +160,7 @@ public List getPointLinks() { return DAO.getInstance().getJdbcTemp().query(POINT_LINK_SELECT, new PointLinkRowMapper()); } + @Override public List getPointLinksForPoint(int datapointId) { if (LOG.isTraceEnabled()) { @@ -173,35 +170,30 @@ public List getPointLinksForPoint(int datapointId) { return DAO.getInstance().getJdbcTemp().query(POINT_LINK_SELECT_WHERE, new Object[]{datapointId, datapointId}, new PointLinkRowMapper()); } - @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 PointLinkVO pointLink) { if (LOG.isTraceEnabled()) { LOG.trace("insertPointLink(PointLinkVO pointLink) pointLink:" + pointLink.toString()); } - KeyHolder keyHolder = new GeneratedKeyHolder(); - - DAO.getInstance().getJdbcTemp().update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { - PreparedStatement ps = connection.prepareStatement(POINT_LINK_INSERT, Statement.RETURN_GENERATED_KEYS); - new ArgumentPreparedStatementSetter(new Object[] { - pointLink.getXid(), - pointLink.getSourcePointId(), - pointLink.getTargetPointId(), - pointLink.getScript(), - pointLink.getEvent(), - DAO.boolToChar(pointLink.isDisabled())} - ).setValues(ps); - return ps; - } - }, keyHolder); - - return keyHolder.getKey().intValue(); + return DAO.getInstance().getJdbcTemp().queryForObject( + POINT_LINK_INSERT, + new Object[]{ + pointLink.getXid(), + pointLink.getSourcePointId(), + pointLink.getTargetPointId(), + pointLink.getScript(), + pointLink.getEvent(), + DAO.boolToChar(pointLink.isDisabled()) + }, + 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 void update(PointLinkVO pointLink) { if (LOG.isTraceEnabled()) { @@ -219,7 +211,8 @@ public void update(PointLinkVO pointLink) { }); } - @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 delete(int id) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/PublisherDAO.java b/src/org/scada_lts/dao/PublisherDAO.java index 0ac8819129..ca75e42c8f 100644 --- a/src/org/scada_lts/dao/PublisherDAO.java +++ b/src/org/scada_lts/dao/PublisherDAO.java @@ -37,8 +37,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.Collections; -import java.util.Comparator; import java.util.List; /** @@ -46,7 +44,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class PublisherDAO { +public class PublisherDAO implements IPublisherDAO { private static final Log LOG = LogFactory.getLog(PublisherDAO.class); @@ -101,6 +99,7 @@ public PublisherVO mapRow(ResultSet rs, int rowNum) } } + @Override public PublisherVO getPublisher(int id) { if (LOG.isTraceEnabled()) { @@ -118,6 +117,7 @@ public PublisherVO getPublisher(int id) { return publisher; } + @Override public PublisherVO getPublisher(String xid) { if (LOG.isTraceEnabled()) { @@ -135,6 +135,7 @@ public PublisherVO getPublisher(String xid) { return publisher; } + @Override public List> getPublishers() { if (LOG.isTraceEnabled()) { @@ -144,7 +145,8 @@ public List> getPublishers() { return DAO.getInstance().getJdbcTemp().query(PUBLISHER_SELECT, new PublisherRowMapper()); } - @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 PublisherVO publisher) { if (LOG.isTraceEnabled()) { @@ -164,7 +166,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return keyHolder.getKey().intValue(); } - @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 update(PublisherVO publisher) { if (LOG.isTraceEnabled()) { @@ -174,7 +177,8 @@ public void update(PublisherVO publisher) { DAO.getInstance().getJdbcTemp().update(PUBLISHER_UPDATE, new Object[] {publisher.getXid(), new SerializationData().writeObject(publisher), publisher.getId()}); } - @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 delete(int id) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/ScheduledEventDAO.java b/src/org/scada_lts/dao/ScheduledEventDAO.java index 0f36cacc2d..16334f0ff2 100644 --- a/src/org/scada_lts/dao/ScheduledEventDAO.java +++ b/src/org/scada_lts/dao/ScheduledEventDAO.java @@ -45,7 +45,7 @@ * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class ScheduledEventDAO { +public class ScheduledEventDAO implements IScheduledEventDAO { private static final Log LOG = LogFactory.getLog(ScheduledEventDAO.class); @@ -185,6 +185,7 @@ public ScheduledEventVO mapRow(ResultSet rs, int rowNum) throws SQLException { } } + @Override public ScheduledEventVO getScheduledEvent(int id) { if (LOG.isTraceEnabled()) { @@ -197,6 +198,7 @@ public ScheduledEventVO getScheduledEvent(int id) { } + @Override public ScheduledEventVO getScheduledEvent(String xid) { if (LOG.isTraceEnabled()) { @@ -214,6 +216,7 @@ public ScheduledEventVO getScheduledEvent(String xid) { return scheduledEvent; } + @Override public List getScheduledEvents() { if (LOG.isTraceEnabled()) { @@ -225,7 +228,8 @@ public List getScheduledEvents() { return DAO.getInstance().getJdbcTemp().query(templateSelectedOrderBy, new ScheduledEventRowMapper()); } - @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 ScheduledEventVO scheduledEventVO) { if (LOG.isTraceEnabled()) { @@ -267,7 +271,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return keyHolder.getKey().intValue(); } - @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 update(ScheduledEventVO scheduledEventVO) { if (LOG.isTraceEnabled()) { @@ -301,7 +306,8 @@ public void update(ScheduledEventVO scheduledEventVO) { ); } - @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 delete(int id) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/ScriptDAO.java b/src/org/scada_lts/dao/ScriptDAO.java index 4d1ea181b0..59a8dc8a79 100644 --- a/src/org/scada_lts/dao/ScriptDAO.java +++ b/src/org/scada_lts/dao/ScriptDAO.java @@ -45,7 +45,7 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ -public class ScriptDAO { +public class ScriptDAO implements IScriptDAO { private static final Log LOG = LogFactory.getLog(ScriptDAO.class); @@ -123,35 +123,37 @@ public ScriptVO mapRow(ResultSet rs, int rowNum) throws SQLException { } } - @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 ScriptVO vo) { if (LOG.isTraceEnabled()) { LOG.trace(vo); } - + KeyHolder keyHolder = new GeneratedKeyHolder(); - + DAO.getInstance().getJdbcTemp().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(SCRIPT_INSERT, Statement.RETURN_GENERATED_KEYS); - new ArgumentPreparedStatementSetter( new Object[] { - vo.getXid(), - vo.getName(), - vo.getScript(), + new ArgumentPreparedStatementSetter( new Object[] { + vo.getXid(), + vo.getName(), + vo.getScript(), vo.getUserId(), new SerializationData().writeObject(vo) }).setValues(ps); return ps; } }, keyHolder); - + return keyHolder.getKey().intValue(); - + } - @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 update(final ScriptVO vo) { if (LOG.isTraceEnabled()) { @@ -167,7 +169,8 @@ public void update(final ScriptVO vo) { vo.getId() }); } - @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 delete(final int id) { if (LOG.isTraceEnabled()) { @@ -178,6 +181,7 @@ public void delete(final int id) { } + @Override public ScriptVO getScript(int id) { try { return DAO.getInstance().getJdbcTemp().queryForObject(SCRIPT_SELECT_ONE, new Object[]{id}, new ScriptRowMapper()); @@ -186,10 +190,12 @@ public ScriptVO getScript(int id) { } } + @Override public List> getScripts() { return (List>) DAO.getInstance().getJdbcTemp().query(SCRIPT_SELECT, new Object[]{ }, new ScriptRowMapper()); } + @Override public ScriptVO getScript(String xid) { try { return DAO.getInstance().getJdbcTemp().queryForObject(SCRIPT_SELECT_BASE_ON_XID, new Object[]{ @@ -199,14 +205,17 @@ public ScriptVO getScript(String xid) { } } + @Override public String generateUniqueXid() { return DAO.getInstance().generateUniqueXid(ScriptVO.XID_PREFIX, "scripts"); } + @Override public boolean isXidUnique(String xid, int excludeId) { return DAO.getInstance().isXidUnique(xid, excludeId, "scripts"); } + @Override public JsonScript findScriptsByPage(String query) { return (JsonScript) DAO.getInstance().getJdbcTemp().query(SCRIPT_SELECT + " ", new Object[]{ }, new ScriptRowMapper()); } diff --git a/src/org/scada_lts/dao/SynopticPanelDAO.java b/src/org/scada_lts/dao/SynopticPanelDAO.java index e800b660e5..dfdac669ed 100644 --- a/src/org/scada_lts/dao/SynopticPanelDAO.java +++ b/src/org/scada_lts/dao/SynopticPanelDAO.java @@ -25,7 +25,7 @@ * @version 1.0.0 */ @Repository -public class SynopticPanelDAO implements CrudOperations { +public class SynopticPanelDAO implements ISynopticPanelDAO { private static final Log LOG = LogFactory.getLog(SynopticPanelDAO.class); diff --git a/src/org/scada_lts/dao/SystemSettingsDAO.java b/src/org/scada_lts/dao/SystemSettingsDAO.java index b3c451725a..35b84f2cae 100644 --- a/src/org/scada_lts/dao/SystemSettingsDAO.java +++ b/src/org/scada_lts/dao/SystemSettingsDAO.java @@ -47,7 +47,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class SystemSettingsDAO { +public class SystemSettingsDAO implements ISystemSettingsDAO { // Database schema version public static final String DATABASE_SCHEMA_VERSION = "databaseSchemaVersion"; @@ -190,7 +190,6 @@ public class SystemSettingsDAO { private static final String DATABASE_SIZE = "" + "select sum(data_length + index_length) /1024 /1024 \"size\" " + "from information_schema.TABLES where table_schema="; - private static final String DATABASE_STATEMENT = "DATABASE()"; private static final String SELECT_DATABASE = "" + "select " @@ -487,7 +486,7 @@ public double getDataBaseSize() { e.printStackTrace(); } - return size.get(0); + return size.isEmpty() ? -1d : size.get(0); } public static R getObject(String key, Function convert) { diff --git a/src/org/scada_lts/dao/ViewHierarchyDAO.java b/src/org/scada_lts/dao/ViewHierarchyDAO.java index 36dc065c20..555cd42d67 100644 --- a/src/org/scada_lts/dao/ViewHierarchyDAO.java +++ b/src/org/scada_lts/dao/ViewHierarchyDAO.java @@ -35,7 +35,7 @@ * @author Grzesiek Bylica grzegorz.bylica@gmail.com */ @Repository -public class ViewHierarchyDAO implements GenericHierarchyDAO { +public class ViewHierarchyDAO implements IViewHierarchyDAO { private static final Log LOG = LogFactory.getLog(ViewHierarchyDAO.class); @@ -109,6 +109,7 @@ public ViewInViewHierarchyNode mapRow(ResultSet rs, int rowNum) throws SQLExcept * Return nodes for hierarchy views * @return */ + @Override public List getAll() { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -127,6 +128,7 @@ public List getAll() { * Return one node for hierarchy views * @return */ + @Override public List getNode(long l) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -145,6 +147,7 @@ public List getNode(long l) { * * @return */ + @Override public List getViewInHierarchyNode() { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -161,6 +164,7 @@ public List getViewInHierarchyNode() { /** * Add node for hierarchy views */ + @Override public int add(ViewHierarchyNode node) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -175,6 +179,7 @@ public int add(ViewHierarchyNode node) { * @return * @return */ + @Override public int update(ViewHierarchyNode node) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -194,6 +199,7 @@ public int update(ViewHierarchyNode node) { * @return * @return */ + @Override public int moveFolder(int id, int newParentId) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -212,6 +218,7 @@ public int moveFolder(int id, int newParentId) { * @return * @return */ + @Override public int moveView(int id, int newParentId) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -230,6 +237,7 @@ public int moveView(int id, int newParentId) { * @return * @return */ + @Override public int delView(int id) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); @@ -248,6 +256,7 @@ public int delView(int id) { * @return * @return */ + @Override public int delFolder(int id) { if (LOG.isTraceEnabled()) { LOG.trace("SQL ViewHierarchyDAO"); diff --git a/src/org/scada_lts/dao/alarms/AlarmsService.java b/src/org/scada_lts/dao/alarms/AlarmsService.java index ea402031af..de462b3e06 100644 --- a/src/org/scada_lts/dao/alarms/AlarmsService.java +++ b/src/org/scada_lts/dao/alarms/AlarmsService.java @@ -40,6 +40,6 @@ public interface AlarmsService { @Deprecated static AlarmsService plcAlarmsService() { - return new PlcAlarmsService(AlarmsDAO.getInstance(), new DataPointService()); + return new PlcAlarmsService(IAlarmsDAO.getInstance(), new DataPointService()); } } diff --git a/src/org/scada_lts/dao/alarms/AlarmsDAO.java b/src/org/scada_lts/dao/alarms/IAlarmsDAO.java similarity index 88% rename from src/org/scada_lts/dao/alarms/AlarmsDAO.java rename to src/org/scada_lts/dao/alarms/IAlarmsDAO.java index bca0edd71b..ec1a54f1b5 100644 --- a/src/org/scada_lts/dao/alarms/AlarmsDAO.java +++ b/src/org/scada_lts/dao/alarms/IAlarmsDAO.java @@ -18,7 +18,7 @@ package org.scada_lts.dao.alarms; -import org.scada_lts.dao.DAO; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.dao.DataAccessException; import java.util.List; @@ -32,14 +32,14 @@ * */ -public interface AlarmsDAO { +public interface IAlarmsDAO { List getLiveAlarms(int offset, int limit) throws DataAccessException; List getHistoryAlarms(String dayDate, String regex, int offset, int limit) throws DataAccessException; boolean setAcknowledgeTime(int id) throws DataAccessException; Optional getInactiveTimeMs(int id) throws DataAccessException; - static AlarmsDAO getInstance() { - return new PlcAlarmsDAO(); + static IAlarmsDAO getInstance() { + return ApplicationBeans.getAlarmsDAOBean(); } } diff --git a/src/org/scada_lts/dao/alarms/PlcAlarmsDAO.java b/src/org/scada_lts/dao/alarms/PlcAlarmsDAO.java index 7f307b3dad..4b81900874 100644 --- a/src/org/scada_lts/dao/alarms/PlcAlarmsDAO.java +++ b/src/org/scada_lts/dao/alarms/PlcAlarmsDAO.java @@ -37,7 +37,7 @@ * */ -class PlcAlarmsDAO implements AlarmsDAO { +class PlcAlarmsDAO implements IAlarmsDAO { private static final Log LOG = LogFactory.getLog(PlcAlarmsDAO.class); diff --git a/src/org/scada_lts/dao/alarms/PlcAlarmsService.java b/src/org/scada_lts/dao/alarms/PlcAlarmsService.java index d6132f65f1..fea18e7788 100644 --- a/src/org/scada_lts/dao/alarms/PlcAlarmsService.java +++ b/src/org/scada_lts/dao/alarms/PlcAlarmsService.java @@ -39,10 +39,10 @@ class PlcAlarmsService implements AlarmsService { private static final Log LOG = LogFactory.getLog(PlcAlarmsService.class); - private final AlarmsDAO alarmsDAO; + private final IAlarmsDAO alarmsDAO; private final DataPointService dataPointService; - public PlcAlarmsService(AlarmsDAO alarmsDAO, DataPointService dataPointService) { + public PlcAlarmsService(IAlarmsDAO alarmsDAO, DataPointService dataPointService) { this.alarmsDAO = alarmsDAO; this.dataPointService = dataPointService; } diff --git a/src/org/scada_lts/dao/cache/PointEventDetectorCache.java b/src/org/scada_lts/dao/cache/PointEventDetectorCache.java index 28fbeebb5d..ec15ca2ec6 100644 --- a/src/org/scada_lts/dao/cache/PointEventDetectorCache.java +++ b/src/org/scada_lts/dao/cache/PointEventDetectorCache.java @@ -4,7 +4,7 @@ import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.event.PointEventDetectorVO; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.PointEventDetectorDAO; +import org.scada_lts.dao.IPointEventDetectorDAO; import java.util.List; @@ -12,9 +12,9 @@ public class PointEventDetectorCache implements PointEventDetectorCacheable { private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(PointEventDetectorCache.class); - private final PointEventDetectorDAO pointEventDetectorDAO; + private final IPointEventDetectorDAO pointEventDetectorDAO; - public PointEventDetectorCache(PointEventDetectorDAO pointEventDetectorDAO) { + public PointEventDetectorCache(IPointEventDetectorDAO pointEventDetectorDAO) { this.pointEventDetectorDAO = pointEventDetectorDAO; } diff --git a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java index 0f2d1c7c7c..246933edfc 100644 --- a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java @@ -3,9 +3,8 @@ import com.serotonin.mango.Common; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.event.PointEventDetectorVO; -import org.scada_lts.dao.DataPointDAO; -import org.scada_lts.dao.IPointEventDetectorDAO; -import org.scada_lts.dao.PointEventDetectorDAO; +import org.scada_lts.dao.*; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.ArrayList; import java.util.List; @@ -22,7 +21,8 @@ public PointEventDetectorDaoWithCache(PointEventDetectorCacheable pointEventDete @Override public void init() { - List dataPoints = new DataPointDAO().getDataPoints(); + IDataPointDAO dao = ApplicationBeans.getDataPointDAOBean(); + List dataPoints = dao.getDataPoints(); Map> pointEventDetectors = new PointEventDetectorDAO() .getPointEventDetectors(Integer.MAX_VALUE, 0) .stream() @@ -47,6 +47,25 @@ public List getPointEventDetectors(DataPointVO dataPoint) .collect(Collectors.toList()); } + @Override + @Deprecated + public int getId(String pointEventDetectorXid, int dataPointId) { + PointEventDetectorVO pointEventDetectorVO = pointEventDetectorCache.selectPointEventDetector(pointEventDetectorXid, dataPointId); + return pointEventDetectorVO == null ? -1 : pointEventDetectorVO.getId(); + } + + @Override + @Deprecated + public String getXid(int pointEventDetectorId) { + PointEventDetectorVO pointEventDetectorVO = pointEventDetectorCache.selectPointEventDetector(pointEventDetectorId); + return pointEventDetectorVO == null ? null : pointEventDetectorVO.getXid(); + } + + @Override + public List getPointEventDetectors(long limit, int offset) { + return new PointEventDetectorDAO().getPointEventDetectors(limit, offset); + } + @Override public boolean isEventDetectorXidUnique(int dataPointId, String xid, int excludeId) { PointEventDetectorVO pointEventDetectorVO = pointEventDetectorCache.selectPointEventDetector(xid, dataPointId); diff --git a/src/org/scada_lts/dao/cache/UserCache.java b/src/org/scada_lts/dao/cache/UserCache.java index 2cdb5a5aaa..8d98e02fa3 100644 --- a/src/org/scada_lts/dao/cache/UserCache.java +++ b/src/org/scada_lts/dao/cache/UserCache.java @@ -1,15 +1,15 @@ package org.scada_lts.dao.cache; import com.serotonin.mango.vo.User; -import org.scada_lts.dao.UserDAO; +import org.scada_lts.dao.IUserDAO; import java.util.List; public class UserCache implements UserCacheable { - private final UserDAO userDAO; + private final IUserDAO userDAO; - public UserCache(UserDAO userDAO) { + public UserCache(IUserDAO userDAO) { this.userDAO = userDAO; } diff --git a/src/org/scada_lts/dao/cache/UserCommentCache.java b/src/org/scada_lts/dao/cache/UserCommentCache.java index 75b6f7deb7..f178432e9b 100644 --- a/src/org/scada_lts/dao/cache/UserCommentCache.java +++ b/src/org/scada_lts/dao/cache/UserCommentCache.java @@ -3,15 +3,15 @@ import com.serotonin.mango.rt.event.EventInstance; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.UserComment; -import org.scada_lts.dao.UserCommentDAO; +import org.scada_lts.dao.IUserCommentDAO; import java.util.List; public class UserCommentCache implements UserCommentCacheable { - private final UserCommentDAO userCommentDAO; + private final IUserCommentDAO userCommentDAO; - public UserCommentCache(UserCommentDAO userCommentDAO) { + public UserCommentCache(IUserCommentDAO userCommentDAO) { this.userCommentDAO = userCommentDAO; } diff --git a/src/org/scada_lts/dao/cache/UserCommentDaoWithCache.java b/src/org/scada_lts/dao/cache/UserCommentDaoWithCache.java index cd8a370cd2..4d25134107 100644 --- a/src/org/scada_lts/dao/cache/UserCommentDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/UserCommentDaoWithCache.java @@ -4,7 +4,6 @@ import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.UserComment; import org.scada_lts.dao.IUserCommentDAO; -import org.scada_lts.dao.UserCommentDAO; import java.util.*; import java.util.stream.Collectors; @@ -12,9 +11,9 @@ public class UserCommentDaoWithCache implements IUserCommentDAO { public final UserCommentCacheable cache; - public final UserCommentDAO userCommentDAO; + public final IUserCommentDAO userCommentDAO; - public UserCommentDaoWithCache(UserCommentCacheable cache, UserCommentDAO userCommentDAO) { + public UserCommentDaoWithCache(UserCommentCacheable cache, IUserCommentDAO userCommentDAO) { this.cache = cache; this.userCommentDAO = userCommentDAO; } diff --git a/src/org/scada_lts/dao/cache/UsersProfileCache.java b/src/org/scada_lts/dao/cache/UsersProfileCache.java index 8065b82488..2fe279ed57 100644 --- a/src/org/scada_lts/dao/cache/UsersProfileCache.java +++ b/src/org/scada_lts/dao/cache/UsersProfileCache.java @@ -4,15 +4,15 @@ import br.org.scadabr.vo.permission.WatchListAccess; import br.org.scadabr.vo.usersProfiles.UsersProfileVO; import com.serotonin.mango.vo.permission.DataPointAccess; -import org.scada_lts.dao.UsersProfileDAO; +import org.scada_lts.dao.IUsersProfileDAO; import java.util.List; public class UsersProfileCache implements UsersProfileCacheable { - private final UsersProfileDAO usersProfileDAO; + private final IUsersProfileDAO usersProfileDAO; - public UsersProfileCache(UsersProfileDAO usersProfileDAO) { + public UsersProfileCache(IUsersProfileDAO usersProfileDAO) { this.usersProfileDAO = usersProfileDAO; } diff --git a/src/org/scada_lts/dao/cache/ViewCache.java b/src/org/scada_lts/dao/cache/ViewCache.java index 81fc543901..c67b2490bc 100644 --- a/src/org/scada_lts/dao/cache/ViewCache.java +++ b/src/org/scada_lts/dao/cache/ViewCache.java @@ -5,18 +5,17 @@ import com.serotonin.mango.view.ShareUser; import com.serotonin.mango.view.View; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.ViewDAO; +import org.scada_lts.dao.IViewDAO; import org.scada_lts.dao.model.BaseObjectIdentifier; -import org.scada_lts.dao.model.ScadaObjectIdentifier; import java.util.List; public class ViewCache implements ViewCacheable { private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(ViewCache.class); - private final ViewDAO viewDAO; + private final IViewDAO viewDAO; - public ViewCache(ViewDAO viewDAO) { + public ViewCache(IViewDAO viewDAO) { this.viewDAO = viewDAO; } diff --git a/src/org/scada_lts/dao/cache/ViewDaoWithCache.java b/src/org/scada_lts/dao/cache/ViewDaoWithCache.java index 33330cf271..57ff753956 100644 --- a/src/org/scada_lts/dao/cache/ViewDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/ViewDaoWithCache.java @@ -6,11 +6,11 @@ import com.serotonin.mango.view.View; import com.serotonin.mango.vo.User; import org.scada_lts.dao.IViewDAO; -import org.scada_lts.dao.ViewDAO; import org.scada_lts.dao.model.BaseObjectIdentifier; import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.permissions.service.GetViewsWithAccess; import org.scada_lts.permissions.service.ViewGetShareUsers; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.ArrayList; import java.util.List; @@ -26,13 +26,19 @@ public ViewDaoWithCache(ViewCacheable viewCache) { @Override public void init() { - List views = new ViewDAO().findAll(); + IViewDAO viewDao = ApplicationBeans.getBean("viewDAO", IViewDAO.class); + List views = viewDao.findAll(); for(View view: views) { applyShareUsers(view); viewCache.put(view); } } + @Override + public List filtered(String filter, String order, Object[] argsFilter, long limit) { + return ApplicationBeans.getBean("viewDAO", IViewDAO.class).filtered(filter, order, argsFilter, limit); + } + @Override public View save(View view) { return viewCache.save(view); @@ -43,6 +49,13 @@ public void update(View view) { viewCache.update(view); } + @Override + public void delete(View entity) { + if (entity != null) { + delete(entity.getId()); + } + } + @Override public void delete(Integer id) { viewCache.delete(id); @@ -62,6 +75,11 @@ public List findAll() { return views; } + @Override + public void batchUpdateInfoUsers(View view) { + ApplicationBeans.getBean("viewDAO", IViewDAO.class).batchUpdateInfoUsers(view); + } + @Override public List selectViewPermissions(int userId) { return viewCache.selectViewPermissions(userId); @@ -146,6 +164,11 @@ public List selectViewWithAccess(int userId, int profileId) { .collect(Collectors.toList()); } + @Override + public void deleteViewForUser(int viewId) { + ApplicationBeans.getBean("viewDAO", IViewDAO.class).deleteViewForUser(viewId); + } + @Override public void deleteViewForUser(int viewId, int userId) { viewCache.deleteViewForUser(viewId, userId); diff --git a/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java b/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java index 48a7bcfdf1..614099b5c6 100644 --- a/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java +++ b/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java @@ -46,7 +46,7 @@ /** * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu */ -public class CompoundEventDetectorDAO implements GenericDAO { +public class CompoundEventDetectorDAO implements ICompoundEventDetectorDAO { private Log LOG = LogFactory.getLog(CompoundEventDetectorDAO.class); @@ -147,6 +147,7 @@ public CompoundEventDetectorVO findById(Object[] pk) { } } + @Override public CompoundEventDetectorVO findByXId(Object[] pk) { try { return (CompoundEventDetectorVO) DAO.getInstance().getJdbcTemp().queryForObject(COMPOUND_EVENT_DETECTOR_SELECT+ " where " + COMPOUND_EVENT_DETECTOR_FILTERED_BASE_ON_XID, pk , new CompoundEventDetectorRowMapper()); @@ -169,7 +170,7 @@ public List filtered(String filter, Object[] argsFilter return (List) DAO.getInstance().getJdbcTemp().query(COMPOUND_EVENT_DETECTOR_SELECT+" where "+ filter + myLimit, args, new CompoundEventDetectorRowMapper()); } - @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 Object[] create(final CompoundEventDetectorVO entity) { if (LOG.isTraceEnabled()) { @@ -198,7 +199,7 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return new Object[] {keyHolder.getKey().intValue()}; } - @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 update(CompoundEventDetectorVO entity) { @@ -213,7 +214,7 @@ public void update(CompoundEventDetectorVO entity) { }); } - @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 delete(CompoundEventDetectorVO entity) { DAO.getInstance().getJdbcTemp().update(COMPOUND_EVENT_DELETE_EVENT_HANLDERS,new Object[]{entity.getId()}); diff --git a/src/org/scada_lts/dao/event/EventDAO.java b/src/org/scada_lts/dao/event/EventDAO.java index f257547571..f3bfb6fb1d 100644 --- a/src/org/scada_lts/dao/event/EventDAO.java +++ b/src/org/scada_lts/dao/event/EventDAO.java @@ -63,7 +63,7 @@ * * @author Grzesiek Bylica Abil'I.T. development team, sdt@abilit.eu */ -public class EventDAO implements GenericDaoCR { +public class EventDAO implements IEventDAO { private static final Log LOG = LogFactory.getLog(EventDAO.class); @@ -819,6 +819,7 @@ private static EventType createHandlerEventType(ResultSet rs) throws SQLExceptio * * @return List of Events */ + @Override public List findEventsWithLimit(int typeId, int typeRef, int limit, int offset) { return (List) DAO.getInstance().getJdbcTemp().query(SELECT_SPECIFIC_DATAPOINT_ALARMS_WITH_LIMIT, new Object[]{typeId, typeRef, limit, offset}, new EventDTORowMapper()); } @@ -831,6 +832,7 @@ public List findEventsWithLimit(int typeId, int typeRef, int limit, in * * @return List of Events */ + @Override public SQLPageWithTotal findEvents( JsonEventSearch query, User user) { @@ -971,7 +973,7 @@ public List filtered(String filter, Object[] argsFilter, long lim return (List) DAO.getInstance().getJdbcTemp().query(BASIC_EVENT_SELECT+" where "+ filter + myLimit, args, new EventRowMapper()); } - @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 Object[] create(final EventInstance entity) { if (LOG.isTraceEnabled()) { @@ -1012,11 +1014,13 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return null; } + @Override public List getEventHandlersByDatapointId(int datapointId) { return (List) DAO.getInstance().getJdbcTemp().query(EVENT_HANDLER_SELECT_PLC_BY_DPID, new Object[]{datapointId}, new PlcEventHandlerRowMapper()); } - @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 updateEvent(EventInstance event) { if (LOG.isTraceEnabled()) { @@ -1027,7 +1031,8 @@ public void updateEvent(EventInstance event) { } - public void updateAck(long actTS, long userId, int alternateAckSource, long eventId ) { + @Override + public void updateAck(long actTS, long userId, int alternateAckSource, long eventId) { if (LOG.isTraceEnabled()) { LOG.trace("actTS:"+actTS+" userId:"+userId+" alternateAckSource:"+alternateAckSource+" eventId:"+eventId); @@ -1037,6 +1042,7 @@ public void updateAck(long actTS, long userId, int alternateAckSource, long even } + @Override public void ackEvents(long actTS, long userId, int alternateAckSource) { if (LOG.isTraceEnabled()) { @@ -1045,6 +1051,7 @@ public void ackEvents(long actTS, long userId, int alternateAckSource) { DAO.getInstance().getJdbcTemp().update( EVENT_ACT_ALL + "and " + STATUS_NO_ACTIVE_CONDITION_SQL, new Object[] { actTS, userId, alternateAckSource } ); } + @Override public void silenceEvents(long userId) { if (LOG.isTraceEnabled()) { LOG.trace(" userId:"+userId); @@ -1052,6 +1059,7 @@ public void silenceEvents(long userId) { DAO.getInstance().getJdbcTemp().update( EVENT_SILENCE_ALL, new Object[] { userId } ); } + @Override public void unassignEvents() { if (LOG.isTraceEnabled()) { LOG.trace(" unassignEvents"); @@ -1059,6 +1067,7 @@ public void unassignEvents() { DAO.getInstance().getJdbcTemp().update(UNASSIGN_EVENT_ALL, new Object[] {} ); } + @Override public void ackAllPendingSelected(long actTS, long userId, int alternateAckSource, List ids) { if (LOG.isTraceEnabled()) { LOG.trace("actTS:"+actTS+" userId:"+userId+" alternateAckSource:"+alternateAckSource); @@ -1071,22 +1080,8 @@ public void ackAllPendingSelected(long actTS, long userId, int alternateAckSourc DAO.getInstance().getJdbcTemp().update( EVENT_ACT_IDS, new Object[] { actTS, userId, alternateAckSource, joiner.toString() } ); } - - @Deprecated - public List getEventsForDataPoint(int dataPointId, int userId) { - return (List) DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where "+ EVENT_FILTER_FOR_DATA_POINT, new Object[]{dataPointId, userId}, new UserEventRowMapper()); - } - - @Deprecated - public List getPendingEvents(int typeId, int typeRef1, int userId) { - return (List) DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where " + EVENT_FILTER_TYPE_REF_USER, new Object[]{typeId, typeRef1, userId, DAO.boolToChar(true)}, new UserEventRowMapper() ); - } - - @Deprecated - public List getPendingEvents(int typeId, int userId) { - return (List) DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where " + EVENT_FILTER_TYPE_USER, new Object[]{typeId, userId, DAO.boolToChar(true)}, new UserEventRowMapper() ); - } + @Override public List getPendingEventsLimit(int userId, int limit) { Object[] args = new Object[] {userId, limit}; @@ -1096,31 +1091,29 @@ public List getPendingEventsLimit(int userId, int limit) { } + @Override public List getPendingEventsLimitAlarmLevelMin(int userId, int alarmLevelMin, int limit) { return DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where " + EVENT_FILTER_USER_ALARM_LEVEL_MIN + LIMIT+" ? ", new Object[]{userId, alarmLevelMin, limit}, new UserEventRowMapper() ); } + @Override public List getEventsForDataPointLimit(int dataPointId, int userId, int limit) { return DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where "+ EVENT_FILTER_FOR_DATA_POINT + LIMIT+" ? ", new Object[]{dataPointId, userId, limit}, new UserEventRowMapper()); } + @Override public List getPendingEventsLimit(int typeId, int typeRef1, int userId, int limit) { return DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where " + EVENT_FILTER_TYPE_REF_USER + LIMIT+" ? ", new Object[]{typeId, typeRef1, userId, DAO.boolToChar(true), limit}, new UserEventRowMapper() ); } + @Override public List getPendingEventsLimit(int typeId, int userId, int limit) { return DAO.getInstance().getJdbcTemp().query(EVENT_SELECT_WITH_USER_DATA+" where " + EVENT_FILTER_TYPE_USER + LIMIT+" ? ", new Object[]{typeId, userId, DAO.boolToChar(true), limit}, new UserEventRowMapper() ); } - - @Deprecated - public void attachRelationalInfo(EventInstance event) { - List lstUserComments = (List) DAO.getInstance().getJdbcTemp().query(EVENT_COMMENT_SELECT, new Object[] { event.getId() }, new UserCommentRowMapper() ); - event.setEventComments(lstUserComments); - } @Deprecated - @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) public int purgeEventsBefore(long time) { if (LOG.isTraceEnabled()) { @@ -1136,13 +1129,15 @@ public int purgeEventsBefore(long time) { } + @Override public int getEventCount() { return DAO.getInstance().getJdbcTemp().queryForObject(COUNT_EVENT, Integer.class); } //TODO rewrite + @Override public List searchOld(int eventId, int eventSourceType, String status, int alarmLevel, final String[] keywords, - final int maxResults, int userId, final ResourceBundle bundle) { + final int maxResults, int userId, final ResourceBundle bundle) { List where = new ArrayList(); List params = new ArrayList(); @@ -1236,19 +1231,22 @@ public Object extractData(ResultSet rs) throws SQLException, private int searchRowCount; private int startRow; + @Override public int getSearchRowCount() { return searchRowCount; } + @Override public int getStartRow() { return startRow; } + @Override public List search(int eventId, int eventSourceType, - String status, int alarmLevel, final String[] keywords, - long dateFrom, long dateTo, int userId, - final ResourceBundle bundle, final int from, final int to, - final Date date) { + String status, int alarmLevel, final String[] keywords, + long dateFrom, long dateTo, int userId, + final ResourceBundle bundle, final int from, final int to, + final Date date) { List where = new ArrayList(); List params = new ArrayList(); @@ -1374,24 +1372,29 @@ public Object extractData(ResultSet rs) throws SQLException, return results; } + @Override public EventType getEventHandlerType(int handlerId) { return (EventType) DAO.getInstance().getJdbcTemp().queryForObject(EVENT_HANDLER_TYPE,new Object[] { handlerId }, new EventHandlerTypeRowMapper() ); } + @Override public List getEventHandlers(int typeId, int ref1, int ref2) { if(ref2 > 0 && (typeId == EventType.EventSources.DATA_POINT || typeId == EventType.EventSources.DATA_SOURCE || typeId == EventType.EventSources.PUBLISHER)) return (List) DAO.getInstance().getJdbcTemp().query(EVENT_HANDLER_SELECT+" where "+ EVENT_HANDLER_FILTER_REF2, new Object[] {typeId, ref1, ref2}, new EventHandlerRowMapper()); return (List) DAO.getInstance().getJdbcTemp().query(EVENT_HANDLER_SELECT+" where "+ EVENT_HANDLER_FILTER_N, new Object[] {typeId, ref1}, new EventHandlerRowMapper()); } + @Override public List getEventHandlers() { return (List) DAO.getInstance().getJdbcTemp().query(EVENT_HANDLER_SELECT, new Object[] {}, new EventHandlerRowMapper()); } + @Override public List getPlcEventHandlers() { return (List) DAO.getInstance().getJdbcTemp().query(EVENT_HANDLER_SELECT_PLC, new Object[] {}, new PlcEventHandlerRowMapper()); } + @Override public EventHandlerVO getEventHandler(int eventHandlerId) { try { return (EventHandlerVO) DAO.getInstance().getJdbcTemp().queryForObject(EVENT_HANDLER_SELECT+" where " + EVENT_HANDLER_FILTER_ID, new Object[] {eventHandlerId}, new EventHandlerRowMapper()); @@ -1400,6 +1403,7 @@ public EventHandlerVO getEventHandler(int eventHandlerId) { } } + @Override public EventHandlerVO getEventHandler(String xid) { try { return (EventHandlerVO) DAO.getInstance().getJdbcTemp().queryForObject(EVENT_HANDLER_SELECT+" where " + EVENT_HANDLER_FILTER_XID, new Object[] {xid}, new EventHandlerRowMapper()); @@ -1408,8 +1412,9 @@ public EventHandlerVO getEventHandler(String xid) { } } - @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) - public int insertEventHandler(final int typeId,final int typeRef1,final int typeRef2, final EventHandlerVO handler) { + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override + public int insertEventHandler(final int typeId, final int typeRef1, final int typeRef2, final EventHandlerVO handler) { if (LOG.isTraceEnabled()) { LOG.trace(handler); @@ -1437,7 +1442,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S } - @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 updateEventHandler(EventHandlerVO handler) { if (LOG.isTraceEnabled()) { @@ -1458,6 +1464,7 @@ public void updateEventHandler(EventHandlerVO handler) { } //TODO rewrite because insert does not requires select + @Override public EventHandlerVO saveEventHandler(int typeId, int typeRef1, int typeRef2, EventHandlerVO handler) { if (handler.getId() == Common.NEW_ID) { int id = insertEventHandler(typeId, typeRef1, typeRef2,handler); @@ -1469,7 +1476,8 @@ public EventHandlerVO saveEventHandler(int typeId, int typeRef1, int typeRef2, E } } - @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 delete(final int id) { if (LOG.isTraceEnabled()) { @@ -1480,7 +1488,8 @@ public void delete(final 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 boolean toggleSilence(int eventId, int userId, Boolean updated) { String result = null; try { @@ -1497,11 +1506,13 @@ public boolean toggleSilence(int eventId, int userId, Boolean updated) { } } + @Override public int getHighestUnsilencedAlarmLevel(int userId) { return DAO.getInstance().getJdbcTemp().queryForObject(HIGHEST_UNSILENT_USER_ALARMS, new Object[] { DAO.boolToChar(false), userId },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 void updateEventAckUserId(int userId) { if (LOG.isTraceEnabled()) { @@ -1512,6 +1523,7 @@ public void updateEventAckUserId(int userId) { } @Transactional(readOnly = true) + @Override public List getAllStatusEvents(Set ids) { if(ids.isEmpty()) return Collections.emptyList(); @@ -1521,6 +1533,7 @@ public List getAllStatusEvents(Set ids) { } @Transactional(readOnly = true) + @Override public List getEventHandlers(Set ids) { if(ids.isEmpty()) return Collections.emptyList(); @@ -1530,6 +1543,7 @@ public List getEventHandlers(Set ids) { } @Transactional(readOnly = true) + @Override public List findCommentsByEventId(int eventId) { StringBuilder sql = new StringBuilder(); List params = new ArrayList(); @@ -1541,6 +1555,7 @@ public List findCommentsByEventId(int eventId) { return (List) result ; } + @Override public String joinAnd(List conditions) { StringBuilder result = new StringBuilder(); result.append(" 1 "); @@ -1552,6 +1567,7 @@ public String joinAnd(List conditions) { return result.toString(); } + @Override public String joinOr(List conditions) { StringBuilder result = new StringBuilder(); result.append(" 0 "); @@ -1563,6 +1579,7 @@ public String joinOr(List conditions) { return result.toString(); } + @Override public boolean isSilence(int eventId, int userId) { String result = null; try { @@ -1577,6 +1594,7 @@ public boolean isSilence(int eventId, int userId) { } } + @Override public boolean assign(long eventId, long acceptTs, User user) { if (LOG.isTraceEnabled()) { @@ -1587,6 +1605,7 @@ public boolean assign(long eventId, long acceptTs, User user) { return updates > 0; } + @Override public boolean unassign(long eventId) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java b/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java new file mode 100644 index 0000000000..37edbe8daa --- /dev/null +++ b/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java @@ -0,0 +1,23 @@ +package org.scada_lts.dao.event; + +import com.serotonin.mango.vo.event.CompoundEventDetectorVO; +import org.scada_lts.dao.GenericDAO; + +import java.util.List; + +public interface ICompoundEventDetectorDAO extends GenericDAO { + + List findAll(); + + CompoundEventDetectorVO findById(Object[] pk); + + CompoundEventDetectorVO findByXId(Object[] pk); + + List filtered(String filter, Object[] argsFilter, long limit); + + Object[] create(CompoundEventDetectorVO entity); + + void update(CompoundEventDetectorVO entity); + + void delete(CompoundEventDetectorVO entity); +} diff --git a/src/org/scada_lts/dao/event/IEventDAO.java b/src/org/scada_lts/dao/event/IEventDAO.java new file mode 100644 index 0000000000..e5b99b6cf0 --- /dev/null +++ b/src/org/scada_lts/dao/event/IEventDAO.java @@ -0,0 +1,117 @@ +package org.scada_lts.dao.event; + +import com.serotonin.mango.rt.event.EventInstance; +import com.serotonin.mango.rt.event.type.EventType; +import com.serotonin.mango.vo.User; +import com.serotonin.mango.vo.event.EventHandlerVO; +import org.scada_lts.dao.GenericDaoCR; +import org.scada_lts.utils.SQLPageWithTotal; +import org.scada_lts.web.mvc.api.dto.EventCommentDTO; +import org.scada_lts.web.mvc.api.dto.EventDTO; +import org.scada_lts.web.mvc.api.dto.eventHandler.EventHandlerPlcDTO; +import org.scada_lts.web.mvc.api.json.JsonEventSearch; + +import java.util.Date; +import java.util.List; +import java.util.ResourceBundle; +import java.util.Set; + +public interface IEventDAO extends GenericDaoCR { + List findAll(); + + EventInstance findById(Object[] pk); + + List filtered(String filter, Object[] argsFilter, long limit); + + Object[] create(EventInstance entity); + + List findEventsWithLimit(int typeId, int typeRef, int limit, int offset); + + SQLPageWithTotal findEvents( + JsonEventSearch query, + User user); + + List getEventHandlersByDatapointId(int datapointId); + + void updateEvent(EventInstance event); + + void updateAck(long actTS, long userId, int alternateAckSource, long eventId); + + void ackEvents(long actTS, long userId, int alternateAckSource); + + void silenceEvents(long userId); + + void unassignEvents(); + + void ackAllPendingSelected(long actTS, long userId, int alternateAckSource, List ids); + + List getPendingEventsLimit(int userId, int limit); + + List getPendingEventsLimitAlarmLevelMin(int userId, int alarmLevelMin, int limit); + + List getEventsForDataPointLimit(int dataPointId, int userId, int limit); + + List getPendingEventsLimit(int typeId, int typeRef1, int userId, int limit); + + List getPendingEventsLimit(int typeId, int userId, int limit); + + @Deprecated + int purgeEventsBefore(long time); + + int getEventCount(); + + List searchOld(int eventId, int eventSourceType, String status, int alarmLevel, String[] keywords, + int maxResults, int userId, ResourceBundle bundle); + + int getSearchRowCount(); + + int getStartRow(); + + List search(int eventId, int eventSourceType, + String status, int alarmLevel, String[] keywords, + long dateFrom, long dateTo, int userId, + ResourceBundle bundle, int from, int to, + Date date); + + EventType getEventHandlerType(int handlerId); + + List getEventHandlers(int typeId, int ref1, int ref2); + + List getEventHandlers(); + + List getPlcEventHandlers(); + + EventHandlerVO getEventHandler(int eventHandlerId); + + EventHandlerVO getEventHandler(String xid); + + int insertEventHandler(int typeId, int typeRef1, int typeRef2, EventHandlerVO handler); + + void updateEventHandler(EventHandlerVO handler); + + EventHandlerVO saveEventHandler(int typeId, int typeRef1, int typeRef2, EventHandlerVO handler); + + void delete(int id); + + boolean toggleSilence(int eventId, int userId, Boolean updated); + + int getHighestUnsilencedAlarmLevel(int userId); + + void updateEventAckUserId(int userId); + + List getAllStatusEvents(Set ids); + + List getEventHandlers(Set ids); + + List findCommentsByEventId(int eventId); + + String joinAnd(List conditions); + + String joinOr(List conditions); + + boolean isSilence(int eventId, int userId); + + boolean assign(long eventId, long acceptTs, User user); + + boolean unassign(long eventId); +} diff --git a/src/org/scada_lts/dao/event/IUserEventDAO.java b/src/org/scada_lts/dao/event/IUserEventDAO.java new file mode 100644 index 0000000000..d37cf38642 --- /dev/null +++ b/src/org/scada_lts/dao/event/IUserEventDAO.java @@ -0,0 +1,16 @@ +package org.scada_lts.dao.event; + +public interface IUserEventDAO extends org.scada_lts.dao.GenericDaoCR { + public abstract java.util.List findAll(); + public abstract org.scada_lts.dao.model.event.UserEvent findById(java.lang.Object[] arg0); + public abstract java.util.List filtered(java.lang.String arg0, java.lang.Object[] arg1, long arg2); + public abstract java.lang.Object[] create(org.scada_lts.dao.model.event.UserEvent arg0); + public abstract void batchUpdate(int arg0, java.util.List arg1, boolean arg2); + public abstract void updateAck(long arg0, boolean arg1); + public abstract void silenceEvent(long arg0, int arg1); + public abstract void unsilenceEvent(long arg0, int arg1); + public abstract void silenceEvents(java.util.List arg0, int arg1); + public abstract void unsilenceEvents(java.util.List arg0, int arg1); + public abstract void delete(int arg0); +} + diff --git a/src/org/scada_lts/dao/event/UserEventDAO.java b/src/org/scada_lts/dao/event/UserEventDAO.java index 9af44795cb..b2497cf032 100644 --- a/src/org/scada_lts/dao/event/UserEventDAO.java +++ b/src/org/scada_lts/dao/event/UserEventDAO.java @@ -27,7 +27,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.GenericDaoCR; import org.scada_lts.dao.model.event.UserEvent; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; @@ -41,7 +40,7 @@ * * @author Grzesiek Bylica Abil'I.T. development team, sdt@abilit.eu */ -public class UserEventDAO implements GenericDaoCR { +public class UserEventDAO implements IUserEventDAO { private static final Log LOG = LogFactory.getLog(UserEventDAO.class); diff --git a/src/org/scada_lts/dao/mailingList/IMailingListDAO.java b/src/org/scada_lts/dao/mailingList/IMailingListDAO.java new file mode 100644 index 0000000000..9d92fbedea --- /dev/null +++ b/src/org/scada_lts/dao/mailingList/IMailingListDAO.java @@ -0,0 +1,29 @@ +package org.scada_lts.dao.mailingList; + +import com.serotonin.mango.vo.mailingList.MailingList; +import org.scada_lts.dao.model.ScadaObjectIdentifier; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; +import java.util.Set; + +public interface IMailingListDAO { + MailingList getMailingList(int id); + + MailingList getMailingList(String xid); + + List getMailingLists(); + + List getSimpleMailingLists(); + + int insert(MailingList mailingList); + + void update(MailingList mailingList); + + void delete(int id); + + List getMailingLists(Set ids); +} diff --git a/src/org/scada_lts/dao/mailingList/IMailingListInactiveDAO.java b/src/org/scada_lts/dao/mailingList/IMailingListInactiveDAO.java new file mode 100644 index 0000000000..b7129b3244 --- /dev/null +++ b/src/org/scada_lts/dao/mailingList/IMailingListInactiveDAO.java @@ -0,0 +1,14 @@ +package org.scada_lts.dao.mailingList; + +import com.serotonin.mango.vo.mailingList.MailingList; + +import java.util.List; + +public interface IMailingListInactiveDAO { + + List getInactiveInterval(int mailingListId); + + void insert(MailingList mailingList); + + void delete(int mailingListId); +} diff --git a/src/org/scada_lts/dao/mailingList/IMailingListMemberDAO.java b/src/org/scada_lts/dao/mailingList/IMailingListMemberDAO.java new file mode 100644 index 0000000000..9416954d8e --- /dev/null +++ b/src/org/scada_lts/dao/mailingList/IMailingListMemberDAO.java @@ -0,0 +1,17 @@ +package org.scada_lts.dao.mailingList; + +import com.serotonin.mango.vo.mailingList.EmailRecipient; +import com.serotonin.mango.vo.mailingList.MailingList; + +import java.util.List; + +public interface IMailingListMemberDAO { + + List getEmailRecipient(int mailingListId); + + void insert(MailingList mailingList); + + void delete(int mailingListId); + + void deleteWithUserId(int userId); +} diff --git a/src/org/scada_lts/dao/mailingList/MailingListDAO.java b/src/org/scada_lts/dao/mailingList/MailingListDAO.java index ede57713aa..a66df18f2a 100644 --- a/src/org/scada_lts/dao/mailingList/MailingListDAO.java +++ b/src/org/scada_lts/dao/mailingList/MailingListDAO.java @@ -48,7 +48,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class MailingListDAO { +public class MailingListDAO implements IMailingListDAO { private static final Log LOG = LogFactory.getLog(MailingListDAO.class); @@ -131,6 +131,7 @@ public MailingList mapRow(ResultSet rs, int rowNum) throws SQLException { } } + @Override public MailingList getMailingList(int id) { if (LOG.isTraceEnabled()) { @@ -142,6 +143,7 @@ public MailingList getMailingList(int id) { return DAO.getInstance().getJdbcTemp().queryForObject(templateSelectWhereId, new Object[] {id}, new MailingListRowMapper()); } + @Override public MailingList getMailingList(String xid) { if (LOG.isTraceEnabled()) { @@ -160,6 +162,7 @@ public MailingList getMailingList(String xid) { return mailingList; } + @Override public List getMailingLists() { if (LOG.isTraceEnabled()) { @@ -171,12 +174,14 @@ public List getMailingLists() { return DAO.getInstance().getJdbcTemp().query(templateSelectOrderBy, new MailingListRowMapper()); } + @Override public List getSimpleMailingLists() { String templateSelectOrderBy = MAILING_LIST_SELECT + "order by name"; return DAO.getInstance().getJdbcTemp().query(templateSelectOrderBy, ScadaObjectIdentifierRowMapper.withDefaultNames()); } - @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 MailingList mailingList) { if (LOG.isTraceEnabled()) { @@ -199,7 +204,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return keyHolder.getKey().intValue(); } - @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 update(MailingList mailingList) { if (LOG.isTraceEnabled()) { @@ -211,7 +217,8 @@ public void update(MailingList mailingList) { mailingList.isCollectInactiveEmails(), mailingList.getCronPattern(), mailingList.getId()}); } - @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 delete(int id) { if (LOG.isTraceEnabled()) { @@ -222,6 +229,7 @@ public void delete(int id) { } @Transactional(readOnly = true) + @Override public List getMailingLists(Set ids) { if(ids.isEmpty()) return Collections.emptyList(); diff --git a/src/org/scada_lts/dao/mailingList/MailingListInactiveDAO.java b/src/org/scada_lts/dao/mailingList/MailingListInactiveDAO.java index 6fa505b5e4..2a96f6d61b 100644 --- a/src/org/scada_lts/dao/mailingList/MailingListInactiveDAO.java +++ b/src/org/scada_lts/dao/mailingList/MailingListInactiveDAO.java @@ -38,7 +38,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class MailingListInactiveDAO { +public class MailingListInactiveDAO implements IMailingListInactiveDAO { private static final Log LOG = LogFactory.getLog(MailingListInactiveDAO.class); diff --git a/src/org/scada_lts/dao/mailingList/MailingListMemberDAO.java b/src/org/scada_lts/dao/mailingList/MailingListMemberDAO.java index d43e6fea42..66cdf7b795 100644 --- a/src/org/scada_lts/dao/mailingList/MailingListMemberDAO.java +++ b/src/org/scada_lts/dao/mailingList/MailingListMemberDAO.java @@ -41,7 +41,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class MailingListMemberDAO { +public class MailingListMemberDAO implements IMailingListMemberDAO { private static final Log LOG = LogFactory.getLog(MailingListMemberDAO.class); diff --git a/src/org/scada_lts/dao/migration/mysql/V2_7_0_2__FixViewPermissions.java b/src/org/scada_lts/dao/migration/mysql/V2_7_0_2__FixViewPermissions.java index 9e3d1d69be..d49c89dcfd 100644 --- a/src/org/scada_lts/dao/migration/mysql/V2_7_0_2__FixViewPermissions.java +++ b/src/org/scada_lts/dao/migration/mysql/V2_7_0_2__FixViewPermissions.java @@ -47,9 +47,9 @@ private void migratePermissions() { IUsersProfileDAO usersProfileDAO = new OnlyMigrationUsersProfileDAO(); WatchListDAO watchListDAO = new OnlyMigrationWatchListDAO(); DataPointDAO dataPointDAO = new OnlyMigrationDataPointDAO(); - DataSourceDAO dataSourceDAO = new OnlyMigrationDataSourceDAO(); + IDataSourceDAO dataSourceDAO = new OnlyMigrationDataSourceDAO(); IViewDAO viewDAO = new OnlyMigrationViewDAO(); - DataPointUserDAO dataPointUserDAO = new OnlyMigrationDataPointUserDAO(); + IDataPointUserDAO dataPointUserDAO = new OnlyMigrationDataPointUserDAO(); IUserCommentDAO userCommentDAO = new OnlyMigrationUserCommentDAO(); PermissionsService watchListPermissionsService = diff --git a/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyDAO.java b/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyDAO.java new file mode 100644 index 0000000000..c77512f991 --- /dev/null +++ b/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyDAO.java @@ -0,0 +1,34 @@ +package org.scada_lts.dao.pointhierarchy; + +import com.serotonin.mango.vo.DataPointVO; +import com.serotonin.mango.vo.hierarchy.PointFolder; +import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +public interface IPointHierarchyDAO { + List getPointsHierarchy(); + + DataPointVO getPointsHierarchy(int id); + + Map> getFolderList(); + + boolean updateTitle(int id, String title); + + boolean updateParentIdDataPoint(int id, int parentId); + + boolean updateParentId(int id, int parentId); + + int insert(int parentId, String name); + + int insert(int id, int parentId, String name); + + void delete(); + + boolean deleteFolder(int key, int parentId); +} diff --git a/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java b/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java new file mode 100644 index 0000000000..1d410a1e71 --- /dev/null +++ b/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java @@ -0,0 +1,24 @@ +package org.scada_lts.dao.pointhierarchy; + +public interface IPointHierarchyXidDAO extends org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO { + public abstract java.util.List getPointsHierarchy(); + public abstract com.serotonin.mango.vo.DataPointVO getPointsHierarchy(int arg0); + public abstract java.util.Map> getFolderList(); + public abstract boolean updateTitle(int arg0, java.lang.String arg1); + public abstract boolean updateParentIdDataPoint(int arg0, int arg1); + public abstract boolean updateParentId(int arg0, int arg1); + public abstract int insert(int arg0, java.lang.String arg1); + public abstract int insert(int arg0, int arg1, java.lang.String arg2); + public abstract void delete(); + public abstract boolean deleteFolder(int arg0, int arg1); + public abstract boolean updateNameFolder(java.lang.String arg0, java.lang.String arg1); + public abstract boolean updateParentPoint(java.lang.String arg0, java.lang.String arg1); + public abstract boolean updateParentPoint(java.lang.String arg0, java.lang.Integer arg1); + public abstract boolean updateFolder(java.lang.String arg0, java.lang.String arg1); + public abstract void add(org.scada_lts.web.mvc.api.dto.FolderPointHierarchy arg0); + public abstract org.scada_lts.web.mvc.api.dto.FolderPointHierarchy folderCheckExist(java.lang.String arg0); + public abstract java.util.List getFolders(); + public abstract void deleteFolderXid(java.lang.String arg0); + public abstract java.lang.String getFolderXid(int arg0); +} + diff --git a/src/org/scada_lts/dao/pointhierarchy/PointHierarchyDAO.java b/src/org/scada_lts/dao/pointhierarchy/PointHierarchyDAO.java index 8b37a03a06..e65bc950f8 100644 --- a/src/org/scada_lts/dao/pointhierarchy/PointHierarchyDAO.java +++ b/src/org/scada_lts/dao/pointhierarchy/PointHierarchyDAO.java @@ -47,7 +47,7 @@ * person supporting and coreecting translation Jerzy Piejko */ -public class PointHierarchyDAO { +public class PointHierarchyDAO implements IPointHierarchyDAO { private static final Log LOG = LogFactory.getLog(PointHierarchyDAO.class); private final static String COLUMN_NAME_ID = "id"; @@ -158,6 +158,7 @@ public PointHierarchyDAO() { * * @return */ + @Override public List getPointsHierarchy() { if (LOG.isTraceEnabled()) { LOG.trace("SQL PointsDAO"); @@ -209,6 +210,7 @@ public PointHierarchyNode mapRow(ResultSet rs, int rownumber) throws SQLExceptio * @param id * @return */ + @Override public DataPointVO getPointsHierarchy(int id) { if (LOG.isTraceEnabled()) { LOG.trace("SQL Point"); @@ -230,6 +232,7 @@ public DataPointVO mapRow(ResultSet rs, int rownumber) throws SQLException { return lstDataPointVO.get(0); } + @Override public Map> getFolderList() { if (LOG.isTraceEnabled()) { @@ -264,6 +267,7 @@ public PointHierarchy mapRow(ResultSet rs, int rowNum) throws SQLException { * @return */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public boolean updateTitle(int id, String title) { int rows = DAO.getInstance().getJdbcTemp().update(updateTitleSQL, new Object[]{title, id}); PointHierarchyDAO.cachedPointHierarchy = null; @@ -278,6 +282,7 @@ public boolean updateTitle(int id, String title) { * @return */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public boolean updateParentIdDataPoint(int id, int parentId) { DataPointVO dp = getPointsHierarchy(id); dp.setPointFolderId(parentId); @@ -294,6 +299,7 @@ public boolean updateParentIdDataPoint(int id, int parentId) { * @return */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public boolean updateParentId(int id, int parentId) { int rows = DAO.getInstance().getJdbcTemp().update(updateParentIdSQL, new Object[]{parentId, id}); PointHierarchyDAO.cachedPointHierarchy = null; @@ -308,6 +314,7 @@ public boolean updateParentId(int id, int parentId) { * @return */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public int insert(int parentId, String name) { DAO.getInstance().getJdbcTemp().update(insertSQL, new Object[]{parentId, name.trim()}); int folderId = DAO.getInstance().getId(); @@ -317,6 +324,7 @@ public int insert(int parentId, String name) { } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public int insert(int id, int parentId, String name) { DAO.getInstance().getJdbcTemp().update(INSERT_POINT_HIERARCHY, new Object[]{parentId, name.trim()}); PointHierarchyDAO.cachedPointHierarchy = null; @@ -324,6 +332,7 @@ public int insert(int id, int parentId, String name) { } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public void delete() { if (LOG.isTraceEnabled()) { LOG.info("delete()"); @@ -338,6 +347,7 @@ public void delete() { * @return */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + @Override public boolean deleteFolder(int key, int parentId) { if (LOG.isTraceEnabled()) { LOG.info("delete key:" + key); diff --git a/src/org/scada_lts/dao/pointhierarchy/PointHierarchyXidDAO.java b/src/org/scada_lts/dao/pointhierarchy/PointHierarchyXidDAO.java index 6d3a928685..16bbe27b12 100644 --- a/src/org/scada_lts/dao/pointhierarchy/PointHierarchyXidDAO.java +++ b/src/org/scada_lts/dao/pointhierarchy/PointHierarchyXidDAO.java @@ -36,7 +36,7 @@ * * @author grzegorz.bylica@gmail.com */ -public class PointHierarchyXidDAO extends PointHierarchyDAO { +public class PointHierarchyXidDAO extends PointHierarchyDAO implements IPointHierarchyXidDAO { private static final String ROOT = "_"; private static final int ROOT_PARENT_ID = 0; diff --git a/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java b/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java new file mode 100644 index 0000000000..15d6063c7f --- /dev/null +++ b/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java @@ -0,0 +1,11 @@ +package org.scada_lts.dao.pointvalues; + +public interface IPointValueAdnnotationsDAO extends org.scada_lts.dao.GenericDaoCR { + public abstract java.util.List findAll(); + public abstract org.scada_lts.dao.model.point.PointValueAdnnotation findById(java.lang.Object[] arg0); + public abstract java.util.List filtered(java.lang.String arg0, java.lang.Object[] arg1, long arg2); + public abstract java.lang.Object[] create(org.scada_lts.dao.model.point.PointValueAdnnotation arg0); + public abstract void update(int arg0); + public abstract void updateAnnotations(java.util.List arg0); +} + diff --git a/src/org/scada_lts/dao/pointvalues/IPointValueAmChartDAO.java b/src/org/scada_lts/dao/pointvalues/IPointValueAmChartDAO.java new file mode 100644 index 0000000000..2cadf103aa --- /dev/null +++ b/src/org/scada_lts/dao/pointvalues/IPointValueAmChartDAO.java @@ -0,0 +1,24 @@ +package org.scada_lts.dao.pointvalues; + +import com.serotonin.mango.vo.DataPointVO; + +import java.util.List; +import java.util.Map; + +public interface IPointValueAmChartDAO { + + List> getPointValuesFromRange(int[] points, long startTs, long endTs); + + List> getPointValuesToCompareFromRange(int[] points, long startTs, long endTs); + + List aggregatePointValues(DataPointVO dataPoint, long startTs, + long endTs, long intervalMs, int limit); + + List getPointValuesFromRangeWithLimit(int[] points, long startTs, + long endTs, int limit); + + List> convertToAmChartCompareDataObject(List values, + int offset); + + List> convertToAmChartDataObject(List values); +} diff --git a/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java b/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java index f64856996b..7f75b72c36 100644 --- a/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java +++ b/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java @@ -76,4 +76,12 @@ public interface IPointValueDAO { PointValueTime getPointValueBefore(int dataPointId, long time); PointValueTime getPointValueAt(int dataPointId, long time); + + List getPointValues(int dataPointId, long since); + + List getPointValuesBetween(int dataPointId, long from, long to); + + List getLatestPointValues(int dataPointId, int limit); + + List getLatestPointValues(int dataPointId, int limit, long before); } diff --git a/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java b/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java index aa7272c3cb..c48b109a97 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java @@ -28,13 +28,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.GenericDaoCR; import org.scada_lts.dao.model.point.PointValue; import org.scada_lts.dao.model.point.PointValueAdnnotation; import org.springframework.jdbc.core.RowMapper; import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; import com.serotonin.mango.rt.dataImage.SetPointSource; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -46,12 +46,10 @@ */ @Deprecated -public class PointValueAdnnotationsDAO implements GenericDaoCR { +public class PointValueAdnnotationsDAO implements IPointValueAdnnotationsDAO { private static final Log LOG = LogFactory.getLog(PointValueAdnnotationsDAO.class); - private static PointValueAdnnotationsDAO instance; - private final static String COLUMN_NAME_POINT_VALUE_ID = "pointValueId"; private final static String COLUMN_NAME_TEXT_POINT_VALUE_SHORT = "textPointValueShort"; private final static String COLUMN_NAME_TEXT_POINT_VALUE_LONG = "textPointValueLong"; @@ -133,11 +131,8 @@ public PointValueAdnnotation mapRow(ResultSet rs, int rowNum) throws SQLExceptio } } - public static PointValueAdnnotationsDAO getInstance() { - if (instance == null) { - instance = new PointValueAdnnotationsDAO(); - } - return instance; + public static IPointValueAdnnotationsDAO getInstance() { + return ApplicationBeans.getPointValueAdnnotationsDAOBean(); } @Override @@ -215,4 +210,4 @@ public void updateAnnotations(List values) { } } -} \ No newline at end of file +} diff --git a/src/org/scada_lts/dao/pointvalues/PointValueAmChartDAO.java b/src/org/scada_lts/dao/pointvalues/PointValueAmChartDAO.java index e4bb1e103a..35ecfbb532 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueAmChartDAO.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueAmChartDAO.java @@ -26,7 +26,7 @@ * * @author Radoslaw Jajko */ -public class PointValueAmChartDAO { +public class PointValueAmChartDAO implements IPointValueAmChartDAO { private static final Log LOG = LogFactory.getLog(PointValueAmChartDAO.class); diff --git a/src/org/scada_lts/dao/pointvalues/PointValueDAO.java b/src/org/scada_lts/dao/pointvalues/PointValueDAO.java index e82c8fdfc6..0659f1cd93 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueDAO.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueDAO.java @@ -63,7 +63,6 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ -@Repository public class PointValueDAO implements GenericDaoCR, IPointValueDAO { private static final Log LOG = LogFactory.getLog(PointValueDAO.class); @@ -741,4 +740,40 @@ private static long getId(KeyHolder keyHolder) { } return id; } + + @Override + public List getPointValues(int dataPointId, long since) { + return filtered( + POINT_VALUE_FILTER_BASE_ON_DATA_POINT_ID_AND_TIME_STAMP, + new Object[]{dataPointId, since}, + GenericDaoCR.NO_LIMIT + ); + } + + @Override + public List getPointValuesBetween(int dataPointId, long from, long to) { + return filtered( + POINT_VALUE_FILTER_BASE_ON_DATA_POINT_ID_AND_TIME_STAMP_FROM_TO, + new Object[]{dataPointId, from, to}, + GenericDaoCR.NO_LIMIT + ); + } + + @Override + public List getLatestPointValues(int dataPointId, int limit) { + return filtered( + POINT_VALUE_FILTER_LAST_BASE_ON_DATA_POINT_ID, + new Object[]{dataPointId}, + limit + ); + } + + @Override + public List getLatestPointValues(int dataPointId, int limit, long before) { + return filtered( + POINT_VALUE_FILTER_LATEST_BASE_ON_DATA_POINT_ID, + new Object[]{dataPointId, before}, + limit + ); + } } \ No newline at end of file diff --git a/src/org/scada_lts/dao/report/IReportDAO.java b/src/org/scada_lts/dao/report/IReportDAO.java new file mode 100644 index 0000000000..9cb857afb4 --- /dev/null +++ b/src/org/scada_lts/dao/report/IReportDAO.java @@ -0,0 +1,30 @@ +package org.scada_lts.dao.report; + +import com.serotonin.mango.vo.report.ReportVO; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +public interface IReportDAO { + ReportVO getReport(int id); + + ReportVO getReport(String xid); + + List getReports(); + + List search(Map query); + + List search(int userId, Map query); + + List getReports(int userId); + + int insert(ReportVO report); + + void update(ReportVO report); + + void delete(int id); +} diff --git a/src/org/scada_lts/dao/report/IReportInstanceDAO.java b/src/org/scada_lts/dao/report/IReportInstanceDAO.java new file mode 100644 index 0000000000..a4bec38b47 --- /dev/null +++ b/src/org/scada_lts/dao/report/IReportInstanceDAO.java @@ -0,0 +1,41 @@ +package org.scada_lts.dao.report; + +import com.serotonin.ShouldNeverHappenException; +import com.serotonin.mango.rt.event.EventInstance; +import com.serotonin.mango.rt.event.type.*; +import com.serotonin.mango.vo.report.ReportInstance; +import com.serotonin.web.i18n.LocalizableMessage; +import com.serotonin.web.i18n.LocalizableMessageParseException; +import org.scada_lts.dao.DAO; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +public interface IReportInstanceDAO { + + ReportInstance getReportInstance(int id); + + List getReportInstances(int userId); + + int insert(ReportInstance reportInstance); + + void updateTime(ReportInstance reportInstance); + + void updatePreventPurge(int id, boolean preventPurge, int userId); + + void delete(int id, int userId); + + int deleteReportBefore(long time); + + List getReportInstanceEvents(int instanceId); + + List getReportInstances(); + + void updatePreventPurge(int id, boolean preventPurge); + +} diff --git a/src/org/scada_lts/dao/report/IReportInstanceDataDAO.java b/src/org/scada_lts/dao/report/IReportInstanceDataDAO.java new file mode 100644 index 0000000000..2e03fcceef --- /dev/null +++ b/src/org/scada_lts/dao/report/IReportInstanceDataDAO.java @@ -0,0 +1,18 @@ +package org.scada_lts.dao.report; + +import com.serotonin.mango.vo.report.ReportDataStreamHandler; +import com.serotonin.mango.vo.report.ReportDataValue; +import com.serotonin.mango.vo.report.ReportPointInfo; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; + +public interface IReportInstanceDataDAO { + int insert(Object[] params, int reportPointId, String timestampSql); + + int insertReportInstanceDataAnnotations(String annotationCase, int reportPointId); + + void setReportValue(ReportPointInfo point, ReportDataValue rdv, ReportDataStreamHandler handler); +} diff --git a/src/org/scada_lts/dao/report/IReportInstancePointDAO.java b/src/org/scada_lts/dao/report/IReportInstancePointDAO.java new file mode 100644 index 0000000000..6b79567a1e --- /dev/null +++ b/src/org/scada_lts/dao/report/IReportInstancePointDAO.java @@ -0,0 +1,64 @@ +package org.scada_lts.dao.report; + +import com.serotonin.mango.rt.dataImage.types.MangoValue; +import com.serotonin.mango.view.text.TextRenderer; +import com.serotonin.mango.vo.DataPointVO; +import com.serotonin.mango.vo.report.ReportInstance; +import com.serotonin.mango.vo.report.ReportPointInfo; +import org.scada_lts.serorepl.utils.StringUtils; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.SQLException; +import java.util.List; + +public interface IReportInstancePointDAO { + List getPointInfos(int instanceId); + + int insert(ReportInstance reportInstance, int dataType, MangoValue startValue, PointInfo pointInfo); + + /* +PointInfo class +*/ + public static class PointInfo { + private final DataPointVO point; + private final String colour; + private final boolean consolidatedChart; + + public PointInfo(DataPointVO point, String colour, boolean consolidatedChart) { + this.point = point; + this.colour = colour; + this.consolidatedChart = consolidatedChart; + } + + public int getId() { + return point.getId(); + } + + public DataPointVO getPoint() { + return point; + } + + public String getColour() { + return colour; + } + + public String getName() { + return StringUtils.truncate(point.getName(), "", 100); + } + + public String getDeviceName() { + return StringUtils.truncate(point.getDeviceName(), "", 40); + } + + public TextRenderer getTextRenderer() { + return point.getTextRenderer(); + } + + + public boolean isConsolidatedChart() { + return consolidatedChart; + } + } +} diff --git a/src/org/scada_lts/dao/report/IReportInstanceUserCommentDAO.java b/src/org/scada_lts/dao/report/IReportInstanceUserCommentDAO.java new file mode 100644 index 0000000000..a30e5bd498 --- /dev/null +++ b/src/org/scada_lts/dao/report/IReportInstanceUserCommentDAO.java @@ -0,0 +1,10 @@ +package org.scada_lts.dao.report; + +import com.serotonin.mango.vo.report.ReportUserComment; + +import java.util.List; + +public interface IReportInstanceUserCommentDAO { + + List getReportUserComments(int reportInstanceId); +} diff --git a/src/org/scada_lts/dao/report/ReportDAO.java b/src/org/scada_lts/dao/report/ReportDAO.java index 601a8ba844..2b1abb5219 100644 --- a/src/org/scada_lts/dao/report/ReportDAO.java +++ b/src/org/scada_lts/dao/report/ReportDAO.java @@ -49,7 +49,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class ReportDAO { +public class ReportDAO implements IReportDAO { private static final Log LOG = LogFactory.getLog(ReportDAO.class); @@ -121,6 +121,7 @@ public ReportVO mapRow(ResultSet rs, int rowNum) throws SQLException { } } + @Override public ReportVO getReport(int id) { if (LOG.isTraceEnabled()) { @@ -136,6 +137,7 @@ public ReportVO getReport(int id) { return reportVO; } + @Override public ReportVO getReport(String xid) { if (LOG.isTraceEnabled()) { @@ -151,6 +153,7 @@ public ReportVO getReport(String xid) { return reportVO; } + @Override public List getReports() { if (LOG.isTraceEnabled()) { @@ -160,10 +163,12 @@ public List getReports() { return DAO.getInstance().getJdbcTemp().query(REPORT_SELECT, new ReportRowMapper()); } + @Override public List search(Map query) { return search(Common.NEW_ID, query); } + @Override public List search(int userId, Map query) { if (LOG.isTraceEnabled()) { @@ -173,6 +178,7 @@ public List search(int userId, Map query) { return DAO.getInstance().getJdbcTemp().query(sql.getQuery(), sql.getArgs(), new ReportRowMapper()); } + @Override public List getReports(int userId) { if (LOG.isTraceEnabled()) { @@ -182,7 +188,8 @@ public List getReports(int userId) { return DAO.getInstance().getJdbcTemp().query(REPORT_SELECT_WHERE_USER_ID_ORDER, new Object[]{userId}, new ReportRowMapper()); } - @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 ReportVO report) { if (LOG.isTraceEnabled()) { @@ -206,7 +213,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return keyHolder.getKey().intValue(); } - @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 update(final ReportVO report) { if (LOG.isTraceEnabled()) { @@ -221,7 +229,8 @@ public void update(final ReportVO report) { ); } - @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 delete(int id) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/report/ReportInstanceDAO.java b/src/org/scada_lts/dao/report/ReportInstanceDAO.java index 2f8a581bdc..14dbfe9255 100644 --- a/src/org/scada_lts/dao/report/ReportInstanceDAO.java +++ b/src/org/scada_lts/dao/report/ReportInstanceDAO.java @@ -49,7 +49,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class ReportInstanceDAO { +public class ReportInstanceDAO implements IReportInstanceDAO { private static final Log LOG = LogFactory.getLog(ReportInstanceDAO.class); @@ -167,6 +167,7 @@ public ReportInstance mapRow(ResultSet rs, int rowNum) throws SQLException { } } + @Override public ReportInstance getReportInstance(int id) { if (LOG.isTraceEnabled()) { @@ -182,6 +183,7 @@ public ReportInstance getReportInstance(int id) { return reportInstance; } + @Override public List getReportInstances(int userId) { if (LOG.isTraceEnabled()) { @@ -191,7 +193,8 @@ public List getReportInstances(int userId) { return DAO.getInstance().getJdbcTemp().query(REPORT_INSTANCE_SELECT_WHERE_USER_ID_ORDER, new Object[]{userId}, new ReportInstanceRowMapper()); } - @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 ReportInstance reportInstance) { if (LOG.isTraceEnabled()) { @@ -221,7 +224,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return keyholder.getKey().intValue(); } - @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 updateTime(ReportInstance reportInstance) { if (LOG.isTraceEnabled()) { @@ -238,7 +242,8 @@ public void updateTime(ReportInstance reportInstance) { }); } - @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 updatePreventPurge(int id, boolean preventPurge, int userId) { if (LOG.isTraceEnabled()) { @@ -252,7 +257,8 @@ public void updatePreventPurge(int id, boolean preventPurge, int userId) { }); } - @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 delete(int id, int userId) { if (LOG.isTraceEnabled()) { @@ -262,7 +268,8 @@ public void delete(int id, int userId) { DAO.getInstance().getJdbcTemp().update(REPORT_INSTANCE_DELETE, new Object[]{id, userId}); } - @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 deleteReportBefore(final long time) { if (LOG.isTraceEnabled()) { @@ -312,10 +319,12 @@ public int deleteReportBefore(final long time) { + COLUMN_NAME_E_ACTIVE_TS; + @Override public List getReportInstanceEvents(int instanceId) { return DAO.getInstance().getJdbcTemp().query(REPORT_INSTANCE_EVENT_SELECT, new Object[] {instanceId}, new ReportEventRowMapper()); } + @Override public List getReportInstances() { if (LOG.isTraceEnabled()) { @@ -325,7 +334,8 @@ public List getReportInstances() { return DAO.getInstance().getJdbcTemp().query(REPORT_INSTANCE_SELECT, new ReportInstanceRowMapper()); } - @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 updatePreventPurge(int id, boolean preventPurge) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/report/ReportInstanceDataDAO.java b/src/org/scada_lts/dao/report/ReportInstanceDataDAO.java index 292a27993e..e0d0b35c50 100644 --- a/src/org/scada_lts/dao/report/ReportInstanceDataDAO.java +++ b/src/org/scada_lts/dao/report/ReportInstanceDataDAO.java @@ -45,7 +45,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class ReportInstanceDataDAO { +public class ReportInstanceDataDAO implements IReportInstanceDataDAO { private static final Log LOG = LogFactory.getLog(ReportInstanceDataDAO.class); @@ -151,7 +151,8 @@ public class ReportInstanceDataDAO { + "rp." + COLUMN_NAME_ID + "=?"; // @formatter:on - @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 Object[] params, final int reportPointId, final String timestampSql) { if (LOG.isTraceEnabled()) { @@ -170,7 +171,8 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return value; } - @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 insertReportInstanceDataAnnotations(String annotationCase, final int reportPointId) { if (LOG.isTraceEnabled()) { @@ -192,6 +194,7 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return reportPointId; } + @Override public void setReportValue(final ReportPointInfo point, final ReportDataValue rdv, final ReportDataStreamHandler handler) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/report/ReportInstancePointDAO.java b/src/org/scada_lts/dao/report/ReportInstancePointDAO.java index 0b19f5b925..5ace222ee2 100644 --- a/src/org/scada_lts/dao/report/ReportInstancePointDAO.java +++ b/src/org/scada_lts/dao/report/ReportInstancePointDAO.java @@ -21,14 +21,12 @@ import com.serotonin.mango.DataTypes; import com.serotonin.mango.rt.dataImage.types.MangoValue; import com.serotonin.mango.view.text.TextRenderer; -import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.report.ReportInstance; import com.serotonin.mango.vo.report.ReportPointInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.DAO; import org.scada_lts.dao.SerializationData; -import org.scada_lts.serorepl.utils.StringUtils; import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; @@ -49,7 +47,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class ReportInstancePointDAO { +public class ReportInstancePointDAO implements IReportInstancePointDAO { private static final Log LOG = LogFactory.getLog(ReportInstancePointDAO.class); @@ -98,51 +96,7 @@ public class ReportInstancePointDAO { // @formatter:on - /* - PointInfo class - */ - public static class PointInfo { - private final DataPointVO point; - private final String colour; - private final boolean consolidatedChart; - - public PointInfo(DataPointVO point, String colour, boolean consolidatedChart) { - this.point = point; - this.colour = colour; - this.consolidatedChart = consolidatedChart; - } - - public int getId() { - return point.getId(); - } - - public DataPointVO getPoint() { - return point; - } - - public String getColour() { - return colour; - } - - public String getName() { - return StringUtils.truncate(point.getName(), "", 100); - } - - public String getDeviceName() { - return StringUtils.truncate(point.getDeviceName(), "", 40); - } - - public TextRenderer getTextRenderer() { - return point.getTextRenderer(); - } - - - - public boolean isConsolidatedChart() { - return consolidatedChart; - } - } - + @Override public List getPointInfos(int instanceId) { if (LOG.isTraceEnabled()) { @@ -152,13 +106,8 @@ public List getPointInfos(int instanceId) { return DAO.getInstance().getJdbcTemp().query(REPORT_INSTANCE_POINT_SELECT_WHERE, new Object[]{instanceId}, new ReportPointInfoRowMapper()); } - @Deprecated(since = "2.7.7") - @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) - public int insert(final ReportInstance reportInstance, final DataPointVO point, final String name, final int dataType, final MangoValue startValue, final PointInfo pointInfo) { - return insert(reportInstance, dataType, startValue, pointInfo); - } - - @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 ReportInstance reportInstance, final int dataType, final MangoValue startValue, final PointInfo pointInfo) { if (LOG.isTraceEnabled()) { diff --git a/src/org/scada_lts/dao/report/ReportInstanceUserCommentDAO.java b/src/org/scada_lts/dao/report/ReportInstanceUserCommentDAO.java index 08ee5591ce..6ca852d483 100644 --- a/src/org/scada_lts/dao/report/ReportInstanceUserCommentDAO.java +++ b/src/org/scada_lts/dao/report/ReportInstanceUserCommentDAO.java @@ -33,7 +33,7 @@ * * @author Mateusz Kaproń Abil'I.T. development team, sdt@abilit.eu */ -public class ReportInstanceUserCommentDAO { +public class ReportInstanceUserCommentDAO implements IReportInstanceUserCommentDAO { private static final Log LOG = LogFactory.getLog(ReportInstanceUserCommentDAO.class); diff --git a/src/org/scada_lts/dao/watchlist/IWatchListDAO.java b/src/org/scada_lts/dao/watchlist/IWatchListDAO.java new file mode 100644 index 0000000000..9295d99a8b --- /dev/null +++ b/src/org/scada_lts/dao/watchlist/IWatchListDAO.java @@ -0,0 +1,65 @@ +package org.scada_lts.dao.watchlist; + +import br.org.scadabr.vo.permission.WatchListAccess; +import com.serotonin.mango.view.ShareUser; +import com.serotonin.mango.vo.WatchList; +import org.scada_lts.dao.GenericDaoCR; +import org.scada_lts.dao.model.ScadaObjectIdentifier; +import org.scada_lts.web.mvc.api.json.JsonDataPointOrder; + +import java.util.List; + +public interface IWatchListDAO extends GenericDaoCR { + + List findAll(); + + WatchList findById(Object[] pk); + + List filtered(String filter, Object[] argsFilter, long limit); + + Object[] create(WatchList entity); + + WatchList findByXId(String xid); + + List getWatchListUsers(int watchListId); + + List getPointsWatchList(int watchListId); + + void updateUsers(int userId, int watchListId); + + void update(WatchList watchList); + + void deleteWatchListPoints(int watchListId); + + void deleteWatchListUsers(int watchListId); + + void deleteWatchList(int watchListId); + + void addPointsForWatchList(WatchList watchList); + + void addWatchListUsers(WatchList watchList); + + void deleteUserFromWatchList(int watchListId, int userId); + + void deleteWatchListPoints(String dataPointIds); + + List selectWatchListsWithAccess(int userId, int profileId); + + List selectWatchListIdentifiersWithAccess(int userId, int profileId); + + List selectWatchListPermissions(int userId); + + int[] insertPermissions(int userId, List toInsert); + + int[] deletePermissions(int userId, List toDelete); + + List selectWatchListShareUsers(int watchListId); + + @Deprecated + JsonDataPointOrder getDataPointOrder(Integer watchListId); + + @Deprecated + void setDataPointOrder(JsonDataPointOrder pointOrder); + + List findIdentifiers(); +} diff --git a/src/org/scada_lts/dao/watchlist/WatchListDAO.java b/src/org/scada_lts/dao/watchlist/WatchListDAO.java index 9f2fb3cbab..587b0eee5a 100644 --- a/src/org/scada_lts/dao/watchlist/WatchListDAO.java +++ b/src/org/scada_lts/dao/watchlist/WatchListDAO.java @@ -27,7 +27,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.GenericDaoCR; import org.scada_lts.dao.ShareUserRowMapper; import org.scada_lts.dao.model.ScadaObjectIdentifierRowMapper; import org.scada_lts.dao.model.ScadaObjectIdentifier; @@ -51,7 +50,7 @@ * * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu */ -public class WatchListDAO implements GenericDaoCR { +public class WatchListDAO implements IWatchListDAO { private static final Log LOG = LogFactory.getLog(WatchListDAO.class); @@ -324,6 +323,7 @@ public WatchList findById(Object[] pk) { } } + @Override public WatchList findByXId(String xid) { try { return (WatchList) DAO.getInstance().getJdbcTemp().queryForObject(WATCH_LIST_SELECT_BASE_ON_XID, new Object[] {xid}, new WatchListRowMapper()); @@ -347,7 +347,7 @@ public List filtered(String filter, Object[] argsFilter, long limit) } - @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 Object[] create(final WatchList entity) { @@ -374,37 +374,45 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return new Object[] {keyHolder.getKey().intValue()}; } + @Override public List getWatchListUsers(int watchListId) { return (List) DAO.getInstance().getJdbcTemp().query(WATCH_LIST_USERS_SELECT_BASE_ON_WATCH_LIST_ID, new Object[] {watchListId}, new WatchListUserRowMapper()); } + @Override public List getPointsWatchList(int watchListId) { return (List) DAO.getInstance().getJdbcTemp().queryForList(WATCH_LIST_POINTS_SELECT_BASE_ON_WATCH_LIST_ID, new Object[] { watchListId }, Integer.class ); } + @Override public void updateUsers(int userId, int watchListId) { DAO.getInstance().getJdbcTemp().update(WATCH_LIST_FOR_USER_UPDATE, new Object[] {watchListId, userId}); } + @Override public void update(WatchList watchList) { DAO.getInstance().getJdbcTemp().update(WATCH_LIST_UPDATE, new Object[] {watchList.getXid(), watchList.getName(), watchList.getId()}); } //TODO rewrite because update is not delete All and add all. + @Override public void deleteWatchListPoints(int watchListId) { DAO.getInstance().getJdbcTemp().update(WATCH_LIST_POINTS_DELETE, new Object[] {watchListId}); } //TODO rewrite + @Override public void deleteWatchListUsers(int watchListId) { DAO.getInstance().getJdbcTemp().update(WATCH_LIST_USERS_DELETE, new Object[] {watchListId}); } + @Override public void deleteWatchList(int watchListId) { DAO.getInstance().getJdbcTemp().update(WATCH_LIST_DELETE_BASE_ON_ID, new Object[] {watchListId}); } //TODO rewrite + @Override public void addPointsForWatchList(final WatchList watchList) { DAO.getInstance().getJdbcTemp().batchUpdate( @@ -423,6 +431,7 @@ public void setValues(PreparedStatement ps, int i) throws SQLException { } //TODO rewrite + @Override public void addWatchListUsers(final WatchList watchList) { DAO.getInstance().getJdbcTemp().batchUpdate( @@ -440,10 +449,12 @@ public void setValues(PreparedStatement ps, int i) throws SQLException { }); } + @Override public void deleteUserFromWatchList(int watchListId, int userId) { DAO.getInstance().getJdbcTemp().update(WATCH_LIST_DELETE_USER_FROM_WATCH_LIST, new Object[] {watchListId, userId}); } + @Override public void deleteWatchListPoints(String dataPointIds) { String[] parameters = dataPointIds.split(","); @@ -456,13 +467,15 @@ public void deleteWatchListPoints(String dataPointIds) { DAO.getInstance().getJdbcTemp().update(queryBuilder.toString(), (Object[]) parameters); } + @Override public List selectWatchListsWithAccess(int userId, int profileId) { return DAO.getInstance().getJdbcTemp().query(WATCH_LIST_SELECT + " where " + WATCH_LIST_FILTER_BASE_ON_USER_ID_USER_PROFILE_ID_PERMISSION_ORDER_BY_NAME, new Object[] { userId, profileId, ShareUser.ACCESS_NONE, userId, ShareUser.ACCESS_NONE }, new WatchListRowMapper()); } - public List selectWatchListIdentifiersWithAccess(int userId, int profileId) { + @Override + public List selectWatchListIdentifiersWithAccess(int userId, int profileId) { return DAO.getInstance().getJdbcTemp().query(WATCH_LIST_SELECT + " where " + WATCH_LIST_FILTER_BASE_ON_USER_ID_USER_PROFILE_ID_PERMISSION_ORDER_BY_NAME, new Object[] { userId, profileId, ShareUser.ACCESS_NONE, userId, ShareUser.ACCESS_NONE }, new ScadaObjectIdentifierRowMapper.Builder() @@ -472,6 +485,7 @@ public List selectWatchListIdentifiersWithAccess(int user .build()); } + @Override public List selectWatchListPermissions(final int userId) { if (LOG.isTraceEnabled()) { LOG.trace("selectViewPermissions(final int userId) userId:" + userId); @@ -486,6 +500,7 @@ public List selectWatchListPermissions(final int userId) { } + @Override public int[] insertPermissions(final int userId, final List toInsert) { if (LOG.isTraceEnabled()) { LOG.trace("insertPermissions(final User user, final List toInsert) user:" + userId + ""); @@ -501,6 +516,7 @@ public int[] insertPermissions(final int userId, final List toI .batchUpdate(WATCHLIST_USER_INSERT_ON_DUPLICATE_KEY_UPDATE_ACCESS_TYPE, batchArgs, argTypes); } + @Override public int[] deletePermissions(final int userId, final List toDelete) { if (LOG.isTraceEnabled()) { @@ -517,6 +533,7 @@ public int[] deletePermissions(final int userId, final List toD .batchUpdate(WATCHLIST_USER_DELETE_BASE_ON_WATCHLIST_ID_USER_ID, batchArgs, argTypes); } + @Override public List selectWatchListShareUsers(int watchListId) { if (LOG.isTraceEnabled()) LOG.trace("selectViewShareUsers(int watchListId) watchListId:" + watchListId); @@ -533,6 +550,7 @@ public List selectWatchListShareUsers(int watchListId) { } @Deprecated + @Override public JsonDataPointOrder getDataPointOrder(Integer watchListId) { if(LOG.isTraceEnabled()) { LOG.trace("getDataPointOrder()"); @@ -548,6 +566,7 @@ public JsonDataPointOrder getDataPointOrder(Integer watchListId) { } @Deprecated + @Override public void setDataPointOrder(JsonDataPointOrder pointOrder) { //Delete all order @@ -562,6 +581,7 @@ public void setDataPointOrder(JsonDataPointOrder pointOrder) { } + @Override public List findIdentifiers() { return DAO.getInstance().getJdbcTemp().query(WATCH_LIST_SELECT_ORDER_BY_NAME, new Object[]{}, new ScadaObjectIdentifierRowMapper.Builder() diff --git a/src/org/scada_lts/db/BinaryDataHandler.java b/src/org/scada_lts/db/BinaryDataHandler.java new file mode 100644 index 0000000000..282ab10bfe --- /dev/null +++ b/src/org/scada_lts/db/BinaryDataHandler.java @@ -0,0 +1,14 @@ +package org.scada_lts.db; + +import java.io.InputStream; +import java.sql.ResultSet; +import java.sql.SQLException; + +public interface BinaryDataHandler { + + InputStream getBinaryStream(ResultSet rs, int columnIndex) throws SQLException; + + InputStream getBinaryStream(ResultSet rs, String columnLabel) throws SQLException; + + int getBinarySqlType(); +} diff --git a/src/org/scada_lts/db/MysqlBinaryDataHandler.java b/src/org/scada_lts/db/MysqlBinaryDataHandler.java new file mode 100644 index 0000000000..058187f4e7 --- /dev/null +++ b/src/org/scada_lts/db/MysqlBinaryDataHandler.java @@ -0,0 +1,27 @@ +package org.scada_lts.db; + +import java.io.InputStream; +import java.sql.Blob; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +public class MysqlBinaryDataHandler implements BinaryDataHandler { + + @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 int getBinarySqlType() { + return Types.BLOB; + } +} diff --git a/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java b/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java index 1c4692f8f8..cf2a159241 100644 --- a/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java +++ b/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java @@ -10,9 +10,10 @@ import org.quartz.SchedulerException; import org.quartz.StatefulJob; import org.quartz.utils.Key; -import org.scada_lts.dao.DataSourceDAO; +import org.scada_lts.dao.IDataSourceDAO; import org.scada_lts.ds.StartStopDsRT; import org.scada_lts.ds.state.StartSleepStateDs; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.Map; @@ -32,7 +33,7 @@ public void execute(JobExecutionContext jobExecutionContext) throws JobExecution int id = (int) entry.getValue(); String name = (String) entry.getKey(); - DataSourceDAO dao = new DataSourceDAO(); + IDataSourceDAO dao = ApplicationBeans.getBean("dataSourceDAO", IDataSourceDAO.class); DataSourceVO ds = dao.getDataSource(id); HttpRetrieverDataSourceVO hrds = (HttpRetrieverDataSourceVO) ds; diff --git a/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java b/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java new file mode 100644 index 0000000000..515251aade --- /dev/null +++ b/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java @@ -0,0 +1,141 @@ +package org.scada_lts.factory; + +import com.serotonin.mango.Common; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public class DatabaseAwareBeanFactory implements FactoryBean, ApplicationContextAware { + + private static final Log LOG = LogFactory.getLog(DatabaseAwareBeanFactory.class); + private static final String DEFAULT_DB_TYPE = "mysql"; + private static final String DB_PLUGIN_CONFIG_PATTERN = "classpath*:META-INF/scadalts-db/%s.xml"; + private static final Object DB_PLUGIN_LOAD_MONITOR = new Object(); + private static final Set DB_PLUGIN_LOAD_ATTEMPTS = Collections.synchronizedSet(new HashSet()); + + private ApplicationContext applicationContext; + private String prefix; + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + + @Override + public T getObject() { + if (applicationContext == null) { + throw new IllegalStateException("ApplicationContext is not set for DatabaseAwareBeanFactory."); + } + if (prefix == null || prefix.trim().isEmpty()) { + throw new IllegalStateException("Bean prefix is not set for DatabaseAwareBeanFactory."); + } + + String dbKey = resolveDbKey(); + String targetBeanName = buildBeanName(dbKey); + if (applicationContext.containsBean(targetBeanName)) { + return getBean(targetBeanName); + } + + ensureDbPluginLoaded(dbKey); + if (applicationContext.containsBean(targetBeanName)) { + return getBean(targetBeanName); + } + + String msg = "DB plugin not found for db.type=" + dbKey + ". Expected bean '" + targetBeanName + + "'. Verify DB plugin JAR and META-INF/scadalts-db/" + dbKey + ".xml are present on classpath."; + LOG.error(msg); + throw new IllegalStateException(msg); + } + + @Override + public Class getObjectType() { + if (applicationContext == null || prefix == null || prefix.trim().isEmpty()) { + return Object.class; + } + String dbKey = resolveDbKey(); + Class type = applicationContext.getType(buildBeanName(dbKey)); + return type == null ? Object.class : type; + } + + @Override + public boolean isSingleton() { + return true; + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + private String resolveDbKey() { + String dbType = Common.getEnvironmentProfile().getString("db.type", DEFAULT_DB_TYPE); + return normalizeDbKey(dbType); + } + + private static String normalizeDbKey(String dbType) { + if (dbType == null) { + return ""; + } + String normalized = dbType.trim().toLowerCase(); + if ("postgresql".equals(normalized) || "pgsql".equals(normalized) || "pg".equals(normalized)) { + return "postgres"; + } + if ("mssqlserver".equals(normalized) || "mssql-server".equals(normalized) || "mssql".equals(normalized)) { + return "mssql"; + } + return normalized; + } + + private void ensureDbPluginLoaded(String dbKey) { + if (!(applicationContext instanceof ConfigurableApplicationContext)) { + return; + } + + String databaseAccessBeanName = "databaseAccess-" + dbKey; + if (applicationContext.containsBean(databaseAccessBeanName)) { + return; + } + + synchronized (DB_PLUGIN_LOAD_MONITOR) { + if (applicationContext.containsBean(databaseAccessBeanName)) { + return; + } + if (DB_PLUGIN_LOAD_ATTEMPTS.contains(dbKey)) { + return; + } + DB_PLUGIN_LOAD_ATTEMPTS.add(dbKey); + + ConfigurableApplicationContext configurable = (ConfigurableApplicationContext) applicationContext; + ConfigurableListableBeanFactory beanFactory = configurable.getBeanFactory(); + if (!(beanFactory instanceof BeanDefinitionRegistry)) { + return; + } + + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; + XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); + String pattern = String.format(DB_PLUGIN_CONFIG_PATTERN, dbKey); + int loaded = reader.loadBeanDefinitions(pattern); + if (loaded > 0) { + LOG.info("Loaded " + loaded + " DB plugin bean definition(s) from " + pattern); + } + } + } + + private String buildBeanName(String dbKey) { + return prefix + "-" + dbKey; + } + + @SuppressWarnings("unchecked") + private T getBean(String beanName) { + return (T) applicationContext.getBean(beanName); + } +} diff --git a/src/org/scada_lts/mango/adapter/MangoReport.java b/src/org/scada_lts/mango/adapter/MangoReport.java index 96bf21f136..7401af8aaf 100644 --- a/src/org/scada_lts/mango/adapter/MangoReport.java +++ b/src/org/scada_lts/mango/adapter/MangoReport.java @@ -23,7 +23,7 @@ import com.serotonin.mango.vo.report.ReportInstance; import com.serotonin.mango.vo.report.ReportUserComment; import com.serotonin.mango.vo.report.ReportVO; -import org.scada_lts.dao.report.ReportInstancePointDAO; +import org.scada_lts.dao.report.IReportInstancePointDAO; import java.util.List; import java.util.Map; @@ -65,7 +65,7 @@ public interface MangoReport { void saveReportInstance(ReportInstance instance); - int runReport(final ReportInstance instance, List points, ResourceBundle bundle); + int runReport(final ReportInstance instance, List points, ResourceBundle bundle); void reportInstanceData(int instanceId, final ReportDataStreamHandler handler); diff --git a/src/org/scada_lts/mango/service/CompoundEventDetectorService.java b/src/org/scada_lts/mango/service/CompoundEventDetectorService.java index ba4d64ce93..320c750af6 100644 --- a/src/org/scada_lts/mango/service/CompoundEventDetectorService.java +++ b/src/org/scada_lts/mango/service/CompoundEventDetectorService.java @@ -21,22 +21,23 @@ import com.serotonin.mango.rt.event.type.AuditEventUtils; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.event.CompoundEventDetectorDAO; +import org.scada_lts.dao.event.ICompoundEventDetectorDAO; import org.scada_lts.mango.adapter.MangoCompoundEventDetector; import com.serotonin.mango.Common; import com.serotonin.mango.rt.event.type.AuditEventType; import com.serotonin.mango.vo.event.CompoundEventDetectorVO; +import org.scada_lts.web.beans.ApplicationBeans; /** * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu */ public class CompoundEventDetectorService implements MangoCompoundEventDetector { - private CompoundEventDetectorDAO cedDao; + private final ICompoundEventDetectorDAO cedDao; public CompoundEventDetectorService() { - cedDao = new CompoundEventDetectorDAO(); + cedDao = ApplicationBeans.getBean("compoundEventDetectorDAO", ICompoundEventDetectorDAO.class); } @Override diff --git a/src/org/scada_lts/mango/service/DataPointService.java b/src/org/scada_lts/mango/service/DataPointService.java index af8a5cfb6e..38a936e17d 100644 --- a/src/org/scada_lts/mango/service/DataPointService.java +++ b/src/org/scada_lts/mango/service/DataPointService.java @@ -44,12 +44,13 @@ import org.apache.commons.logging.LogFactory; import org.jfree.util.Log; import org.scada_lts.dao.*; -import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.dao.model.point.PointValue; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO; import org.scada_lts.dao.pointhierarchy.PointHierarchyDAO; +import org.scada_lts.dao.pointvalues.IPointValueAmChartDAO; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.dao.pointvalues.PointValueAmChartDAO; -import org.scada_lts.dao.pointvalues.PointValueDAO; -import org.scada_lts.dao.watchlist.WatchListDAO; +import org.scada_lts.dao.watchlist.IWatchListDAO; import org.scada_lts.mango.adapter.MangoDataPoint; import org.scada_lts.mango.adapter.MangoPointHierarchy; import org.scada_lts.permissions.service.GetDataPointsWithAccess; @@ -75,36 +76,36 @@ public class DataPointService implements MangoDataPoint { private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(DataPointService.class); - private final DataPointDAO dataPointDAO; + private final IDataPointDAO dataPointDAO; - private final DataSourceDAO dataSourceDAO; + private final IDataSourceDAO dataSourceDAO; private final IUserCommentDAO userCommentDAO; private final IPointEventDetectorDAO pointEventDetectorDAO; - private final PointHierarchyDAO pointHierarchyDAO; + private final IPointHierarchyDAO pointHierarchyDAO; - private final DataPointUserDAO dataPointUserDAO ; + private final IDataPointUserDAO dataPointUserDAO ; - private static final PointValueDAO pointValueDAO = new PointValueDAO(); + private static final IPointValueDAO pointValueDAO = ApplicationBeans.getPointValueDAOBean(); - private final WatchListDAO watchListDAO; + private final IWatchListDAO watchListDAO; - private static final PointLinkDAO pointLinkDAO = new PointLinkDAO(); + private static final IPointLinkDAO pointLinkDAO = ApplicationBeans.getBean("pointLinkDAO", IPointLinkDAO.class); private final PointHierarchyService pointHierarchyService; - private static final PointValueAmChartDAO pointValueAmChartDao = new PointValueAmChartDAO(); + private static final IPointValueAmChartDAO pointValueAmChartDao = ApplicationBeans.getPointValueAmChartDAOBean(); private final GetObjectsWithAccess getDataPointsWithAccess; public DataPointService() { - this.dataPointDAO = ApplicationBeans.getBean("dataPointDAO", DataPointDAO.class); - this.dataSourceDAO = ApplicationBeans.getBean("dataSourceDAO", DataSourceDAO.class); - this.pointHierarchyDAO = ApplicationBeans.getBean("pointHierarchyDAO", PointHierarchyDAO.class); - this.dataPointUserDAO = ApplicationBeans.getBean("dataPointUserDAO", DataPointUserDAO.class); - this.watchListDAO = ApplicationBeans.getBean("watchListDAO", WatchListDAO.class); + this.dataPointDAO = ApplicationBeans.getDataPointDAOBean(); + this.dataSourceDAO = ApplicationBeans.getBean("dataSourceDAO", IDataSourceDAO.class); + this.pointHierarchyDAO = ApplicationBeans.getBean("pointHierarchyDAO", IPointHierarchyDAO.class); + this.dataPointUserDAO = ApplicationBeans.getDataPointUserDAOBean(); + this.watchListDAO = ApplicationBeans.getBean("watchListDAO", IWatchListDAO.class); this.pointHierarchyService = ApplicationBeans.getBean("pointHierarchyService", PointHierarchyService.class); this.userCommentDAO = ApplicationBeans.getUserCommentDaoBean(); this.getDataPointsWithAccess = new GetDataPointsWithAccess(dataPointDAO); @@ -353,7 +354,7 @@ public void insertDataPoint(final DataPointVO dp) { @Override public void updateDataPoint(final DataPointVO dp) { - DataPointVO oldDp = dataPointDAO.getDataPoint(dp.getId()); + DataPointVO oldDp = dataPointDAO.getDataPoint(dp.getXid()); if (oldDp.getPointLocator().getDataTypeId() != dp.getPointLocator().getDataTypeId()) { new PointValueDao().deletePointValuesWithMismatchedType(dp.getId(), dp.getPointLocator().getDataTypeId()); } diff --git a/src/org/scada_lts/mango/service/DataSourceService.java b/src/org/scada_lts/mango/service/DataSourceService.java index 46b71b7abb..f482bbc9d0 100644 --- a/src/org/scada_lts/mango/service/DataSourceService.java +++ b/src/org/scada_lts/mango/service/DataSourceService.java @@ -24,10 +24,7 @@ import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.dataSource.DataSourceVO; -import org.scada_lts.dao.DAO; -import org.scada_lts.dao.DataPointDAO; -import org.scada_lts.dao.DataSourceDAO; -import org.scada_lts.dao.MaintenanceEventDAO; +import org.scada_lts.dao.*; import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.ds.state.UserChangeEnableStateDs; import org.scada_lts.ds.state.UserCpChangeEnableStateDs; @@ -60,17 +57,17 @@ public class DataSourceService implements MangoDataSource { //TODO spring - private final DataSourceDAO dataSourceDAO; + private final IDataSourceDAO dataSourceDAO; private final DataPointService dataPointService; private final GetObjectsWithAccess, User> getDataSourcesWithAccess; public DataSourceService() { - this.dataSourceDAO = ApplicationBeans.getBean("dataSourceDAO", DataSourceDAO.class); + this.dataSourceDAO = ApplicationBeans.getBean("dataSourceDAO", IDataSourceDAO.class); this.dataPointService = new DataPointService(); - this.getDataSourcesWithAccess = new GetDataSourcesWithAccess(dataSourceDAO, new DataPointDAO()); + this.getDataSourcesWithAccess = new GetDataSourcesWithAccess(dataSourceDAO, ApplicationBeans.getDataPointDAOBean()); } - public DataSourceService(DataSourceDAO dataSourceDAO, DataPointService dataPointService, DataPointDAO dataPointDAO) { + public DataSourceService(IDataSourceDAO dataSourceDAO, DataPointService dataPointService, IDataPointDAO dataPointDAO) { this.dataSourceDAO = dataSourceDAO; this.dataPointService = dataPointService; this.getDataSourcesWithAccess = new GetDataSourcesWithAccess(dataSourceDAO, dataPointDAO); @@ -175,7 +172,8 @@ public void deleteDataSource(final int dataSourceId) { @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) private void deleteInTransaction(final int dataSourceId) { - new MaintenanceEventDAO().deleteMaintenanceEventsForDataSource(dataSourceId); + IMaintenanceEventDAO meDAO = ApplicationBeans.getBean("maintenanceEventDAO", IMaintenanceEventDAO.class); + meDAO.deleteMaintenanceEventsForDataSource(dataSourceId); dataSourceDAO.delete(dataSourceId); UsersProfileService usersProfileService = new UsersProfileService(); usersProfileService.updatePermissions(); diff --git a/src/org/scada_lts/mango/service/EventService.java b/src/org/scada_lts/mango/service/EventService.java index 9fc28fc2ff..01a3f2a689 100644 --- a/src/org/scada_lts/mango/service/EventService.java +++ b/src/org/scada_lts/mango/service/EventService.java @@ -39,7 +39,8 @@ import org.scada_lts.dao.DAO; import org.scada_lts.dao.IUserCommentDAO; import org.scada_lts.dao.event.EventDAO; -import org.scada_lts.dao.event.UserEventDAO; +import org.scada_lts.dao.event.IEventDAO; +import org.scada_lts.dao.event.IUserEventDAO; import org.scada_lts.mango.adapter.MangoEvent; import org.scada_lts.utils.SQLPageWithTotal; import org.scada_lts.web.beans.ApplicationBeans; @@ -66,14 +67,14 @@ public class EventService implements MangoEvent { private static final Log LOG = LogFactory.getLog(EventService.class); - private final EventDAO eventDAO; - private final UserEventDAO userEventDAO; + private final IEventDAO eventDAO; + private final IUserEventDAO userEventDAO; private final IUserCommentDAO userCommentDAO; private final SystemSettingsService systemSettingsService; public EventService() { - eventDAO = new EventDAO(); - userEventDAO = new UserEventDAO(); + eventDAO = ApplicationBeans.getBean("eventDAO", IEventDAO.class); + userEventDAO = ApplicationBeans.getUserEventDAOBean(); userCommentDAO = ApplicationBeans.getUserCommentDaoBean(); systemSettingsService = ApplicationBeans.getBean("systemSettingsService", SystemSettingsService.class); } diff --git a/src/org/scada_lts/mango/service/FlexProjectService.java b/src/org/scada_lts/mango/service/FlexProjectService.java index e4bde74148..b265197a10 100644 --- a/src/org/scada_lts/mango/service/FlexProjectService.java +++ b/src/org/scada_lts/mango/service/FlexProjectService.java @@ -19,8 +19,9 @@ import br.org.scadabr.api.vo.FlexProject; import com.serotonin.mango.Common; -import org.scada_lts.dao.FlexProjectDAO; +import org.scada_lts.dao.IFlexProjectDAO; import org.scada_lts.mango.adapter.MangoFlexProject; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.List; @@ -31,7 +32,7 @@ */ public class FlexProjectService implements MangoFlexProject { - private FlexProjectDAO flexProjectDAO = new FlexProjectDAO(); + private final IFlexProjectDAO flexProjectDAO = ApplicationBeans.getFlexProjectDAOBean(); @Override public int saveFlexProject(int id, String name, String description, String xmlConfig) { diff --git a/src/org/scada_lts/mango/service/MailingListService.java b/src/org/scada_lts/mango/service/MailingListService.java index 97f3e49b02..bad6ede96e 100644 --- a/src/org/scada_lts/mango/service/MailingListService.java +++ b/src/org/scada_lts/mango/service/MailingListService.java @@ -26,12 +26,13 @@ import org.apache.commons.logging.LogFactory; import org.joda.time.DateTime; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.mailingList.MailingListDAO; -import org.scada_lts.dao.mailingList.MailingListInactiveDAO; -import org.scada_lts.dao.mailingList.MailingListMemberDAO; +import org.scada_lts.dao.mailingList.IMailingListDAO; +import org.scada_lts.dao.mailingList.IMailingListInactiveDAO; +import org.scada_lts.dao.mailingList.IMailingListMemberDAO; import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.mango.adapter.MangoMailingList; import org.scada_lts.service.CommunicationChannelType; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -49,15 +50,15 @@ public class MailingListService implements MangoMailingList { //TODO // @Resource - private static final MailingListDAO mailingListDAO = new MailingListDAO(); + private static final IMailingListDAO mailingListDAO = ApplicationBeans.getBean("mailingListDAO", IMailingListDAO.class); //TODO // @Resource - private static final MailingListInactiveDAO mailingListInactiveDAO = new MailingListInactiveDAO(); + private static final IMailingListInactiveDAO mailingListInactiveDAO = ApplicationBeans.getMailingListInactiveDAOBean(); //TODO // @Resource - private static final MailingListMemberDAO mailingListMemberDAO = new MailingListMemberDAO(); + private static final IMailingListMemberDAO mailingListMemberDAO = ApplicationBeans.getMailingListMemberDAOBean(); private static final Log LOG = LogFactory.getLog(MailingListService.class); diff --git a/src/org/scada_lts/mango/service/MaintenanceEventService.java b/src/org/scada_lts/mango/service/MaintenanceEventService.java index 51bc930ac5..506e0c010b 100644 --- a/src/org/scada_lts/mango/service/MaintenanceEventService.java +++ b/src/org/scada_lts/mango/service/MaintenanceEventService.java @@ -22,8 +22,9 @@ import com.serotonin.mango.rt.event.type.AuditEventUtils; import com.serotonin.mango.vo.event.MaintenanceEventVO; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.MaintenanceEventDAO; +import org.scada_lts.dao.IMaintenanceEventDAO; import org.scada_lts.mango.adapter.MangoMaintenanceEvent; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.dao.EmptyResultDataAccessException; import java.util.List; @@ -35,7 +36,7 @@ */ public class MaintenanceEventService implements MangoMaintenanceEvent { - private MaintenanceEventDAO maintenanceEventDAO = new MaintenanceEventDAO(); + private final IMaintenanceEventDAO maintenanceEventDAO = ApplicationBeans.getBean("maintenanceEventDAO", IMaintenanceEventDAO.class); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/PendingEventService.java b/src/org/scada_lts/mango/service/PendingEventService.java index cecbf8308b..228aebaad0 100644 --- a/src/org/scada_lts/mango/service/PendingEventService.java +++ b/src/org/scada_lts/mango/service/PendingEventService.java @@ -24,8 +24,8 @@ import com.serotonin.mango.vo.UserComment; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.scada_lts.dao.IPendingEventsDAO; import org.scada_lts.dao.IUserCommentDAO; -import org.scada_lts.dao.PendingEventsDAO; import org.scada_lts.service.IHighestAlarmLevelService; import org.scada_lts.utils.SystemSettingsUtils; import org.scada_lts.web.beans.ApplicationBeans; @@ -42,7 +42,7 @@ public class PendingEventService { private final IUserCommentDAO userCommentDAO; - private final PendingEventsDAO pendingEventsDAO; + private final IPendingEventsDAO pendingEventsDAO; private final SystemSettingsService systemSettingsService; @@ -51,7 +51,7 @@ public class PendingEventService { public PendingEventService() { userCommentDAO = ApplicationBeans.getUserCommentDaoBean(); highestAlarmLevelService = ApplicationBeans.getHighestAlarmLevelServiceBean(); - pendingEventsDAO = new PendingEventsDAO(); + pendingEventsDAO = ApplicationBeans.getPendingEventsDAOBean(); systemSettingsService = new SystemSettingsService(); } diff --git a/src/org/scada_lts/mango/service/PointLinkService.java b/src/org/scada_lts/mango/service/PointLinkService.java index defaa2b634..220ab0b16a 100644 --- a/src/org/scada_lts/mango/service/PointLinkService.java +++ b/src/org/scada_lts/mango/service/PointLinkService.java @@ -22,8 +22,9 @@ import com.serotonin.mango.rt.event.type.AuditEventUtils; import com.serotonin.mango.vo.link.PointLinkVO; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.PointLinkDAO; +import org.scada_lts.dao.IPointLinkDAO; import org.scada_lts.mango.adapter.MangoPointLink; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.List; @@ -34,7 +35,7 @@ */ public class PointLinkService implements MangoPointLink { - private static PointLinkDAO pointLinkDAO = new PointLinkDAO(); + private static IPointLinkDAO pointLinkDAO = ApplicationBeans.getBean("pointLinkDAO", IPointLinkDAO.class); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index e51ab11529..f187ccb8d0 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -41,13 +41,13 @@ import com.serotonin.mango.vo.dataSource.meta.MetaPointLocatorVO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.GenericDaoCR; import org.scada_lts.dao.model.point.PointValue; -import org.scada_lts.dao.pointvalues.PointValueDAO; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.mango.adapter.MangoPointValues; import org.scada_lts.monitor.type.IntegerMonitor; import org.scada_lts.utils.SystemSettingsUtils; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; @@ -75,14 +75,14 @@ public class PointValueService implements MangoPointValues { private static List UNSAVED_POINT_VALUES = new ArrayList(); private static final int POINT_VALUE_INSERT_VALUES_COUNT = 4; - private PointValueDAO pointValueDAO = new PointValueDAO(); + private IPointValueDAO pointValueDAO; private DataPointService dataPointService = new DataPointService(); private DataSourceService dataSourceService = new DataSourceService(); private static final Log LOG = LogFactory.getLog(PointValueService.class); public PointValueService() { - + pointValueDAO = ApplicationBeans.getPointValueDAOBean(); } /** @@ -220,7 +220,7 @@ public void savePointValue(int pointId, PointValueTime pointValue) { @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) long savePointValueInTrasaction(final int pointId, final int dataType, double dvalue, final long time, final String svalue, final SetPointSource source, boolean async) { // Apply database specific bounds on double values. - dvalue = PointValueDAO.getInstance().applyBounds(dvalue); + dvalue = pointValueDAO.applyBounds(dvalue); if (async) { BatchWriteBehind.add(new BatchWriteBehindEntry(pointId, dataType, @@ -249,7 +249,7 @@ public long savePointValue(final int pointId, final int dataType, double dvalue, final long time, final String svalue, final SetPointSource source, boolean async) { // Apply database specific bounds on double values. - dvalue = PointValueDAO.getInstance().applyBounds(dvalue); + dvalue = pointValueDAO.applyBounds(dvalue); if (async) { BatchWriteBehind.add(new BatchWriteBehindEntry(pointId, dataType, @@ -276,7 +276,7 @@ public long savePointValue(final int pointId, final int dataType, double dvalue, private long savePointValueImpl(int pointId, int dataType, double dvalue, long time, String svalue, SetPointSource source) { - long id = (Long) PointValueDAO.getInstance().create(pointId, dataType, dvalue, time)[0]; + long id = (Long) pointValueDAO.create(pointId, dataType, dvalue, time)[0]; if (svalue == null && dataType == DataTypes.IMAGE) { @@ -302,7 +302,7 @@ private long savePointValueImpl(int pointId, int dataType, double dvalue, long t else shortString = svalue; } - PointValueDAO.getInstance().createAnnotation(id, shortString, longString, sourceType, sourceId); + pointValueDAO.createAnnotation(id, shortString, longString, sourceType, sourceId); } @@ -320,41 +320,33 @@ private List getLstPointValueTime(List lstIn) { public List getPointValues(int dataPointId, long since) { - List lst = PointValueDAO.getInstance().filtered( - PointValueDAO.POINT_VALUE_FILTER_BASE_ON_DATA_POINT_ID_AND_TIME_STAMP, - new Object[]{dataPointId, since}, GenericDaoCR.NO_LIMIT); + List lst = pointValueDAO.getPointValues(dataPointId, since); return getLstPointValueTime(lst); } public List getPointValuesBetween(int dataPointId, long from, long to) { - List lst = PointValueDAO.getInstance().filtered( - PointValueDAO.POINT_VALUE_FILTER_BASE_ON_DATA_POINT_ID_AND_TIME_STAMP_FROM_TO, - new Object[]{dataPointId, from, to}, GenericDaoCR.NO_LIMIT); + List lst = pointValueDAO.getPointValuesBetween(dataPointId, from, to); return getLstPointValueTime(lst); } public List getLatestPointValues(int dataPointId, int limit) { - List lst = PointValueDAO.getInstance().filtered( - PointValueDAO.POINT_VALUE_FILTER_LAST_BASE_ON_DATA_POINT_ID, - new Object[]{dataPointId}, limit); + List lst = pointValueDAO.getLatestPointValues(dataPointId, limit); return getLstPointValueTime(lst); } public List getLatestPointValues(int dataPointId, int limit, long before) { - List lst = PointValueDAO.getInstance().filtered( - PointValueDAO.POINT_VALUE_FILTER_LAST_BASE_ON_DATA_POINT_ID, - new Object[]{dataPointId, before}, limit); + List lst = pointValueDAO.getLatestPointValues(dataPointId, limit, before); return getLstPointValueTime(lst); } public PointValueTime getLatestPointValue(int dataPointId) { - Long maxTs = PointValueDAO.getInstance().getLatestPointValue(dataPointId); + Long maxTs = pointValueDAO.getLatestPointValue(dataPointId); if (maxTs == null || maxTs == 0) return null; - List lstValues = PointValueDAO.getInstance().findByIdAndTs(dataPointId, maxTs); + List lstValues = pointValueDAO.findByIdAndTs(dataPointId, maxTs); if (lstValues.isEmpty()) return null; @@ -369,12 +361,12 @@ public PointValueTime getLatestPointValue(int dataPointId) { } public PointValueTime getPointValueBefore(int dataPointId, long time) { - return PointValueDAO.getInstance().getPointValueBefore(dataPointId, time); + return pointValueDAO.getPointValueBefore(dataPointId, time); } public PointValueTime getPointValueAt(int dataPointId, long time) { try { - return PointValueDAO.getInstance().getPointValueAt(dataPointId, time); + return pointValueDAO.getPointValueAt(dataPointId, time); } catch (Exception ex) { return null; } @@ -382,42 +374,42 @@ public PointValueTime getPointValueAt(int dataPointId, long time) { @Deprecated public long deletePointValuesBeforeWithOutLast(int dataPointId, long time) { - return PointValueDAO.getInstance().deletePointValuesBeforeWithOutLast(dataPointId, time); + return pointValueDAO.deletePointValuesBeforeWithOutLast(dataPointId, time); } @Override public long deletePointValuesBeforeWithOutLastTwo(int dataPointId, long time) { - return PointValueDAO.getInstance().deletePointValuesBeforeWithOutLastTwo(dataPointId, time); + return pointValueDAO.deletePointValuesBeforeWithOutLastTwo(dataPointId, time); } @Override public long dateRangeCount(int dataPointId, long from, long to) { - return PointValueDAO.getInstance().dateRangeCount(dataPointId, from, to); + return pointValueDAO.dateRangeCount(dataPointId, from, to); } @Override public long getInceptionDate(int dataPointId) { - return PointValueDAO.getInstance().getInceptionDate(dataPointId); + return pointValueDAO.getInceptionDate(dataPointId); } @Override public long getStartTime(List dataPointIds) { - return PointValueDAO.getInstance().getStartTime(dataPointIds); + return pointValueDAO.getStartTime(dataPointIds); } @Override public long getEndTime(List dataPointIds) { - return PointValueDAO.getInstance().getEndTime(dataPointIds); + return pointValueDAO.getEndTime(dataPointIds); } @Override public LongPair getStartAndEndTime(List dataPointIds) { - return PointValueDAO.getInstance().getStartAndEndTime(dataPointIds); + return pointValueDAO.getStartAndEndTime(dataPointIds); } @Override public List getFiledataIds() { - return PointValueDAO.getInstance().getFiledataIds(); + return pointValueDAO.getFiledataIds(); } /** @@ -512,6 +504,7 @@ static class BatchWriteBehind extends AbstractBeforeAfterWorkItem { "BatchWriteBehind.ENTRIES_MONITOR", null); private static final IntegerMonitor INSTANCES_MONITOR = new IntegerMonitor( "BatchWriteBehind.INSTANCES_MONITOR", null); + private static IPointValueDAO pointValueDAO; static { @@ -524,6 +517,10 @@ static class BatchWriteBehind extends AbstractBeforeAfterWorkItem { Common.MONITORED_VALUES.addIfMissingStatMonitor(INSTANCES_MONITOR); } + public BatchWriteBehind() { + pointValueDAO = ApplicationBeans.getPointValueDAOBean(); + } + static void add(BatchWriteBehindEntry e) { synchronized (ENTRIES) { ENTRIES.push(e); @@ -549,7 +546,9 @@ static void add(BatchWriteBehindEntry e) { private int instancesSize; private int entriesSize; - public BatchWriteBehind() {} + public static void setPointValueDAO(IPointValueDAO dao) { + pointValueDAO = dao; + } @Override public void work() { @@ -580,7 +579,7 @@ public void work() { int retries = 10; while (true) { try { - PointValueDAO.getInstance().executeBatchUpdateInsert(params); + pointValueDAO.executeBatchUpdateInsert(params); break; } catch (ConcurrencyFailureException e) { @@ -633,7 +632,7 @@ public String getDetails() { } public PointValueTime getPointValue(long id) { - PointValueTime pointValueTime = PointValueDAO.getInstance().getPointValue(id); + PointValueTime pointValueTime = pointValueDAO.getPointValue(id); /*if(pointValueTime instanceof AnnotatedPointValueTime) { updateAnnotation((AnnotatedPointValueTime) pointValueTime); }*/ @@ -646,22 +645,22 @@ public void updatePointValueAnnotations(int userId) { @Override public long deletePointValues(int dataPointId) { - return PointValueDAO.getInstance().deletePointValue(dataPointId); + return pointValueDAO.deletePointValue(dataPointId); } @Override public long deleteAllPointValue() { - return PointValueDAO.getInstance().deleteAllPointData(); + return pointValueDAO.deleteAllPointData(); } @Override public long deletePointValuesWithMismatchedType(int dataPointId, int dataType) { - return PointValueDAO.getInstance().deletePointValuesWithMismatchedType(dataPointId, dataType); + return pointValueDAO.deletePointValuesWithMismatchedType(dataPointId, dataType); } @Override public long deletePointValuesWithValueLimit(int dataPointId, int limit) { - return PointValueDAO.getInstance().deletePointValuesWithValueLimit(dataPointId, limit); + return pointValueDAO.deletePointValuesWithValueLimit(dataPointId, limit); } public void updateMetaDataPointByScript(User user, String xid) { diff --git a/src/org/scada_lts/mango/service/PublisherService.java b/src/org/scada_lts/mango/service/PublisherService.java index a7e7798c16..e45647e1f0 100644 --- a/src/org/scada_lts/mango/service/PublisherService.java +++ b/src/org/scada_lts/mango/service/PublisherService.java @@ -21,8 +21,9 @@ import com.serotonin.mango.vo.publish.PublishedPointVO; import com.serotonin.mango.vo.publish.PublisherVO; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.PublisherDAO; +import org.scada_lts.dao.IPublisherDAO; import org.scada_lts.mango.adapter.MangoPublisher; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.Collections; import java.util.Comparator; @@ -35,7 +36,7 @@ */ public class PublisherService implements MangoPublisher { - private PublisherDAO publisherDAO = new PublisherDAO(); + private final IPublisherDAO publisherDAO = ApplicationBeans.getBean("publisherDAO", IPublisherDAO.class); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/ReportService.java b/src/org/scada_lts/mango/service/ReportService.java index a7437a1c64..57738b92d9 100644 --- a/src/org/scada_lts/mango/service/ReportService.java +++ b/src/org/scada_lts/mango/service/ReportService.java @@ -34,6 +34,7 @@ import org.scada_lts.permissions.service.GetReportInstancesWithAccess; import org.scada_lts.permissions.service.GetReportsWithAccess; import org.scada_lts.serorepl.utils.StringUtils; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Service; @@ -52,20 +53,20 @@ @Service public class ReportService implements MangoReport { - private ReportDAO reportDAO; - private ReportInstanceDAO reportInstanceDAO; - private ReportInstanceDataDAO reportInstanceDataDAO; - private ReportInstancePointDAO reportInstancePointDAO; - private ReportInstanceUserCommentDAO reportInstanceUserCommentDAO; + private IReportDAO reportDAO; + private IReportInstanceDAO reportInstanceDAO; + private IReportInstanceDataDAO reportInstanceDataDAO; + private IReportInstancePointDAO reportInstancePointDAO; + private IReportInstanceUserCommentDAO reportInstanceUserCommentDAO; private GetReportsWithAccess getReportsWithAccess; private GetReportInstancesWithAccess getReportInstancesWithAccess; public ReportService() { - this.reportDAO = new ReportDAO(); - this.reportInstanceDAO = new ReportInstanceDAO(); - this.reportInstanceDataDAO = new ReportInstanceDataDAO(); - this.reportInstancePointDAO = new ReportInstancePointDAO(); - this.reportInstanceUserCommentDAO = new ReportInstanceUserCommentDAO(); + this.reportDAO = ApplicationBeans.getBean("reportDAO", IReportDAO.class); + this.reportInstanceDAO = ApplicationBeans.getBean("reportInstanceDAO", IReportInstanceDAO.class); + this.reportInstanceDataDAO = ApplicationBeans.getBean("reportInstanceDataDAO", IReportInstanceDataDAO.class); + this.reportInstancePointDAO = ApplicationBeans.getBean("reportInstancePointDAO", IReportInstancePointDAO.class); + this.reportInstanceUserCommentDAO = ApplicationBeans.getReportInstanceUserCommentDAOBean(); this.getReportsWithAccess = new GetReportsWithAccess(reportDAO); this.getReportInstancesWithAccess = new GetReportInstancesWithAccess(reportInstanceDAO); } @@ -184,7 +185,7 @@ public void saveReportInstance(ReportInstance reportInstance) { } @Override - public int runReport(final ReportInstance instance, List points, ResourceBundle bundle) { + public int runReport(final ReportInstance instance, List points, ResourceBundle bundle) { PointValueService pointValueService = new PointValueService(); int count = 0; @@ -215,7 +216,7 @@ else if (instance.isToNow()) { } // For each point. - for (ReportInstancePointDAO.PointInfo pointInfo : points) { + for (IReportInstancePointDAO.PointInfo pointInfo : points) { DataPointVO point = pointInfo.getPoint(); int dataType = point.getPointLocator().getDataTypeId(); diff --git a/src/org/scada_lts/mango/service/ScheduledEventService.java b/src/org/scada_lts/mango/service/ScheduledEventService.java index c732c947ab..87349cad73 100644 --- a/src/org/scada_lts/mango/service/ScheduledEventService.java +++ b/src/org/scada_lts/mango/service/ScheduledEventService.java @@ -22,8 +22,9 @@ import com.serotonin.mango.rt.event.type.AuditEventUtils; import com.serotonin.mango.vo.event.ScheduledEventVO; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.ScheduledEventDAO; +import org.scada_lts.dao.IScheduledEventDAO; import org.scada_lts.mango.adapter.MangoScheduledEvent; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.List; @@ -34,7 +35,7 @@ */ public class ScheduledEventService implements MangoScheduledEvent { - private ScheduledEventDAO scheduledEventDAO = new ScheduledEventDAO(); + private final IScheduledEventDAO scheduledEventDAO = ApplicationBeans.getBean("scheduledEventDAO", IScheduledEventDAO.class); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/ScriptService.java b/src/org/scada_lts/mango/service/ScriptService.java index 5de8ae9ed3..9b87e76ff2 100644 --- a/src/org/scada_lts/mango/service/ScriptService.java +++ b/src/org/scada_lts/mango/service/ScriptService.java @@ -3,8 +3,9 @@ import br.org.scadabr.vo.scripting.ScriptVO; import com.serotonin.mango.Common; import com.serotonin.mango.vo.GetExtendedNameComparator; -import org.scada_lts.dao.ScriptDAO; +import org.scada_lts.dao.IScriptDAO; import org.scada_lts.mango.adapter.MangoScript; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.stereotype.Service; import java.util.List; @@ -12,7 +13,7 @@ @Service public class ScriptService implements MangoScript { - private ScriptDAO scriptDAO = new ScriptDAO(); + private final IScriptDAO scriptDAO = ApplicationBeans.getBean("scriptDAO", IScriptDAO.class); @Override public void saveScript(final ScriptVO vo) { diff --git a/src/org/scada_lts/mango/service/SystemSettingsService.java b/src/org/scada_lts/mango/service/SystemSettingsService.java index d8d59ec293..b33f40fb5a 100644 --- a/src/org/scada_lts/mango/service/SystemSettingsService.java +++ b/src/org/scada_lts/mango/service/SystemSettingsService.java @@ -3,6 +3,7 @@ import br.org.scadabr.db.configuration.ConfigurationDB; import com.fasterxml.jackson.databind.ObjectMapper; import com.serotonin.mango.Common; +import com.serotonin.mango.db.DatabaseAccess; import com.serotonin.mango.db.dao.DataPointDao; import com.serotonin.mango.rt.dataImage.DataPointSyncMode; import com.serotonin.mango.rt.event.type.AuditEventType; @@ -18,6 +19,7 @@ import com.serotonin.web.i18n.LocalizableMessage; import org.apache.commons.logging.LogFactory; import org.scada_lts.config.ScadaConfig; +import org.scada_lts.dao.ISystemSettingsDAO; import org.scada_lts.dao.SystemSettingsDAO; import org.scada_lts.mango.adapter.MangoEvent; import org.scada_lts.serorepl.utils.DirectoryInfo; @@ -49,10 +51,10 @@ public class SystemSettingsService { private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(SystemSettingsService.class); - private SystemSettingsDAO systemSettingsDAO; + private final ISystemSettingsDAO systemSettingsDAO; public SystemSettingsService() { - systemSettingsDAO = new SystemSettingsDAO(); + systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); } public Map getSettings() { @@ -256,6 +258,14 @@ public void saveSystemInfoSettings(JsonSettingsSystemInfo json) { } public String getDatabaseType() { + try { + DatabaseAccess databaseAccess = DatabaseAccess.getDatabaseAccess(); + if (databaseAccess != null) { + return databaseAccess.getTypeKey(); + } + } catch (Exception ignore) { + // fallback to env.properties + } return Common.getEnvironmentProfile().getString("db.type", "derby"); } @@ -290,12 +300,17 @@ public Map getDatabaseSize() { data.put("filedataSize", com.serotonin.util.DirectoryUtils.bytesDescription(filedataSize)); data.put("totalSize", com.serotonin.util.DirectoryUtils.bytesDescription(dbSize + filedataSize)); - if (getDatabaseType().equalsIgnoreCase("mysql")) { + String dbType = getDatabaseType(); + if (dbType.equalsIgnoreCase("mysql") || dbType.equalsIgnoreCase("postgres")) { double size = systemSettingsDAO.getDataBaseSize(); - data.put("databaseSize", size + "MB"); - data.put("filedataCount", 0); - data.put("filedataSize", 0); - data.put("totalSize", size + "MB"); + if (size >= 0) { + data.put("databaseSize", size + "MB"); + data.put("filedataCount", 0); + data.put("filedataSize", 0); + data.put("totalSize", size + "MB"); + } else { + data.put("databaseSize", "common.unknown"); + } } List counts = new DataPointDao().getTopPointHistoryCounts(); diff --git a/src/org/scada_lts/mango/service/WatchListService.java b/src/org/scada_lts/mango/service/WatchListService.java index 5fb80eb81e..f66cc4892a 100644 --- a/src/org/scada_lts/mango/service/WatchListService.java +++ b/src/org/scada_lts/mango/service/WatchListService.java @@ -20,9 +20,11 @@ import java.sql.SQLException; import java.util.List; +import com.serotonin.mango.db.dao.DataPointDao; import com.serotonin.mango.vo.User; import org.scada_lts.dao.DAO; import org.scada_lts.dao.model.ScadaObjectIdentifier; +import org.scada_lts.dao.watchlist.IWatchListDAO; import org.scada_lts.dao.watchlist.WatchListDAO; import org.scada_lts.mango.adapter.MangoWatchList; import org.scada_lts.permissions.service.GetObjectsWithAccess; @@ -36,7 +38,6 @@ import org.springframework.transaction.annotation.Transactional; import com.serotonin.mango.Common; -import com.serotonin.mango.db.dao.DataPointDao; import com.serotonin.mango.view.ShareUser; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.WatchList; @@ -48,19 +49,19 @@ @Service public class WatchListService implements MangoWatchList { - private WatchListDAO watchListDAO; + private IWatchListDAO watchListDAO; private GetShareUsers getShareUsers; private UsersProfileService usersProfileService; private GetObjectsWithAccess getObjectsWithAccess; public WatchListService() { - this.watchListDAO = ApplicationBeans.getBean("watchListDAO", WatchListDAO.class); + this.watchListDAO = ApplicationBeans.getBean("watchListDAO", IWatchListDAO.class); this.getShareUsers = ApplicationBeans.getWatchListGetShareUsersBean(); this.usersProfileService = ApplicationBeans.getUsersProfileService(); this.getObjectsWithAccess = new GetWatchListsWithAccess(watchListDAO); } - public WatchListService(WatchListDAO watchListDAO, GetShareUsers getShareUsers, UsersProfileService usersProfileService) { + public WatchListService(IWatchListDAO watchListDAO, GetShareUsers getShareUsers, UsersProfileService usersProfileService) { this.watchListDAO = watchListDAO; this.getShareUsers = getShareUsers; this.usersProfileService = usersProfileService; diff --git a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataPointService.java b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataPointService.java index 379b690af2..4d7265f5ac 100644 --- a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataPointService.java +++ b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataPointService.java @@ -25,16 +25,16 @@ import com.serotonin.mango.vo.hierarchy.PointFolder; import com.serotonin.mango.vo.hierarchy.PointHierarchy; -import org.scada_lts.dao.DataPointDAO; +import org.scada_lts.dao.IDataPointDAO; import org.scada_lts.mango.adapter.MangoDataPoint; import java.util.*; public final class OnlyMigrationDataPointService implements MangoDataPoint { - private DataPointDAO dataPointDAO; + private IDataPointDAO dataPointDAO; - public OnlyMigrationDataPointService(DataPointDAO dataPointDAO) { + public OnlyMigrationDataPointService(IDataPointDAO dataPointDAO) { this.dataPointDAO = dataPointDAO; } diff --git a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataSourceService.java b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataSourceService.java index f63a286c74..1c8fa8c0db 100644 --- a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataSourceService.java +++ b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationDataSourceService.java @@ -20,7 +20,7 @@ import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.dataSource.DataSourceVO; -import org.scada_lts.dao.DataSourceDAO; +import org.scada_lts.dao.IDataSourceDAO; import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.mango.adapter.MangoDataSource; @@ -29,9 +29,9 @@ public final class OnlyMigrationDataSourceService implements MangoDataSource { - private DataSourceDAO dataSourceDAO; + private IDataSourceDAO dataSourceDAO; - public OnlyMigrationDataSourceService(DataSourceDAO dataSourceDAO) { + public OnlyMigrationDataSourceService(IDataSourceDAO dataSourceDAO) { this.dataSourceDAO = dataSourceDAO; } diff --git a/src/org/scada_lts/permissions/service/DataPointProfilePermissionsService.java b/src/org/scada_lts/permissions/service/DataPointProfilePermissionsService.java index a001749a61..5ed11e772a 100644 --- a/src/org/scada_lts/permissions/service/DataPointProfilePermissionsService.java +++ b/src/org/scada_lts/permissions/service/DataPointProfilePermissionsService.java @@ -3,12 +3,9 @@ import br.org.scadabr.vo.usersProfiles.UsersProfileVO; import com.serotonin.mango.vo.permission.DataPointAccess; import org.scada_lts.dao.IUsersProfileDAO; -import org.springframework.stereotype.Service; - import java.util.List; -@Service public class DataPointProfilePermissionsService implements PermissionsService { private final IUsersProfileDAO usersProfileDAO; diff --git a/src/org/scada_lts/permissions/service/DataPointUserPermissionsService.java b/src/org/scada_lts/permissions/service/DataPointUserPermissionsService.java index 21f628e225..199decba00 100644 --- a/src/org/scada_lts/permissions/service/DataPointUserPermissionsService.java +++ b/src/org/scada_lts/permissions/service/DataPointUserPermissionsService.java @@ -2,15 +2,15 @@ import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.permission.DataPointAccess; -import org.scada_lts.dao.DataPointUserDAO; +import org.scada_lts.dao.IDataPointUserDAO; import java.util.List; public class DataPointUserPermissionsService implements PermissionsService { - private final DataPointUserDAO dataPointUserDAO; + private final IDataPointUserDAO dataPointUserDAO; - public DataPointUserPermissionsService(DataPointUserDAO dataPointUserDAO) { + public DataPointUserPermissionsService(IDataPointUserDAO dataPointUserDAO) { this.dataPointUserDAO = dataPointUserDAO; } diff --git a/src/org/scada_lts/permissions/service/DataSourceProfilePermissionsService.java b/src/org/scada_lts/permissions/service/DataSourceProfilePermissionsService.java index c758b5d220..5445f9f464 100644 --- a/src/org/scada_lts/permissions/service/DataSourceProfilePermissionsService.java +++ b/src/org/scada_lts/permissions/service/DataSourceProfilePermissionsService.java @@ -2,11 +2,9 @@ import br.org.scadabr.vo.usersProfiles.UsersProfileVO; import org.scada_lts.dao.IUsersProfileDAO; -import org.springframework.stereotype.Service; import java.util.List; -@Service public class DataSourceProfilePermissionsService implements PermissionsService { private final IUsersProfileDAO usersProfileDAO; diff --git a/src/org/scada_lts/permissions/service/DataSourceUserPermissionsService.java b/src/org/scada_lts/permissions/service/DataSourceUserPermissionsService.java index 315db2e53d..03e3c34041 100644 --- a/src/org/scada_lts/permissions/service/DataSourceUserPermissionsService.java +++ b/src/org/scada_lts/permissions/service/DataSourceUserPermissionsService.java @@ -2,15 +2,15 @@ import com.serotonin.mango.vo.User; -import org.scada_lts.dao.DataSourceDAO; +import org.scada_lts.dao.IDataSourceDAO; import java.util.List; public class DataSourceUserPermissionsService implements PermissionsService { - private final DataSourceDAO dataSourceDAO; + private final IDataSourceDAO dataSourceDAO; - public DataSourceUserPermissionsService(DataSourceDAO dataSourceDAO) { + public DataSourceUserPermissionsService(IDataSourceDAO dataSourceDAO) { this.dataSourceDAO = dataSourceDAO; } diff --git a/src/org/scada_lts/permissions/service/GetDataPointsWithAccess.java b/src/org/scada_lts/permissions/service/GetDataPointsWithAccess.java index f5a1d301ed..fd6fe241b9 100644 --- a/src/org/scada_lts/permissions/service/GetDataPointsWithAccess.java +++ b/src/org/scada_lts/permissions/service/GetDataPointsWithAccess.java @@ -5,7 +5,7 @@ import com.serotonin.mango.vo.permission.Permissions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.DataPointDAO; +import org.scada_lts.dao.IDataPointDAO; import org.scada_lts.dao.model.ScadaObjectIdentifier; import java.util.Collection; @@ -19,9 +19,9 @@ public class GetDataPointsWithAccess implements GetObjectsWithAccess object) { return user.isAdmin(); } - public static boolean hasDataSourceReadPermission(User user, DataSourceVO dataSource, DataPointDAO dataPointDAO) { + public static boolean hasDataSourceReadPermission(User user, DataSourceVO dataSource, IDataPointDAO dataPointDAO) { if(user == null) { LOG.warn("user is null"); return false; diff --git a/src/org/scada_lts/permissions/service/GetReportInstancesWithAccess.java b/src/org/scada_lts/permissions/service/GetReportInstancesWithAccess.java index 201b99f9b1..7183ca09ce 100644 --- a/src/org/scada_lts/permissions/service/GetReportInstancesWithAccess.java +++ b/src/org/scada_lts/permissions/service/GetReportInstancesWithAccess.java @@ -7,7 +7,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.model.ScadaObjectIdentifier; -import org.scada_lts.dao.report.ReportInstanceDAO; +import org.scada_lts.dao.report.IReportInstanceDAO; import java.util.Collections; import java.util.List; @@ -19,9 +19,9 @@ public class GetReportInstancesWithAccess implements GetObjectsWithAccess { private final IUsersProfileDAO usersProfileDAO; diff --git a/src/org/scada_lts/permissions/service/ViewUserPermissionsService.java b/src/org/scada_lts/permissions/service/ViewUserPermissionsService.java index d83aebc8c0..921d680551 100644 --- a/src/org/scada_lts/permissions/service/ViewUserPermissionsService.java +++ b/src/org/scada_lts/permissions/service/ViewUserPermissionsService.java @@ -4,11 +4,9 @@ import br.org.scadabr.vo.permission.ViewAccess; import com.serotonin.mango.vo.User; import org.scada_lts.dao.IViewDAO; -import org.springframework.stereotype.Service; import java.util.List; -@Service public class ViewUserPermissionsService implements PermissionsService { private final IViewDAO viewDAO; diff --git a/src/org/scada_lts/permissions/service/WatchListGetShareUsers.java b/src/org/scada_lts/permissions/service/WatchListGetShareUsers.java index 44f7980f91..64db3d3c46 100644 --- a/src/org/scada_lts/permissions/service/WatchListGetShareUsers.java +++ b/src/org/scada_lts/permissions/service/WatchListGetShareUsers.java @@ -2,7 +2,7 @@ import com.serotonin.mango.view.ShareUser; import com.serotonin.mango.vo.WatchList; -import org.scada_lts.dao.watchlist.WatchListDAO; +import org.scada_lts.dao.watchlist.IWatchListDAO; import java.util.List; @@ -10,9 +10,9 @@ public class WatchListGetShareUsers implements GetShareUsers { - private final WatchListDAO watchListDAO; + private final IWatchListDAO watchListDAO; - public WatchListGetShareUsers(WatchListDAO watchListDAO) { + public WatchListGetShareUsers(IWatchListDAO watchListDAO) { this.watchListDAO = watchListDAO; } diff --git a/src/org/scada_lts/permissions/service/WatchListProfilePermissionsService.java b/src/org/scada_lts/permissions/service/WatchListProfilePermissionsService.java index f96edfa7da..6ff9cdf740 100644 --- a/src/org/scada_lts/permissions/service/WatchListProfilePermissionsService.java +++ b/src/org/scada_lts/permissions/service/WatchListProfilePermissionsService.java @@ -3,11 +3,9 @@ import br.org.scadabr.vo.permission.WatchListAccess; import br.org.scadabr.vo.usersProfiles.UsersProfileVO; import org.scada_lts.dao.IUsersProfileDAO; -import org.springframework.stereotype.Service; import java.util.List; -@Service public class WatchListProfilePermissionsService implements PermissionsService{ private final IUsersProfileDAO usersProfileDAO; diff --git a/src/org/scada_lts/permissions/service/WatchListUserPermissionsService.java b/src/org/scada_lts/permissions/service/WatchListUserPermissionsService.java index 15720a56c4..9c3127f188 100644 --- a/src/org/scada_lts/permissions/service/WatchListUserPermissionsService.java +++ b/src/org/scada_lts/permissions/service/WatchListUserPermissionsService.java @@ -2,15 +2,15 @@ import br.org.scadabr.vo.permission.WatchListAccess; import com.serotonin.mango.vo.User; -import org.scada_lts.dao.watchlist.WatchListDAO; +import org.scada_lts.dao.watchlist.IWatchListDAO; import java.util.List; public class WatchListUserPermissionsService implements PermissionsService { - private final WatchListDAO watchListDAO; + private final IWatchListDAO watchListDAO; - public WatchListUserPermissionsService(WatchListDAO watchListDAO) { + public WatchListUserPermissionsService(IWatchListDAO watchListDAO) { this.watchListDAO = watchListDAO; } diff --git a/src/org/scada_lts/service/SynopticPanelService.java b/src/org/scada_lts/service/SynopticPanelService.java index 874fdf797a..cfb2864686 100644 --- a/src/org/scada_lts/service/SynopticPanelService.java +++ b/src/org/scada_lts/service/SynopticPanelService.java @@ -1,9 +1,10 @@ package org.scada_lts.service; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.SynopticPanelDAO; +import org.scada_lts.dao.ISynopticPanelDAO; import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.service.model.SynopticPanel; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; @@ -20,7 +21,7 @@ @Service public class SynopticPanelService { - private final SynopticPanelDAO synopticPanelDAO = new SynopticPanelDAO(); + private final ISynopticPanelDAO synopticPanelDAO = ApplicationBeans.getBean("synopticPanelDAO", ISynopticPanelDAO.class); public List getSimpleSynopticPanelsList() { return synopticPanelDAO.getSimpleList(); diff --git a/src/org/scada_lts/service/ViewHierarchyService.java b/src/org/scada_lts/service/ViewHierarchyService.java index dc3c71653f..c599067023 100644 --- a/src/org/scada_lts/service/ViewHierarchyService.java +++ b/src/org/scada_lts/service/ViewHierarchyService.java @@ -23,15 +23,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.GenericHierarchyDAO; -import org.scada_lts.dao.IViewDAO; -import org.scada_lts.dao.ViewHierarchyDAO; +import org.scada_lts.dao.*; import org.scada_lts.dao.model.viewshierarchy.ViewHierarchyNode; import org.scada_lts.dao.model.viewshierarchy.ViewInViewHierarchyNode; import org.scada_lts.service.model.ViewHierarchyJSON; -import org.scada_lts.web.beans.ApplicationBeans; import org.slf4j.profiler.Profiler; -import org.springframework.stereotype.Service; import com.serotonin.mango.view.View; @@ -41,7 +37,6 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ -@Service public class ViewHierarchyService { private static final Log LOG = LogFactory.getLog(ViewHierarchyService.class); @@ -52,15 +47,12 @@ public class ViewHierarchyService { public static final int ROOT_ID = -1; - private ViewHierarchyDAO vhDAO = new ViewHierarchyDAO(); + private IViewHierarchyDAO vhDAO; private final IViewDAO viewDAO; + - public ViewHierarchyService(){ - this.viewDAO = ApplicationBeans.getViewDaoBean(); - } - - public ViewHierarchyService(ViewHierarchyDAO vhDAO, IViewDAO viewDAO){ + public ViewHierarchyService(IViewHierarchyDAO vhDAO, IViewDAO viewDAO){ this.vhDAO = vhDAO; this.viewDAO = viewDAO; } diff --git a/src/org/scada_lts/service/pointhierarchy/PointHierarchyService.java b/src/org/scada_lts/service/pointhierarchy/PointHierarchyService.java index 1b877b89aa..3f5c81d64c 100644 --- a/src/org/scada_lts/service/pointhierarchy/PointHierarchyService.java +++ b/src/org/scada_lts/service/pointhierarchy/PointHierarchyService.java @@ -27,11 +27,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.cache.PointHierarchyCache; -import org.scada_lts.dao.DataPointDAO; -import org.scada_lts.dao.HierarchyDAO; +import org.scada_lts.dao.IHierarchyDAO; +import org.scada_lts.dao.IDataPointDAO; import org.scada_lts.dao.pointhierarchy.PointHierarchyDAO; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; -import org.scada_lts.dao.pointhierarchy.PointHierarchyXidDAO; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyXidDAO; import org.scada_lts.exception.CacheHierarchyException; import org.scada_lts.mango.service.DataPointService; import org.scada_lts.service.model.PointHierarchyConsistency; @@ -53,13 +53,13 @@ public class PointHierarchyService { // cache private static final Log LOG = LogFactory.getLog(PointHierarchyService.class); - private final PointHierarchyXidDAO pointHierarchyXidDAO; - private final DataPointDAO dataPointDAO; - private final HierarchyDAO hierarchyDAO; + private final IPointHierarchyXidDAO pointHierarchyXidDAO; + private final IDataPointDAO dataPointDAO; + private final IHierarchyDAO hierarchyDAO; - public PointHierarchyService(PointHierarchyXidDAO pointHierarchyXidDAO, - DataPointDAO dataPointDAO, - HierarchyDAO hierarchyDAO) { + public PointHierarchyService(IPointHierarchyXidDAO pointHierarchyXidDAO, + IDataPointDAO dataPointDAO, + IHierarchyDAO hierarchyDAO) { this.pointHierarchyXidDAO = pointHierarchyXidDAO; this.dataPointDAO = dataPointDAO; this.hierarchyDAO = hierarchyDAO; @@ -259,7 +259,7 @@ public List getPointHierarchyWithEmptyByKey(User user, int k return PointHierarchyUtils.getPointHierarchyWithEmptyByKey(user, hierarchyDAO, dataPointDAO, key); } - protected PointHierarchyXidDAO getPointHierarchyDAO() { + protected IPointHierarchyXidDAO getPointHierarchyDAO() { return pointHierarchyXidDAO; } } diff --git a/src/org/scada_lts/service/pointhierarchy/PointHierarchyXidService.java b/src/org/scada_lts/service/pointhierarchy/PointHierarchyXidService.java index 7196018bcb..596e9de2ce 100644 --- a/src/org/scada_lts/service/pointhierarchy/PointHierarchyXidService.java +++ b/src/org/scada_lts/service/pointhierarchy/PointHierarchyXidService.java @@ -17,22 +17,19 @@ */ package org.scada_lts.service.pointhierarchy; -import com.serotonin.ShouldNeverHappenException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.cache.PointHierarchyCache; -import org.scada_lts.dao.DataPointDAO; -import org.scada_lts.dao.HierarchyDAO; +import org.scada_lts.dao.IHierarchyDAO; +import org.scada_lts.dao.IDataPointDAO; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; -import org.scada_lts.dao.pointhierarchy.PointHierarchyXidDAO; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyXidDAO; import org.scada_lts.web.mvc.api.dto.FolderPointHierarchy; import org.scada_lts.web.mvc.api.dto.FolderPointHierarchyExport; import org.scada_lts.web.mvc.api.dto.ObjectHierarchy; -import org.scada_lts.web.mvc.api.dto.ObjectHierarchyType; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.stream.Collectors; /** @@ -44,7 +41,7 @@ public class PointHierarchyXidService extends PointHierarchyService { private static final Log LOG = LogFactory.getLog(PointHierarchyXidService.class); - public PointHierarchyXidService(PointHierarchyXidDAO pointHierarchyXidDAO, DataPointDAO dataPointDAO, HierarchyDAO hierarchyDAO) { + public PointHierarchyXidService(IPointHierarchyXidDAO pointHierarchyXidDAO, IDataPointDAO dataPointDAO, IHierarchyDAO hierarchyDAO) { super(pointHierarchyXidDAO, dataPointDAO, hierarchyDAO); } diff --git a/src/org/scada_lts/utils/GetDataPointsUtils.java b/src/org/scada_lts/utils/GetDataPointsUtils.java index 316fe5a76f..572f1d8f44 100644 --- a/src/org/scada_lts/utils/GetDataPointsUtils.java +++ b/src/org/scada_lts/utils/GetDataPointsUtils.java @@ -5,7 +5,6 @@ import com.serotonin.db.KeyValuePair; import com.serotonin.mango.Common; import com.serotonin.mango.DataTypes; -import com.serotonin.mango.rt.event.handlers.SetPointHandlerRT; import com.serotonin.mango.view.View; import com.serotonin.mango.view.component.CompoundChild; import com.serotonin.mango.view.component.CompoundComponent; @@ -26,6 +25,7 @@ import org.scada_lts.mango.service.DataPointService; import org.scada_lts.mango.service.EventService; import org.scada_lts.permissions.service.GetDataPointsWithAccess; +import org.springframework.dao.EmptyResultDataAccessException; import java.util.*; import java.util.function.Function; @@ -67,7 +67,7 @@ public static Set getDataPointsByView(User user, View view, DataP public static Set getTargetDataPointsByPointLinks(User user, List pointLinks, DataPointService dataPointService) { Set dataPoints = new HashSet<>(); for (PointLinkVO pointLinkVO : pointLinks) { - DataPointVO targetDataPoint = dataPointService.getDataPoint(pointLinkVO.getTargetPointId()); + DataPointVO targetDataPoint = safeGetDataPoint(dataPointService, pointLinkVO.getTargetPointId()); if(targetDataPoint != null && targetDataPoint.getPointLocator() != null && targetDataPoint.getPointLocator().isSettable() && GetDataPointsWithAccess.hasDataPointSetPermission(user, targetDataPoint)) @@ -79,7 +79,7 @@ public static Set getTargetDataPointsByPointLinks(User user, List public static Set getSourceDataPointsByPointLinks(User user, List pointLinks, DataPointService dataPointService) { Set dataPoints = new HashSet<>(); for (PointLinkVO pointLinkVO : pointLinks) { - DataPointVO sourceDataPoint = dataPointService.getDataPoint(pointLinkVO.getSourcePointId()); + DataPointVO sourceDataPoint = safeGetDataPoint(dataPointService, pointLinkVO.getSourcePointId()); if(sourceDataPoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, sourceDataPoint)) dataPoints.add(new DataPointBean(sourceDataPoint)); } @@ -176,21 +176,38 @@ private static Set getDataPointIdsByViewComponents(View view) { return ids; } + private static DataPointVO safeGetDataPoint(DataPointService dataPointService, int pointId) { + if(pointId < 1) { + return null; + } + try { + return dataPointService.getDataPoint(pointId); + } catch (EmptyResultDataAccessException ex) { + return null; + } + } + private static Set getDataPointsByEventHandlers(List eventHandlers, DataPointService dataPointService, User user) { Set dataPoints = new HashSet<>(); for (EventHandlerVO eventHandler : eventHandlers) { - if(eventHandler.createRuntime() instanceof SetPointHandlerRT) { + if(eventHandler.getHandlerType() == EventHandlerVO.TYPE_SET_POINT) { DataPointVO targetPoint = dataPointService.getDataPoint(eventHandler.getTargetPointId()); - DataPointVO activePoint = dataPointService.getDataPoint(eventHandler.getActivePointId()); - DataPointVO inactivePoint = dataPointService.getDataPoint(eventHandler.getInactivePointId()); if (targetPoint != null && GetDataPointsWithAccess.hasDataPointSetPermission(user, targetPoint)) { dataPoints.add(targetPoint); } - if (activePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, activePoint)) { - dataPoints.add(activePoint); + + if (eventHandler.getActiveAction() == EventHandlerVO.SET_ACTION_POINT_VALUE) { + DataPointVO activePoint = dataPointService.getDataPoint(eventHandler.getActivePointId()); + if (activePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, activePoint)) { + dataPoints.add(activePoint); + } } - if (inactivePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, inactivePoint)) { - dataPoints.add(inactivePoint); + + if (eventHandler.getInactiveAction() == EventHandlerVO.SET_ACTION_POINT_VALUE) { + DataPointVO inactivePoint = dataPointService.getDataPoint(eventHandler.getInactivePointId()); + if (inactivePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, inactivePoint)) { + dataPoints.add(inactivePoint); + } } } } diff --git a/src/org/scada_lts/utils/PointHierarchyUtils.java b/src/org/scada_lts/utils/PointHierarchyUtils.java index 05804a920c..28d45455cc 100644 --- a/src/org/scada_lts/utils/PointHierarchyUtils.java +++ b/src/org/scada_lts/utils/PointHierarchyUtils.java @@ -3,8 +3,8 @@ import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.permission.Permissions; -import org.scada_lts.dao.DataPointDAO; -import org.scada_lts.dao.HierarchyDAO; +import org.scada_lts.dao.IHierarchyDAO; +import org.scada_lts.dao.IDataPointDAO; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; import org.scada_lts.recursive.CreatePointHierarchyTree; @@ -21,8 +21,8 @@ public final class PointHierarchyUtils { private PointHierarchyUtils() {} public static List getPointHierarchyWithEmptyByKey(User user, - HierarchyDAO hierarchyDAO, - DataPointDAO dataPointDAO, + IHierarchyDAO hierarchyDAO, + IDataPointDAO dataPointDAO, int key) { List pointNodes = getPointNodesWithAccess(user, dataPointDAO); List folderNodes = getFolderNodes(hierarchyDAO); @@ -30,25 +30,25 @@ public static List getPointHierarchyWithEmptyByKey(User user } public static List getPointHierarchyByKey(User user, - HierarchyDAO hierarchyDAO, - DataPointDAO dataPointDAO, + IHierarchyDAO hierarchyDAO, + IDataPointDAO dataPointDAO, int key) { List pointNodes = getPointNodesWithAccess(user, dataPointDAO); List folderNodes = getFolderNodes(hierarchyDAO); return getPointHierarchyNodes(key, pointNodes, folderNodes, false); } - public static PointHierarchyNode getPointHierarchyWithEmptyRoot(User user, HierarchyDAO hierarchyDAO, DataPointDAO dataPointDAO) { + public static PointHierarchyNode getPointHierarchyWithEmptyRoot(User user, IHierarchyDAO hierarchyDAO, IDataPointDAO dataPointDAO) { return getRootNode(user, hierarchyDAO, dataPointDAO); } - public static PointHierarchyNode getPointHierarchyRoot(User user, HierarchyDAO hierarchyDAO, DataPointDAO dataPointDAO) { + public static PointHierarchyNode getPointHierarchyRoot(User user, IHierarchyDAO hierarchyDAO, IDataPointDAO dataPointDAO) { PointHierarchyNode root = getRootNode(user, hierarchyDAO, dataPointDAO); cleanTree(root); return root; } - public static List getPointNodesWithAccess(User user, DataPointDAO dataPointDAO) { + public static List getPointNodesWithAccess(User user, IDataPointDAO dataPointDAO) { List dataPoints = dataPointDAO.getDataPoints(); List pointNodes = new ArrayList<>(); for (DataPointVO point : dataPoints) { @@ -128,7 +128,7 @@ private static boolean isNotEmpty(PointHierarchyNode root, return false; } - private static List getFolderNodes(HierarchyDAO hierarchyDAO) { + private static List getFolderNodes(IHierarchyDAO hierarchyDAO) { List folderNodes = hierarchyDAO.getHierarchy(); if(folderNodes == null) return Collections.emptyList(); @@ -156,7 +156,7 @@ private static boolean filter(boolean withEmpty, List pointA return !node.isFolder() || withEmpty || isNotEmpty(node, pointAndFolderNodes, TREE_DEPTH); } - private static PointHierarchyNode getRootNode(User user, HierarchyDAO hierarchyDAO, DataPointDAO dataPointDAO) { + private static PointHierarchyNode getRootNode(User user, IHierarchyDAO hierarchyDAO, IDataPointDAO dataPointDAO) { List folderNodes = getFolderNodes(hierarchyDAO); List pointNodes = getPointNodesWithAccess(user, dataPointDAO); List pointAndFolderNodes = new ArrayList<>(); diff --git a/src/org/scada_lts/web/beans/ApplicationBeans.java b/src/org/scada_lts/web/beans/ApplicationBeans.java index 8fb00b1e84..7563ae08ea 100644 --- a/src/org/scada_lts/web/beans/ApplicationBeans.java +++ b/src/org/scada_lts/web/beans/ApplicationBeans.java @@ -7,19 +7,30 @@ import com.serotonin.mango.Common; import com.serotonin.mango.util.LoggingUtils; import com.serotonin.mango.view.View; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.login.ILoggedUsers; import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.WatchList; import com.serotonin.mango.vo.permission.DataPointAccess; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.scada_lts.db.BinaryDataHandler; import org.scada_lts.dao.*; +import org.scada_lts.dao.alarms.IAlarmsDAO; import org.scada_lts.dao.cache.*; +import org.scada_lts.dao.event.IUserEventDAO; +import org.scada_lts.dao.mailingList.IMailingListInactiveDAO; +import org.scada_lts.dao.mailingList.IMailingListMemberDAO; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyXidDAO; +import org.scada_lts.dao.pointvalues.IPointValueAdnnotationsDAO; +import org.scada_lts.dao.pointvalues.IPointValueAmChartDAO; import org.scada_lts.mango.service.UserCommentService; import org.scada_lts.mango.service.UsersProfileService; import org.scada_lts.permissions.service.*; +import org.scada_lts.dao.report.IReportInstanceUserCommentDAO; import org.scada_lts.service.IHighestAlarmLevelService; +import org.scada_lts.service.ViewHierarchyService; import org.scada_lts.web.ws.services.DataPointServiceWebSocket; import org.scada_lts.web.ws.services.UserEventServiceWebSocket; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -38,6 +49,10 @@ public static T getBean(String beanName, Class type) { return getBeanFromContext(beanName, type); } + public static ApplicationContext getApplicationContext() { + return getBeansContext(); + } + public static IUserDAO getUserDaoBean() { boolean userCacheEnabled = Common.getEnvironmentProfile().getBoolean(UserCacheable.CACHE_ENABLED_KEY, true); return userCacheEnabled ? @@ -153,6 +168,14 @@ public static ObjectMapper getObjectMapper() { return getBeanFromContext("objectMapper", ObjectMapper.class); } + public static BinaryDataHandler getBinaryDataHandler() { + BinaryDataHandler handler = getBeanFromContext("binaryDataHandler", BinaryDataHandler.class); + if (handler == null) { + throw new IllegalStateException("binaryDataHandler bean is missing."); + } + return handler; + } + public static class Lazy { private Lazy() {} @@ -203,4 +226,74 @@ private static ApplicationContext getBeansContext() { private static ApplicationContext getBeansApplication() { return GetApplicationBeans.context() == null ? null : GetApplicationBeans.context(); } + + public static ViewHierarchyService getViewHierarchyServiceBean() { + return getBean("viewHierarchyService", ViewHierarchyService.class); + } + + public static IDataPointDAO getDataPointDAOBean(){ + return getBean("dataPointDAO", IDataPointDAO.class); + } + + public static IPointValueDAO getPointValueDAOBean(){ + return getBean("pointValueDAO", IPointValueDAO.class); + } + + public static IDataPointUserDAO getDataPointUserDAOBean() { + return getBean("dataPointUserDAO", IDataPointUserDAO.class); + } + + public static IEventDetectorTemplateDAO getEventDetectorTemplateDAOBean() { + return getBean("eventDetectorTemplateDAO", IEventDetectorTemplateDAO.class); + } + + public static IFlexProjectDAO getFlexProjectDAOBean() { + return getBean("flexProjectDAO", IFlexProjectDAO.class); + } + + public static IHierarchyDAO getHierarchyDAOBean() { + return getBean("hierarchyDAO", IHierarchyDAO.class); + } + + public static IPendingEventsDAO getPendingEventsDAOBean() { + return getBean("pendingEventsDAO", IPendingEventsDAO.class); + } + + public static ISystemSettingsDAO getSystemSettingsDAOBean() { + return getBean("systemSettingsDAO", ISystemSettingsDAO.class); + } + + public static IUserEventDAO getUserEventDAOBean() { + return getBean("userEventDAO", IUserEventDAO.class); + } + + public static IMailingListInactiveDAO getMailingListInactiveDAOBean() { + return getBean("mailingListInactiveDAO", IMailingListInactiveDAO.class); + } + + public static IMailingListMemberDAO getMailingListMemberDAOBean() { + return getBean("mailingListMemberDAO", IMailingListMemberDAO.class); + } + + public static IPointHierarchyXidDAO getPointHierarchyXidDAOBean() { + return getBean("pointHierarchyXidDAO", IPointHierarchyXidDAO.class); + } + + public static IPointValueAdnnotationsDAO getPointValueAdnnotationsDAOBean() { + return getBean("pointValueAdnnotationsDAO", IPointValueAdnnotationsDAO.class); + } + + public static IPointValueAmChartDAO getPointValueAmChartDAOBean() { + return getBean("pointValueAmChartDAO", IPointValueAmChartDAO.class); + } + + public static IReportInstanceUserCommentDAO getReportInstanceUserCommentDAOBean() { + return getBean("reportInstanceUserCommentDAO", IReportInstanceUserCommentDAO.class); + } + + public static IAlarmsDAO getAlarmsDAOBean() { + return getBean("alarmsDAO", IAlarmsDAO.class); + } + + } diff --git a/src/org/scada_lts/web/mvc/api/DataPointApiService.java b/src/org/scada_lts/web/mvc/api/DataPointApiService.java index 68dedf9bb0..49adb9a05a 100644 --- a/src/org/scada_lts/web/mvc/api/DataPointApiService.java +++ b/src/org/scada_lts/web/mvc/api/DataPointApiService.java @@ -289,14 +289,20 @@ private List searchDataPoint(HttpServletRequest request, try { if(user.isAdmin()) { int page = searchDataPointJson.getPage(); - if((searchDataPointJson.getDataTypes() == null || searchDataPointJson.getDataTypes().isEmpty()) - && (searchDataPointJson.getSettable() == null)) { + boolean hasTypeOrSettableFilter = + (searchDataPointJson.getDataTypes() != null && !searchDataPointJson.getDataTypes().isEmpty()) + || (searchDataPointJson.getSettable() != null); + boolean hasExcludeIds = + searchDataPointJson.getExcludeIds() != null && !searchDataPointJson.getExcludeIds().isEmpty(); + if(!hasTypeOrSettableFilter && !hasExcludeIds) { return dataPointService.getDataPoints(searchDataPointJson.getKeywordSearch(), searchDataPointJson.getExcludeIds(), searchDataPointJson.isStartsWith(), page, searchDataPointJson.getLimit()); } else { + // Exclude ids are handled by filterByExcludeIds below. + // Keep DAO query free from NOT IN to avoid SQL-dialect issues. List points = dataPointService.getDataPoints(searchDataPointJson.getKeywordSearch(), - searchDataPointJson.getExcludeIds(), searchDataPointJson.isStartsWith(), + null, searchDataPointJson.isStartsWith(), -1, -1); return filteredAndPaginationPoints(user, searchDataPointJson, points); } diff --git a/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchy.java b/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchy.java index 252a38a350..8f6c5667a9 100644 --- a/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchy.java +++ b/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchy.java @@ -1,6 +1,6 @@ package org.scada_lts.web.mvc.api.dto; -import org.scada_lts.dao.pointhierarchy.PointHierarchyXidDAO; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyXidDAO; import org.scada_lts.web.beans.validation.xss.XssProtect; import java.io.Serializable; @@ -42,7 +42,7 @@ public String toString() { return "type=" + type + ", xid='" + xid; } - public boolean move(String destinationFolderXid, PointHierarchyXidDAO pointHierarchyXidDAO) { + public boolean move(String destinationFolderXid, IPointHierarchyXidDAO pointHierarchyXidDAO) { return type.move(xid, destinationFolderXid, pointHierarchyXidDAO); } } diff --git a/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchyType.java b/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchyType.java index 3845e10a2b..c224795999 100644 --- a/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchyType.java +++ b/src/org/scada_lts/web/mvc/api/dto/ObjectHierarchyType.java @@ -2,13 +2,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.pointhierarchy.PointHierarchyXidDAO; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyXidDAO; public enum ObjectHierarchyType { FOLDER { @Override - public boolean move(String moveObjectXid, String destinationFolderXid, PointHierarchyXidDAO pointHierarchyXidDAO) { + public boolean move(String moveObjectXid, String destinationFolderXid, IPointHierarchyXidDAO pointHierarchyXidDAO) { boolean res = false; try { res = pointHierarchyXidDAO.updateFolder(moveObjectXid, destinationFolderXid); @@ -20,7 +20,7 @@ public boolean move(String moveObjectXid, String destinationFolderXid, PointHier }, POINT { @Override - public boolean move(String moveObjectXid, String destinationFolderXid, PointHierarchyXidDAO pointHierarchyXidDAO) { + public boolean move(String moveObjectXid, String destinationFolderXid, IPointHierarchyXidDAO pointHierarchyXidDAO) { boolean res = false; try { res = pointHierarchyXidDAO.updateParentPoint(moveObjectXid, destinationFolderXid); @@ -33,6 +33,6 @@ public boolean move(String moveObjectXid, String destinationFolderXid, PointHier private static final Log LOG = LogFactory.getLog(ObjectHierarchyType.class); - public abstract boolean move(String moveObjectXid, String destinationFolderXid, PointHierarchyXidDAO pointHierarchyXidDAO); + public abstract boolean move(String moveObjectXid, String destinationFolderXid, IPointHierarchyXidDAO pointHierarchyXidDAO); } diff --git a/src/org/scada_lts/web/mvc/controller/SqlController.java b/src/org/scada_lts/web/mvc/controller/SqlController.java index ae75bec143..68929837a0 100644 --- a/src/org/scada_lts/web/mvc/controller/SqlController.java +++ b/src/org/scada_lts/web/mvc/controller/SqlController.java @@ -43,9 +43,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.serotonin.mango.Common; import com.serotonin.mango.vo.permission.Permissions; import com.serotonin.util.SerializationHelper; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.web.util.WebUtils; /** @@ -128,12 +128,7 @@ private static List> query(final String sql, final JdbcTemplate jdb row.add(rs.getString(i + 1)); else if (meta.getColumnType(i + 1) == Types.LONGVARBINARY || meta.getColumnType(i + 1) == Types.BLOB || meta.getColumnType(i + 1) == Types.BINARY) { - Object o; - if (Common.getEnvironmentProfile().getString("db.type").equals("postgres")) { - o = SerializationHelper.readObject(rs.getBinaryStream(i + 1)); - } else { - o = SerializationHelper.readObject(rs.getBlob(i + 1).getBinaryStream()); - } + Object o = SerializationHelper.readObject(ApplicationBeans.getBinaryDataHandler().getBinaryStream(rs, i + 1)); row.add("Serialized data(" + o + ")"); } else row.add(rs.getObject(i + 1)); diff --git a/test/br/org/scadabr/db/scenarios/ScenarioWithAdministrador.java b/test/br/org/scadabr/db/scenarios/ScenarioWithAdministrador.java index 9fa7f3c318..4770659ffd 100644 --- a/test/br/org/scadabr/db/scenarios/ScenarioWithAdministrador.java +++ b/test/br/org/scadabr/db/scenarios/ScenarioWithAdministrador.java @@ -4,6 +4,7 @@ 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.mango.db.dao.UserDao; import com.serotonin.mango.vo.User; @@ -28,8 +29,8 @@ public void setupScenario(DatabaseAccess database) { user.setDataPointPermissions(new LinkedList()); new UserDao().saveUser(user); - new SystemSettingsDAO().setValue( - SystemSettingsDAO.DATABASE_SCHEMA_VERSION, Common.getVersion()); + ISystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO(); + systemSettingsDAO.setValue(SystemSettingsDAO.DATABASE_SCHEMA_VERSION, Common.getVersion()); } } diff --git a/test/com/serotonin/mango/db/MySQLAccessTest.java b/test/com/serotonin/mango/db/MySQLAccessTest.java index 3402bd7152..54c8a707da 100644 --- a/test/com/serotonin/mango/db/MySQLAccessTest.java +++ b/test/com/serotonin/mango/db/MySQLAccessTest.java @@ -19,7 +19,7 @@ import com.serotonin.db.spring.ConnectionCallbackVoid; import com.serotonin.mango.Common; -import com.serotonin.mango.db.DatabaseAccess.DatabaseType; +import org.scada_lts.dao.ISystemSettingsDAO; import org.scada_lts.dao.SystemSettingsDAO; import com.serotonin.mango.db.dao.UserDao; import com.serotonin.mango.vo.User; @@ -31,7 +31,7 @@ public class MySQLAccessTest extends AbstractMySQLDependentTest { @Test public void databaseTypeShouldBeORACLE11G() { - assertEquals(DatabaseType.MYSQL, mysqlAccess.getType()); + assertEquals("mysql", mysqlAccess.getTypeKey()); } @Test @@ -75,8 +75,8 @@ public void afterInitializeEmptyDatabaseShouldSaveDatabaseSchemaVersion() { useScenario(new TablelessDatabaseScenario()); // automatically // initializes // DatabaseAccess - final String savedValue = new SystemSettingsDAO() - .getValue(SystemSettingsDAO.DATABASE_SCHEMA_VERSION); + ISystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO(); + final String savedValue = systemSettingsDAO.getDatabaseSchemaVersion(SystemSettingsDAO.DATABASE_SCHEMA_VERSION, null); assertEquals(Common.getVersion(), savedValue); } diff --git a/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java b/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java index 61d67caf57..d91ea6dbc0 100644 --- a/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java +++ b/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java @@ -16,20 +16,23 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.scada_lts.dao.DAO; +import org.scada_lts.dao.IDataPointDAO; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.mango.service.SystemSettingsService; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.jdbc.core.JdbcTemplate; import utils.TestUtils; import java.util.ArrayList; import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) -@PrepareForTest({DAO.class, Common.class, PointValueDAO.class, RuntimeManager.class}) +@PrepareForTest({DAO.class, Common.class, PointValueDAO.class, RuntimeManager.class, IDataPointDAO.class, ApplicationBeans.class}) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*", "javax.activation.*", "javax.management.*"}) public class RuntimeManagerCreateDataPointRtTest { @@ -39,6 +42,17 @@ public class RuntimeManagerCreateDataPointRtTest { @Before public void config() throws Exception { + + IPointValueDAO pointValueDAOMock = mock(IPointValueDAO.class); + when(pointValueDAOMock.filtered( + eq(PointValueDAO.POINT_VALUE_FILTER_LAST_BASE_ON_DATA_POINT_ID), + any(Object[].class), anyInt())) + .thenReturn(new ArrayList<>()); + + mockStatic(org.scada_lts.web.beans.ApplicationBeans.class); + when(org.scada_lts.web.beans.ApplicationBeans.getPointValueDAOBean()) + .thenReturn(pointValueDAOMock); + DAO dao = mock(DAO.class); JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class); when(dao.getJdbcTemp()).thenReturn(jdbcTemplate); diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java index be4f8410fa..9f5902154c 100644 --- a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java +++ b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java @@ -22,6 +22,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.scada_lts.dao.DAO; import org.scada_lts.dao.IUserDAO; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.login.ILoggedUsers; import org.scada_lts.mango.service.PointValueService; @@ -31,7 +32,7 @@ import java.util.ResourceBundle; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.*; @@ -59,14 +60,15 @@ public void config() throws Exception { IUserDAO userDAO = mock(IUserDAO.class); when(userDAO.getUser(eq(12))).thenReturn(sourceUser); - mockStatic(PointValueDAO.class); - when(PointValueDAO.getInstance()).thenReturn(new PointValueDAOMemory(userDAO)); - ILoggedUsers loggedUsers = mock(ILoggedUsers.class); when(loggedUsers.getUser(eq(12))).thenReturn(sourceUser); mockStatic(ApplicationBeans.class); + PointValueDAOMemory memoryDao = new PointValueDAOMemory(userDAO); + when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); + when(ApplicationBeans.getPointValueDAOBean()) + .thenReturn(memoryDao); SystemSettingsService systemSettingsService = mock(SystemSettingsService.class); whenNew(SystemSettingsService.class).withAnyArguments().thenReturn(systemSettingsService); diff --git a/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java b/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java index 96f99ed5f0..6ba1496eeb 100644 --- a/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java +++ b/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java @@ -1,5 +1,7 @@ package com.serotonin.mango.rt.dataImage.datapointrt.config; +import com.serotonin.mango.db.DatabaseAccess; +import org.springframework.jdbc.core.JdbcTemplate; import utils.TestUtils; import com.serotonin.mango.Common; import com.serotonin.mango.db.dao.DataPointDao; @@ -46,6 +48,7 @@ import utils.UsersDAOMemory; import utils.mock.PowerMockUtils; +import javax.sql.DataSource; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -57,7 +60,7 @@ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest({DAO.class, Common.class, PointValueDAO.class, DataPointDao.class, DataSourceDao.class, - VirtualDataSourceRT.class, RuntimeManager.class, PointValueService.class, PointValueDAO.class, ApplicationBeans.class, PointValueDao.class, + VirtualDataSourceRT.class, RuntimeManager.class, PointValueService.class, IPointValueDAO.class, ApplicationBeans.class, PointValueDao.class, SystemSettingsDAO.class}) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*", "javax.activation.*", "javax.management.*"}) @@ -95,7 +98,7 @@ public class ConfigDataPointRtTest { private final DataPointSyncMode sync; private RuntimeManager runtimeManagerMock; - private PointValueDAO pointValueDAOMock; + private IPointValueDAO pointValueDAOMock; private DataSourceVO dataSourceVO; private DataPointVO dataPointVO; @@ -163,44 +166,44 @@ private void preconfig() throws Exception { when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); when(loggedUsers.getUser(eq(user.getId()))).thenReturn(user); + DataSource dsMock = mock(DataSource.class); + when(ApplicationBeans.getBean("databaseSource", DataSource.class)).thenReturn(dsMock); + dataSourceVO = createDataSource(); dataPointVO = createDataPoint(defaultCacheSize, tolerance, startValue, dataTypeId, dataSourceVO); - pointValueDAOMock = mock(PointValueDAO.class); + pointValueDAOMock = mock(PointValueDAOMemory.class); - when(pointValueDAOMock.createAnnotation(anyLong(), anyString(), anyString(), anyInt(), anyInt())).thenAnswer(a -> { - Object[] args = a.getArguments(); - return pointValueDAOMemory.createAnnotation((long)args[0], (String)args[1], (String)args[2], (int)args[3], (int)args[4]); - }); + when(pointValueDAOMock.applyBounds(anyDouble())).thenAnswer(inv -> inv.getArgument(0)); - when(pointValueDAOMock.createAnnotation(anyLong(), isNull(), anyString(), anyInt(), anyInt())).thenAnswer(a -> { - Object[] args = a.getArguments(); - return pointValueDAOMemory.createAnnotation((long)args[0], (String)args[1], (String)args[2], (int)args[3], (int)args[4]); - }); + when(pointValueDAOMock.createAnnotation(anyLong(), anyString(), anyString(), anyInt(), anyInt())) + .thenAnswer(a -> pointValueDAOMemory.createAnnotation((long)a.getArgument(0), a.getArgument(1), a.getArgument(2), a.getArgument(3), a.getArgument(4))); + when(pointValueDAOMock.createAnnotation(anyLong(), isNull(), anyString(), anyInt(), anyInt())) + .thenAnswer(a -> pointValueDAOMemory.createAnnotation((long)a.getArgument(0), a.getArgument(1), a.getArgument(2), a.getArgument(3), a.getArgument(4))); + when(pointValueDAOMock.createAnnotation(anyLong(), anyString(), isNull(), anyInt(), anyInt())) + .thenAnswer(a -> pointValueDAOMemory.createAnnotation((long)a.getArgument(0), a.getArgument(1), a.getArgument(2), a.getArgument(3), a.getArgument(4))); + when(pointValueDAOMock.createAnnotation(anyLong(), isNull(), isNull(), anyInt(), anyInt())) + .thenAnswer(a -> pointValueDAOMemory.createAnnotation((long)a.getArgument(0), a.getArgument(1), a.getArgument(2), a.getArgument(3), a.getArgument(4))); - when(pointValueDAOMock.createAnnotation(anyLong(), anyString(), isNull(), anyInt(), anyInt())).thenAnswer(a -> { - Object[] args = a.getArguments(); - return pointValueDAOMemory.createAnnotation((long)args[0], (String)args[1], (String)args[2], (int)args[3], (int)args[4]); - }); + when(pointValueDAOMock.create(anyInt(), anyInt(), anyDouble(), anyLong())) + .thenAnswer(a -> pointValueDAOMemory.create((int)a.getArgument(0), (int)a.getArgument(1), (double)a.getArgument(2), (long)a.getArgument(3))); - when(pointValueDAOMock.createAnnotation(anyLong(), isNull(), isNull(), anyInt(), anyInt())).thenAnswer(a -> { - Object[] args = a.getArguments(); - return pointValueDAOMemory.createAnnotation((long)args[0], (String)args[1], (String)args[2], (int)args[3], (int)args[4]); - }); + when(pointValueDAOMock.getPointValue(anyLong())) + .thenAnswer(a -> pointValueDAOMemory.getPointValue((long)a.getArgument(0))); - when(pointValueDAOMock.create(anyInt(), anyInt(), anyDouble(), anyLong())).thenAnswer(a -> { - Object[] args = a.getArguments(); - return pointValueDAOMemory.create((int)args[0], (int)args[1], (double)args[2], (long)args[3]); - }); + mockStatic(ApplicationBeans.class); + when(ApplicationBeans.getPointValueDAOBean()).thenReturn(pointValueDAOMock); - when(pointValueDAOMock.getPointValue(anyLong())).thenAnswer(a -> { - Object[] args = a.getArguments(); - return pointValueDAOMemory.getPointValue((long)args[0]); - }); - when(pointValueDAOMock.applyBounds(anyDouble())).thenCallRealMethod(); + DatabaseAccess dbAccessMock = mock(DatabaseAccess.class); + when(ApplicationBeans.getBean("databaseAccess", DatabaseAccess.class)).thenReturn(dbAccessMock); + when(dbAccessMock.getTypeKey()).thenReturn("mysql"); - mockStatic(PointValueDAO.class); - when(PointValueDAO.getInstance()).thenReturn(pointValueDAOMock); + JdbcTemplate jdbcTemplateMock = mock(JdbcTemplate.class); + DAO daoMock = mock(DAO.class); + when(daoMock.getJdbcTemp()).thenReturn(jdbcTemplateMock); + mockStatic(DAO.class); + when(DAO.getInstance()).thenReturn(daoMock); + when(jdbcTemplateMock.queryForObject(anyString(), any(), eq(Long.class))).thenReturn(1L); RealTimeTimer realTimeTimerMock = mock(RealTimeTimer.class); whenNew(RealTimeTimer.class).withNoArguments().thenReturn(realTimeTimerMock); @@ -212,17 +215,17 @@ private void preconfig() throws Exception { runtimeManagerMock = mock(RuntimeManager.class); doAnswer(a -> { - runtimeManager.saveDataPoint((DataPointVO)a.getArguments()[0]); + runtimeManager.saveDataPoint(a.getArgument(0)); return null; }).when(runtimeManagerMock).saveDataPoint(any(DataPointVO.class)); doAnswer(a -> { - runtimeManager.saveDataSource((DataSourceVO)a.getArguments()[0]); + runtimeManager.saveDataSource(a.getArgument(0)); return null; }).when(runtimeManagerMock).saveDataSource(any(DataSourceVO.class)); when(runtimeManagerMock.getDataPoint(anyInt())) - .thenAnswer(a -> runtimeManager.getDataPoint((int)a.getArguments()[0])); + .thenAnswer(a -> runtimeManager.getDataPoint(a.getArgument(0))); when(contextWrapper.getRuntimeManager()).thenReturn(runtimeManagerMock); BackgroundProcessing backgroundProcessingMock = mock(BackgroundProcessing.class); @@ -232,27 +235,19 @@ private void preconfig() throws Exception { when(contextWrapper.getEventManager()).thenReturn(eventManagerMock); DataPointService dataPointServiceMock = mock(DataPointService.class); - whenNew(DataPointService.class) - .withNoArguments() - .thenReturn(dataPointServiceMock); + whenNew(DataPointService.class).withNoArguments().thenReturn(dataPointServiceMock); when(dataPointServiceMock.getDataPoint(anyInt())).thenReturn(dataPointVO); DataSourceService dataSourceServiceMock = mock(DataSourceService.class); - whenNew(DataSourceService.class) - .withNoArguments() - .thenReturn(dataSourceServiceMock); + whenNew(DataSourceService.class).withNoArguments().thenReturn(dataSourceServiceMock); when(dataSourceServiceMock.getDataSource(anyInt())).thenReturn(dataSourceVO); TimeoutTask timeoutTaskMock = mock(TimeoutTask.class); - whenNew(TimeoutTask.class) - .withAnyArguments() - .thenReturn(timeoutTaskMock); + whenNew(TimeoutTask.class).withAnyArguments().thenReturn(timeoutTaskMock); SystemSettingsService systemSettingsServiceMock = mock(SystemSettingsService.class); when(systemSettingsServiceMock.getDataPointRtValueSynchronized()).thenReturn(sync); - whenNew(SystemSettingsService.class) - .withNoArguments() - .thenReturn(systemSettingsServiceMock); + whenNew(SystemSettingsService.class).withNoArguments().thenReturn(systemSettingsServiceMock); DataPointServiceWebSocket dataPointServiceWebSocket = mock(DataPointServiceWebSocket.class); when(ApplicationBeans.getDataPointServiceWebSocketBean()).thenReturn(dataPointServiceWebSocket); @@ -261,6 +256,7 @@ private void preconfig() throws Exception { when(ApplicationBeans.getUserDaoBean()).thenReturn(userDAO); } + protected DataPointVO createDataPoint(int defaultCacheSize, double tolerance, String startValue, int dataTypeId, DataSourceVO dataSourceVO) { @@ -445,7 +441,7 @@ protected int getNumberOfLaunches() { return numberOfLaunches; } - public PointValueDAO getPointValueDAOMock() { + public IPointValueDAO getPointValueDAOMock() { return pointValueDAOMock; } diff --git a/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java b/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java index e7c498749c..55386a8501 100644 --- a/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java +++ b/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java @@ -4,6 +4,13 @@ import com.serotonin.mango.rt.maint.BackgroundProcessing; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.scada_lts.dao.pointvalues.IPointValueDAO; +import org.scada_lts.mango.service.PointValueService; +import org.scada_lts.web.beans.ApplicationBeans; import utils.TestUtils; import com.serotonin.mango.rt.dataSource.DataSourceRT; import com.serotonin.mango.vo.DataPointVO; @@ -13,14 +20,17 @@ import utils.mock.PowerMockUtils; import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static utils.mock.MockitoUtils.mockBackgroundProcessing; import static utils.mock.MockitoUtils.mockContextWrapper; +@RunWith(PowerMockRunner.class) +@PrepareForTest({ApplicationBeans.class, PointValueService.class}) public class AbstractStartStopDataPointsUtilsTest { private DataPointVO dataPoint1; @@ -59,6 +69,21 @@ public void config() throws Exception { PowerMockUtils.configDaoMock(); + IPointValueDAO dao = mock(IPointValueDAO.class); + PowerMockito.when(ApplicationBeans.getPointValueDAOBean()) + .thenReturn(dao); + when(dao.getLatestPointValue(anyInt())).thenReturn(null); + when(dao.findByIdAndTs(anyInt(), anyLong())).thenReturn(Collections.emptyList()); + when(dao.applyBounds(anyDouble())).thenAnswer(inv -> inv.getArgument(0)); + when(dao.create(anyInt(), anyInt(), anyDouble(), anyLong())).thenReturn(new Object[]{1L}); + + PointValueService pvs = mock(PointValueService.class); + when(pvs.getLatestPointValue(anyInt())).thenReturn(null); + when(pvs.getLatestPointValues(anyInt(), anyInt())).thenReturn(Collections.emptyList()); + + PowerMockito.whenNew(PointValueService.class).withNoArguments().thenReturn(pvs); + + dataPoint1 = TestUtils.newPointSettable(1, -1); dataPoint2 = TestUtils.newPointSettable(2, -1); dataPoint3 = TestUtils.newPointSettable(3, -1); diff --git a/test/com/serotonin/util/SerializationHelperTest.java b/test/com/serotonin/util/SerializationHelperTest.java index 44840d4de9..a8d73d3d83 100644 --- a/test/com/serotonin/util/SerializationHelperTest.java +++ b/test/com/serotonin/util/SerializationHelperTest.java @@ -32,7 +32,7 @@ public static String[][] data() { public SerializationHelperTest(String file, String encoding) throws IOException { this.toWrite = Files.readString(Path.of(FileTestUtils.getResourcesPath("encoding", file)), Charset.forName(encoding)); - this.utf8Expected = new String(toWrite.getBytes(), StandardCharsets.UTF_8); + this.utf8Expected = toWrite; } @Test @@ -50,8 +50,8 @@ public void when_writeSafeUTF_and_readSafeUTF_then_equals_bytes() throws IOExcep try(ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { String result = SerializationHelper.readSafeUTF(inputStream); - byte[] bytesExpected = utf8Expected.getBytes(); - byte[] bytesResult = result.getBytes(); + byte[] bytesExpected = utf8Expected.getBytes(StandardCharsets.UTF_8); + byte[] bytesResult = result.getBytes(StandardCharsets.UTF_8); Assert.assertEquals(bytesExpected.length, bytesResult.length); @@ -86,4 +86,4 @@ public void when_writeSafeUTF_and_readSafeUTF_then_equals_chars() throws IOExcep } } } -} \ No newline at end of file +} diff --git a/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java b/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java index a300a00fdc..9bff0cdf96 100644 --- a/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java +++ b/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -14,16 +15,19 @@ import org.scada_lts.dao.model.pointhierarchy.PointHierarchyDataSource; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; import org.scada_lts.dao.pointhierarchy.PointHierarchyDAO; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.Arrays; import java.util.Collections; import java.util.List; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) -@PrepareForTest({PointHierarchyCache.class}) +@PrepareForTest({PointHierarchyCache.class, ApplicationBeans.class}) // resources/org/powermock/extensions/configuration.properties is not working @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*", "javax.activation.*", "javax.management.*"}) @@ -204,14 +208,21 @@ public void config() throws Exception { when(hierarchyDAOMock.getHierarchy()).thenReturn(pointHierarchy); when(pointHierarchyDAOMock.getPointsHierarchy()).thenReturn(folderHierarchy); - whenNew(HierarchyDAO.class) + PowerMockito.whenNew(HierarchyDAO.class) .withAnyArguments() .thenReturn(hierarchyDAOMock); - whenNew(PointHierarchyDAO.class) + PowerMockito.whenNew(PointHierarchyDAO.class) .withAnyArguments() .thenReturn(pointHierarchyDAOMock); + PowerMockito.mockStatic(ApplicationBeans.class); + + when(ApplicationBeans.getBean(eq("pointHierarchyDAO"), any(Class.class))) + .thenReturn(pointHierarchyDAOMock); + when(ApplicationBeans.getHierarchyDAOBean()) + .thenReturn(hierarchyDAOMock); + this.pointHierarchyCache = new PointHierarchyCache(true); } @@ -226,4 +237,4 @@ public void when_delete() throws Exception { //then: Assert.assertEquals(pointHierarchyExpected, result); } -} \ No newline at end of file +} diff --git a/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java b/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java index 36800fb8f7..196694392a 100644 --- a/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java +++ b/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -13,17 +14,21 @@ import org.scada_lts.dao.model.pointhierarchy.PointHierarchyComparator; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyDataSource; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO; import org.scada_lts.dao.pointhierarchy.PointHierarchyDAO; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.Arrays; import java.util.Collections; import java.util.List; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) -@PrepareForTest({PointHierarchyCache.class}) +@PrepareForTest({PointHierarchyCache.class, ApplicationBeans.class}) // resources/org/powermock/extensions/configuration.properties is not working @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*", "javax.activation.*", "javax.management.*"}) @@ -123,6 +128,15 @@ public void config() throws Exception { .withAnyArguments() .thenReturn(pointHierarchyDAOMock); + PowerMockito.mockStatic(ApplicationBeans.class); + + when(ApplicationBeans.getBean( + eq("pointHierarchyDAO"), + (Class) any(Class.class))) + .thenReturn(pointHierarchyDAOMock); + when(ApplicationBeans.getHierarchyDAOBean()) + .thenReturn(hierarchyDAOMock); + this.pointHierarchyCache = new PointHierarchyCache(true); } @@ -135,4 +149,4 @@ public void when_getOnBaseParentId() throws Exception { //then: Assert.assertEquals(pointHierarchyExpected, result); } -} \ No newline at end of file +} diff --git a/test/org/scada_lts/dao/EventDetectorTemplateDaoTest.java b/test/org/scada_lts/dao/EventDetectorTemplateDaoTest.java index 998ba5fa91..cf89051709 100644 --- a/test/org/scada_lts/dao/EventDetectorTemplateDaoTest.java +++ b/test/org/scada_lts/dao/EventDetectorTemplateDaoTest.java @@ -49,7 +49,7 @@ public void test() throws Exception { // end papulate data // CRUD start - EventDetectorTemplateDAO eventDetectorTemplateDAO = new EventDetectorTemplateDAO(); + IEventDetectorTemplateDAO eventDetectorTemplateDAO = new EventDetectorTemplateDAO(); //insert int id = eventDetectorTemplateDAO.insertEventDetectorTemplate(eventDetectorTempVO); diff --git a/test/org/scada_lts/dao/EventServiceTest.java b/test/org/scada_lts/dao/EventServiceTest.java index 1313009926..3c06f9afb2 100644 --- a/test/org/scada_lts/dao/EventServiceTest.java +++ b/test/org/scada_lts/dao/EventServiceTest.java @@ -28,6 +28,7 @@ import org.junit.Before; import org.junit.Test; import org.scada_lts.config.ScadaConfig; +import org.scada_lts.dao.event.IUserEventDAO; import org.scada_lts.dao.event.UserEventDAO; import org.scada_lts.dao.model.event.UserEvent; import org.scada_lts.mango.adapter.MangoEvent; @@ -222,7 +223,7 @@ public void getEventsForDataPoint() { dataPoint.setDataSourceXid(DATA_SOURCE_XID); dataPoint.setDataSourceTypeId(DATA_SOURCE_TYPE_ID); - DataPointDAO dataPointDAO = new DataPointDAO(); + IDataPointDAO dataPointDAO = new DataPointDAO(); int id = dataPointDAO.insert(dataPoint); dataPoint.setId(id); @@ -241,7 +242,7 @@ public void getEventsForDataPoint() { pointEventDetector.setAlphanumericState(ALPHANUMERIC_STATE); pointEventDetector.setWeight(WEIGHT); - PointEventDetectorDAO pointEventDetectorDAO = new PointEventDetectorDAO(); + IPointEventDetectorDAO pointEventDetectorDAO = new PointEventDetectorDAO(); int idPointEventDetector = pointEventDetectorDAO.insert(dataPoint.getId(), pointEventDetector); EventType type = new DataPointEventType(id,idPointEventDetector); @@ -257,7 +258,7 @@ public void getEventsForDataPoint() { userEvent.setSilenced(false); userEvent.setUserId(ADMIN_USER_ID); - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); userEventDAO.create(userEvent); List eventsForDataPoint = eventService.getEventsForDataPoint(id, ADMIN_USER_ID); boolean checkEventsForDataPoint = eventsForDataPoint.size() == 1; @@ -279,7 +280,7 @@ public void getPendingEventsForDataPoint() { dataPoint.setDataSourceXid(DATA_SOURCE_XID); dataPoint.setDataSourceTypeId(DATA_SOURCE_TYPE_ID); - DataPointDAO dataPointDAO = new DataPointDAO(); + IDataPointDAO dataPointDAO = new DataPointDAO(); int id = dataPointDAO.insert(dataPoint); dataPoint.setId(id); @@ -298,7 +299,7 @@ public void getPendingEventsForDataPoint() { pointEventDetector.setAlphanumericState(ALPHANUMERIC_STATE); pointEventDetector.setWeight(WEIGHT); - PointEventDetectorDAO pointEventDetectorDAO = new PointEventDetectorDAO(); + IPointEventDetectorDAO pointEventDetectorDAO = new PointEventDetectorDAO(); int idPointEventDetector = pointEventDetectorDAO.insert(pointEventDetector); EventType type = new DataPointEventType(id,idPointEventDetector); @@ -316,7 +317,7 @@ public void getPendingEventsForDataPoint() { userEvent.setSilenced(false); userEvent.setUserId(ADMIN_USER_ID); - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); userEventDAO.create(userEvent); List eventsPendingForDataPoint = eventService.getPendingEventsForDataPoint(id, ADMIN_USER_ID); boolean checkEventsForPendingDataPoint = eventsPendingForDataPoint.size() == 1; @@ -392,7 +393,7 @@ public void searchOldId() { userEvent.setSilenced(false); userEvent.setUserId(ADMIN_USER_ID); - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); userEventDAO.create(userEvent); List events = eventService.searchOld(e.getId(),EventType.EventSources.DATA_SOURCE,"*",alarmLevel,null,0,ADMIN_USER_ID,null); @@ -421,7 +422,7 @@ public void search() { userEvent.setSilenced(false); userEvent.setUserId(ADMIN_USER_ID); - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); userEventDAO.create(userEvent); List events = eventService.search(0, -1, null, -1, null, 1, null, 0, 5000, null); @@ -450,7 +451,7 @@ public void searchRowCountStartRow() { userEvent.setSilenced(false); userEvent.setUserId(ADMIN_USER_ID); - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); userEventDAO.create(userEvent); eventService.search(0, -1, null, -1, null, 1, null, 0, 5000, null); @@ -546,7 +547,7 @@ public void toggleSilence() { userEvent.setSilenced(false); userEvent.setUserId(ADMIN_USER_ID); - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); userEventDAO.create(userEvent); User user = new User(); diff --git a/test/org/scada_lts/dao/FlexProjectDaoTest.java b/test/org/scada_lts/dao/FlexProjectDaoTest.java index 2262dda6a6..1e440a8881 100644 --- a/test/org/scada_lts/dao/FlexProjectDaoTest.java +++ b/test/org/scada_lts/dao/FlexProjectDaoTest.java @@ -17,9 +17,9 @@ */ package org.scada_lts.dao; -import br.org.scadabr.api.vo.FlexProject; -import org.junit.Test; -import org.springframework.dao.EmptyResultDataAccessException; +import br.org.scadabr.api.vo.FlexProject; +import org.junit.Test; +import org.springframework.dao.EmptyResultDataAccessException; import java.util.List; @@ -54,7 +54,7 @@ public void test() { flexProject.setDescription(DESCRIPTION); flexProject.setXmlConfig(XML_CONFIG); - FlexProjectDAO flexProjectDAO = new FlexProjectDAO(); + IFlexProjectDAO flexProjectDAO = new FlexProjectDAO(); //Insert objects int firstId = flexProjectDAO.insert(NAME, DESCRIPTION, XML_CONFIG); diff --git a/test/org/scada_lts/dao/ReportInstanceDaoTest.java b/test/org/scada_lts/dao/ReportInstanceDaoTest.java index d559dfcf31..b51a8efbb7 100644 --- a/test/org/scada_lts/dao/ReportInstanceDaoTest.java +++ b/test/org/scada_lts/dao/ReportInstanceDaoTest.java @@ -25,6 +25,10 @@ import com.serotonin.web.i18n.I18NUtils; import org.junit.Before; import org.junit.Test; +import org.scada_lts.dao.report.IReportInstanceDAO; +import org.scada_lts.dao.report.IReportInstanceDataDAO; +import org.scada_lts.dao.report.IReportInstancePointDAO; +import org.scada_lts.dao.report.IReportInstanceUserCommentDAO; import org.scada_lts.dao.report.ReportInstanceDAO; import org.scada_lts.dao.report.ReportInstanceDataDAO; import org.scada_lts.dao.report.ReportInstancePointDAO; @@ -79,7 +83,7 @@ public class ReportInstanceDaoTest extends TestDAO { private AnalogRenderer analogRenderer; private DataPointVO dataPointVO; private MangoValue startValue; - private ReportInstancePointDAO.PointInfo pointInfo; + private IReportInstancePointDAO.PointInfo pointInfo; @Before public void beforeTest() { @@ -98,7 +102,7 @@ public void beforeTest() { startValue = mock(MangoValue.class); when(startValue.toString()).thenReturn("mValString").thenReturn("secondMVal"); - pointInfo = mock(ReportInstancePointDAO.PointInfo.class); + pointInfo = mock(IReportInstancePointDAO.PointInfo.class); when(pointInfo.getColour()).thenReturn("blue").thenReturn("red"); when(pointInfo.isConsolidatedChart()).thenReturn(true); } @@ -129,7 +133,7 @@ public void testReportInstanceDAO() { secondReportInstance.setRecordCount(SECOND_RECORD_COUNT); secondReportInstance.setPreventPurge(SECOND_PREVENT_PURGE); - ReportInstanceDAO reportInstanceDAO = new ReportInstanceDAO(); + IReportInstanceDAO reportInstanceDAO = new ReportInstanceDAO(); //Insert int firstId = reportInstanceDAO.insert(reportInstance); @@ -204,10 +208,10 @@ public void testReportInstanceDataDAO() { + "runEndTime, recordCount, preventPurge) " + " values (" + USER_ID + ", '" + NAME + "', " + INCLUDE_EVENTS + ", " + INCLUDE_USER_COMMENT + ", " + REPORT_START_TIME + ", " + REPORT_END_TIME + "," + RUN_START_TIME + "," + RUN_END_TIME + "," + RECORD_COUNT + "," + PREVENT_PURGE + ")"); - ReportInstancePointDAO reportInstancePointDAO = new ReportInstancePointDAO(); + IReportInstancePointDAO reportInstancePointDAO = new ReportInstancePointDAO(); reportInstancePointDAO.insert(reportInstance, DATA_TYPE, startValue, pointInfo); - ReportInstanceDataDAO reportInstanceDataDAO = new ReportInstanceDataDAO(); + IReportInstanceDataDAO reportInstanceDataDAO = new ReportInstanceDataDAO(); ReportInstance reportInst = new ReportInstance(); reportInst.setReportStartTime(1); @@ -263,7 +267,7 @@ public void testReportInstancePointDAO() { + "runEndTime, recordCount, preventPurge) " + " values (" + USER_ID + ", '" + NAME + "', " + INCLUDE_EVENTS + ", " + INCLUDE_USER_COMMENT + ", " + REPORT_START_TIME + ", " + REPORT_END_TIME + "," + RUN_START_TIME + "," + RUN_END_TIME + "," + RECORD_COUNT + "," + PREVENT_PURGE + ")"); - ReportInstancePointDAO reportInstancePointDAO = new ReportInstancePointDAO(); + IReportInstancePointDAO reportInstancePointDAO = new ReportInstancePointDAO(); //Insert objects int firstId = reportInstancePointDAO.insert(reportInstance, DATA_TYPE, startValue, pointInfo); @@ -297,7 +301,7 @@ public void testReportInstanceUserCommentDAO() { + ", " + REPORT_START_TIME + ", " + REPORT_END_TIME + "," + RUN_START_TIME + "," + RUN_END_TIME + "," + RECORD_COUNT + "," + PREVENT_PURGE + ")"); DAO.getInstance().getJdbcTemp().update("INSERT INTO reportinstanceusercomments (reportInstanceId, username, commentType, typeKey, ts, commentText) values (1, 'fName', 1, 1, 20, 'fCom')"); - ReportInstanceUserCommentDAO reportInstanceUserCommentDAO = new ReportInstanceUserCommentDAO(); + IReportInstanceUserCommentDAO reportInstanceUserCommentDAO = new ReportInstanceUserCommentDAO(); //Insert objects List reportUserCommentList = reportInstanceUserCommentDAO.getReportUserComments(INSTANCE_ID); diff --git a/test/org/scada_lts/dao/SystemSettingsDaoTest.java b/test/org/scada_lts/dao/SystemSettingsDaoTest.java index a13d2ece48..5406f45cb4 100644 --- a/test/org/scada_lts/dao/SystemSettingsDaoTest.java +++ b/test/org/scada_lts/dao/SystemSettingsDaoTest.java @@ -17,9 +17,10 @@ */ package org.scada_lts.dao; -import org.junit.Test; -import org.scada_lts.dao.report.ReportInstanceDAO; -import org.springframework.dao.EmptyResultDataAccessException; +import org.junit.Test; +import org.scada_lts.dao.report.IReportInstanceDAO; +import org.scada_lts.dao.report.ReportInstanceDAO; +import org.springframework.dao.EmptyResultDataAccessException; import static org.junit.Assert.assertTrue; @@ -30,7 +31,7 @@ */ public class SystemSettingsDaoTest extends TestDAO { - private static final SystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO(); + private static final ISystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO(); private static final String SETTING_NAME = "settingName"; private static final String SETTING_VALUE = "/ScadaLTS"; @@ -116,7 +117,7 @@ public void databaseTest() { assertTrue(sizeWithRecords >= emptySize); - ReportInstanceDAO reportInstanceDAO = new ReportInstanceDAO(); + IReportInstanceDAO reportInstanceDAO = new ReportInstanceDAO(); reportInstanceDAO.getReportInstance(1); systemSettingsDAO.resetDataBase(); diff --git a/test/org/scada_lts/dao/UserEventDaoTest.java b/test/org/scada_lts/dao/UserEventDaoTest.java index 377056880d..e7b2cff2d5 100644 --- a/test/org/scada_lts/dao/UserEventDaoTest.java +++ b/test/org/scada_lts/dao/UserEventDaoTest.java @@ -22,6 +22,7 @@ import java.util.List; import org.junit.Test; +import org.scada_lts.dao.event.IUserEventDAO; import org.scada_lts.dao.event.UserEventDAO; import org.scada_lts.dao.model.event.UserEvent; @@ -75,7 +76,7 @@ public void test() { // end populate data - UserEventDAO userEventDAO = new UserEventDAO(); + IUserEventDAO userEventDAO = new UserEventDAO(); //CR diff --git a/test/utils/PointValueDAOMemory.java b/test/utils/PointValueDAOMemory.java index fb43931920..b70fe5ba81 100644 --- a/test/utils/PointValueDAOMemory.java +++ b/test/utils/PointValueDAOMemory.java @@ -232,4 +232,24 @@ public PointValueTime getPointValueBefore(int dataPointId, long time) { public PointValueTime getPointValueAt(int dataPointId, long time) { throw new UnsupportedOperationException(); } + + @Override + public List getPointValues(int dataPointId, long since) { + throw new UnsupportedOperationException(); + } + + @Override + public List getPointValuesBetween(int dataPointId, long from, long to) { + throw new UnsupportedOperationException(); + } + + @Override + public List getLatestPointValues(int dataPointId, int limit) { + throw new UnsupportedOperationException(); + } + + @Override + public List getLatestPointValues(int dataPointId, int limit, long before) { + throw new UnsupportedOperationException(); + } } diff --git a/test/utils/ScriptTestUtils.java b/test/utils/ScriptTestUtils.java index 6903ea0664..7a06cffa90 100644 --- a/test/utils/ScriptTestUtils.java +++ b/test/utils/ScriptTestUtils.java @@ -15,16 +15,16 @@ import com.serotonin.mango.vo.dataSource.virtual.VirtualPointLocatorVO; import com.serotonin.mango.vo.permission.Permissions; import org.mockito.Mockito; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.web.beans.ApplicationBeans; import org.scada_lts.web.ws.services.DataPointServiceWebSocket; import utils.mock.PowerMockUtils; import java.util.*; -import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.*; public class ScriptTestUtils { @@ -72,6 +72,17 @@ public static void configMock(RuntimeManager runtimeManager, ScriptContextObject mockStatic(ApplicationBeans.class); DataPointServiceWebSocket dataPointServiceWebSocket = mock(DataPointServiceWebSocket.class); when(ApplicationBeans.getDataPointServiceWebSocketBean()).thenReturn(dataPointServiceWebSocket); + IPointValueDAO pointValueDaoMock = mock(IPointValueDAO.class); + when(ApplicationBeans.getPointValueDAOBean()) + .thenReturn(pointValueDaoMock); + + when(pointValueDaoMock.applyBounds(anyDouble())).thenAnswer(inv -> inv.getArgument(0)); + when(pointValueDaoMock.create(anyInt(), anyInt(), anyDouble(), anyLong())) + .thenReturn(new Object[]{1L}); + + DataPointServiceWebSocket wsMock = mock(DataPointServiceWebSocket.class); + when(ApplicationBeans.getDataPointServiceWebSocketBean()).thenReturn(wsMock); + doNothing().when(wsMock).notifyStateSubscribers(anyBoolean(), anyInt()); } public static void configScriptMock(RuntimeManager runtimeManager, ScriptContextObject scriptContextObject) throws Exception { diff --git a/test/utils/mock/PowerMockUtils.java b/test/utils/mock/PowerMockUtils.java index 3fb1161c03..b204262806 100644 --- a/test/utils/mock/PowerMockUtils.java +++ b/test/utils/mock/PowerMockUtils.java @@ -10,6 +10,8 @@ import com.serotonin.mango.web.ContextWrapper; import com.serotonin.util.PropertiesUtils; import org.scada_lts.dao.DAO; +import org.scada_lts.dao.pointvalues.IPointValueDAO; +import org.scada_lts.mango.service.PointValueService; import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; @@ -19,16 +21,20 @@ import javax.servlet.http.HttpServletRequest; import javax.sql.DataSource; +import java.util.Collections; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; import static com.serotonin.mango.util.ThreadPoolExecutorUtils.createForkJoinPool; import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.*; public class PowerMockUtils { + private static IPointValueDAO pointValueDAOMock; + public static void configMock(RuntimeManager runtimeManager, User user) throws Exception { configMockContextWrapper(runtimeManager); @@ -103,4 +109,21 @@ public static BackgroundProcessing mockBackgroundProcessing() { .terminate(); return backgroundProcessing; } + + public static void mockPointValueDAOBean() throws Exception { + + IPointValueDAO dao = mock(IPointValueDAO.class); + when(dao.getLatestPointValue(anyInt())).thenReturn(null); + when(dao.applyBounds(anyDouble())).thenAnswer(inv -> inv.getArgument(0)); + + mockStatic(ApplicationBeans.class); + when(ApplicationBeans.getPointValueDAOBean()) + .thenReturn(dao); + + PointValueService pvs = mock(PointValueService.class); + when(pvs.getLatestPointValue(anyInt())).thenReturn(null); + when(pvs.getLatestPointValues(anyInt(), anyInt())).thenReturn(Collections.emptyList()); + + whenNew(PointValueService.class).withNoArguments().thenReturn(pvs); + } } From b2ffeb2c2d6ddeaeedc7c3038336b38886cacde6 Mon Sep 17 00:00:00 2001 From: patrykb0802 Date: Thu, 12 Mar 2026 12:21:47 +0100 Subject: [PATCH 2/7] #3249 Refactor DAO layer for modular architecture --- .../cache/PointEventDetectorDaoWithCache.java | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java index 246933edfc..c9799cfc87 100644 --- a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java @@ -47,25 +47,6 @@ public List getPointEventDetectors(DataPointVO dataPoint) .collect(Collectors.toList()); } - @Override - @Deprecated - public int getId(String pointEventDetectorXid, int dataPointId) { - PointEventDetectorVO pointEventDetectorVO = pointEventDetectorCache.selectPointEventDetector(pointEventDetectorXid, dataPointId); - return pointEventDetectorVO == null ? -1 : pointEventDetectorVO.getId(); - } - - @Override - @Deprecated - public String getXid(int pointEventDetectorId) { - PointEventDetectorVO pointEventDetectorVO = pointEventDetectorCache.selectPointEventDetector(pointEventDetectorId); - return pointEventDetectorVO == null ? null : pointEventDetectorVO.getXid(); - } - - @Override - public List getPointEventDetectors(long limit, int offset) { - return new PointEventDetectorDAO().getPointEventDetectors(limit, offset); - } - @Override public boolean isEventDetectorXidUnique(int dataPointId, String xid, int excludeId) { PointEventDetectorVO pointEventDetectorVO = pointEventDetectorCache.selectPointEventDetector(xid, dataPointId); From 6b3e8232e120f57f327267ee6cffa6efff5d42e6 Mon Sep 17 00:00:00 2001 From: patrykb0802 Date: Wed, 8 Apr 2026 17:36:10 +0200 Subject: [PATCH 3/7] #3249 Refactor DAO layer for modular architecture --- WebContent/WEB-INF/applicationContext.xml | 77 ++- WebContent/resources/package-lock.json | 472 ++++++++++++------ build.gradle | 16 +- .../db/configuration/ConfigurationDB.java | 49 ++ .../util/SystemSettingsJSONWrapper.java | 2 +- .../serotonin/mango/MangoContextListener.java | 2 +- .../serotonin/mango/db/DatabaseAccess.java | 117 +++-- src/com/serotonin/mango/db/DerbyAccess.java | 4 +- src/com/serotonin/mango/db/MSSQLAccess.java | 4 +- src/com/serotonin/mango/db/MySQLAccess.java | 4 +- .../serotonin/mango/db/Oracle11GAccess.java | 4 +- .../serotonin/mango/db/PostgreSQLAccess.java | 4 +- .../serotonin/mango/db/dao/DataSourceDao.java | 6 +- .../serotonin/mango/db/upgrade/DBUpgrade.java | 2 +- .../serotonin/mango/rt/RuntimeManager.java | 14 +- .../rt/dataSource/sql/SqlDataSourceRT.java | 4 +- .../mango/rt/event/type/AuditEventType.java | 2 +- .../mango/rt/event/type/AuditEventUtils.java | 4 +- .../mango/rt/event/type/SystemEventType.java | 2 +- .../mango/web/dwr/DataSourceEditDwr.java | 4 +- .../mango/web/dwr/DataSourceListDwr.java | 4 +- .../serotonin/mango/web/dwr/EmportDwr.java | 6 +- .../mango/web/dwr/SystemSettingsDwr.java | 22 +- .../web/mvc/controller/ScadaLocaleUtils.java | 2 +- .../scada_lts/cache/ViewHierarchyCache.java | 7 +- .../scada_lts/dao/IPointEventDetectorDAO.java | 1 + src/org/scada_lts/dao/ISystemSettingsDAO.java | 2 +- .../scada_lts/dao/PointEventDetectorDAO.java | 1 + src/org/scada_lts/dao/SystemSettingsDAO.java | 3 +- .../cache/PointEventDetectorDaoWithCache.java | 35 +- src/org/scada_lts/db/BinaryDataHandler.java | 14 - .../scada_lts/db/MysqlBinaryDataHandler.java | 27 - .../factory/DatabaseAwareBeanFactory.java | 17 +- .../mango/service/PointValueService.java | 4 - .../mango/service/SystemSettingsService.java | 30 +- .../service/GetWatchListsWithAccess.java | 3 +- .../service/InactiveEventsProvider.java | 4 +- .../service/InactiveEventsProviderImpl.java | 8 +- .../service/ViewHierarchyService.java | 6 + .../scada_lts/web/beans/ApplicationBeans.java | 15 +- .../web/mvc/api/DataPointApiService.java | 8 +- .../web/mvc/controller/SqlController.java | 4 +- .../dao/IsEventDetectorXidUniqueTest.java | 2 +- .../scada_lts/dao/SystemSettingsDaoTest.java | 15 +- 44 files changed, 666 insertions(+), 367 deletions(-) delete mode 100644 src/org/scada_lts/db/BinaryDataHandler.java delete mode 100644 src/org/scada_lts/db/MysqlBinaryDataHandler.java diff --git a/WebContent/WEB-INF/applicationContext.xml b/WebContent/WEB-INF/applicationContext.xml index 73669e9b7d..94b1263c54 100644 --- a/WebContent/WEB-INF/applicationContext.xml +++ b/WebContent/WEB-INF/applicationContext.xml @@ -78,21 +78,50 @@ - - - - + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + @@ -102,11 +131,6 @@ - - - - - @@ -184,8 +208,14 @@ - - + + + + + + + + @@ -234,11 +264,6 @@ - - - - - @@ -361,7 +386,10 @@ - + + + + @@ -371,6 +399,7 @@ + diff --git a/WebContent/resources/package-lock.json b/WebContent/resources/package-lock.json index 2c0517e89c..95a09e1fd7 100644 --- a/WebContent/resources/package-lock.json +++ b/WebContent/resources/package-lock.json @@ -1,273 +1,367 @@ { "name": "scada-lts-webapp", "version": "1.0.0", - "lockfileVersion": 1, + "lockfileVersion": 3, "requires": true, - "dependencies": { - "@babel/helper-string-parser": { + "packages": { + "": { + "name": "scada-lts-webapp", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "axios": "0.21.4", + "bootstrap": "3.4.1", + "bootstrap3-dialog": "1.35.4", + "jquery": "3.6.1", + "jquery-ui-dist": "1.12.1", + "jquery.fancytree": "2.18.0", + "json-lint": "0.1.0", + "sockjs-client": "1.6.0", + "stompjs": "2.3.3", + "sweetalert2": "7.33.1", + "vue": "2.7.10", + "vue-axios": "2.1.5", + "vue-jsoneditor": "1.0.13" + } + }, + "node_modules/@babel/helper-string-parser": { "version": "7.25.9", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", - "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==" + "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", + "engines": { + "node": ">=6.9.0" + } }, - "@babel/helper-validator-identifier": { + "node_modules/@babel/helper-validator-identifier": { "version": "7.25.9", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", - "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==" + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", + "engines": { + "node": ">=6.9.0" + } }, - "@babel/parser": { + "node_modules/@babel/parser": { "version": "7.26.5", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.5.tgz", "integrity": "sha512-SRJ4jYmXRqV1/Xc+TIVG84WjHBXKlxO9sHQnA2Pf12QQEAp1LOh6kDzNHXcUnbH1QI0FDoPPVOt+vyUDucxpaw==", - "requires": { + "dependencies": { "@babel/types": "^7.26.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" } }, - "@babel/types": { + "node_modules/@babel/types": { "version": "7.26.5", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.5.tgz", "integrity": "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg==", - "requires": { + "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" + }, + "engines": { + "node": ">=6.9.0" } }, - "@sphinxxxx/color-conversion": { + "node_modules/@sphinxxxx/color-conversion": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/@sphinxxxx/color-conversion/-/color-conversion-2.2.2.tgz", "integrity": "sha512-XExJS3cLqgrmNBIP3bBw6+1oQ1ksGjFh0+oClDKFYpCCqx/hlqwWO5KO/S63fzUo67SxI9dMrF0y5T/Ey7h8Zw==" }, - "@vue/compiler-sfc": { + "node_modules/@vue/compiler-sfc": { "version": "2.7.10", "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-2.7.10.tgz", "integrity": "sha512-55Shns6WPxlYsz4WX7q9ZJBL77sKE1ZAYNYStLs6GbhIOMrNtjMvzcob6gu3cGlfpCR4bT7NXgyJ3tly2+Hx8Q==", - "requires": { + "dependencies": { "@babel/parser": "^7.18.4", "postcss": "^8.4.14", "source-map": "^0.6.1" } }, - "ajv": { + "node_modules/ajv": { "version": "5.5.2", "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", "integrity": "sha512-Ajr4IcMXq/2QmMkEmSvxqfLN5zGmJ92gHXAeOXq1OekoH2rfDNsgdDoL2f7QaRCy7G/E6TpxBVdRuNraMztGHw==", - "requires": { + "dependencies": { "co": "^4.6.0", "fast-deep-equal": "^1.0.0", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.3.0" } }, - "axios": { + "node_modules/axios": { "version": "0.21.4", "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", - "requires": { + "dependencies": { "follow-redirects": "^1.14.0" } }, - "bootstrap": { + "node_modules/bootstrap": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-3.4.1.tgz", - "integrity": "sha512-yN5oZVmRCwe5aKwzRj6736nSmKDX7pLYwsXiCj/EYmo16hODaBiT4En5btW/jhBF/seV+XMx3aYwukYC3A49DA==" + "integrity": "sha512-yN5oZVmRCwe5aKwzRj6736nSmKDX7pLYwsXiCj/EYmo16hODaBiT4En5btW/jhBF/seV+XMx3aYwukYC3A49DA==", + "deprecated": "This version of Bootstrap is no longer supported. Please upgrade to the latest version.", + "engines": { + "node": ">=6" + } }, - "bootstrap3-dialog": { + "node_modules/bootstrap3-dialog": { "version": "1.35.4", "resolved": "https://registry.npmjs.org/bootstrap3-dialog/-/bootstrap3-dialog-1.35.4.tgz", "integrity": "sha512-wHrJmqASIEsZWhHhfq9q0QhhGI8AnSh4tAAjUGK0MfMZjZ6vFl0niDZs5IwFDChCKKjcgFiFnXxLLoJ6nvyI2A==" }, - "brace": { + "node_modules/brace": { "version": "0.11.1", "resolved": "https://registry.npmjs.org/brace/-/brace-0.11.1.tgz", "integrity": "sha512-Fc8Ne62jJlKHiG/ajlonC4Sd66Pq68fFwK4ihJGNZpGqboc324SQk+lRvMzpPRuJOmfrJefdG8/7JdWX4bzJ2Q==" }, - "bufferutil": { + "node_modules/bufferutil": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz", "integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==", + "hasInstallScript": true, "optional": true, - "requires": { + "dependencies": { "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" } }, - "co": { + "node_modules/co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==" + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } }, - "csstype": { + "node_modules/csstype": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==" }, - "d": { + "node_modules/d": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz", "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==", - "requires": { + "optional": true, + "dependencies": { "es5-ext": "^0.10.64", "type": "^2.7.2" + }, + "engines": { + "node": ">=0.12" } }, - "debug": { + "node_modules/debug": { "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "requires": { + "dependencies": { "ms": "^2.1.1" } }, - "drag-tracker": { + "node_modules/drag-tracker": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/drag-tracker/-/drag-tracker-1.0.0.tgz", "integrity": "sha512-BSGDl37YXpW49dLMRfiDExxzD3yPOpLEBGx05Wed3z2sk2+Qd5dFvHCSVFTPsGTeltGBtkRB4qhLhSKv6tvBKw==" }, - "es5-ext": { + "node_modules/es5-ext": { "version": "0.10.64", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz", "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==", - "requires": { + "hasInstallScript": true, + "optional": true, + "dependencies": { "es6-iterator": "^2.0.3", "es6-symbol": "^3.1.3", "esniff": "^2.0.1", "next-tick": "^1.1.0" + }, + "engines": { + "node": ">=0.10" } }, - "es6-iterator": { + "node_modules/es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", - "requires": { + "optional": true, + "dependencies": { "d": "1", "es5-ext": "^0.10.35", "es6-symbol": "^3.1.1" } }, - "es6-symbol": { + "node_modules/es6-symbol": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz", "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==", - "requires": { + "optional": true, + "dependencies": { "d": "^1.0.2", "ext": "^1.7.0" + }, + "engines": { + "node": ">=0.12" } }, - "esniff": { + "node_modules/esniff": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz", "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==", - "requires": { + "optional": true, + "dependencies": { "d": "^1.0.1", "es5-ext": "^0.10.62", "event-emitter": "^0.3.5", "type": "^2.7.2" + }, + "engines": { + "node": ">=0.10" } }, - "event-emitter": { + "node_modules/event-emitter": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==", - "requires": { + "optional": true, + "dependencies": { "d": "1", "es5-ext": "~0.10.14" } }, - "eventsource": { + "node_modules/eventsource": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-1.1.2.tgz", - "integrity": "sha512-xAH3zWhgO2/3KIniEKYPr8plNSzlGINOUqYj0m0u7AB81iRw8b/3E73W6AuU+6klLbaSFmZnaETQ2lXPfAydrA==" + "integrity": "sha512-xAH3zWhgO2/3KIniEKYPr8plNSzlGINOUqYj0m0u7AB81iRw8b/3E73W6AuU+6klLbaSFmZnaETQ2lXPfAydrA==", + "engines": { + "node": ">=0.12.0" + } }, - "ext": { + "node_modules/ext": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", - "requires": { + "optional": true, + "dependencies": { "type": "^2.7.2" } }, - "fast-deep-equal": { + "node_modules/fast-deep-equal": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz", "integrity": "sha512-fueX787WZKCV0Is4/T2cyAdM4+x1S3MXXOAhavE1ys/W42SHAPacLTQhucja22QBYrfGw50M2sRiXPtTGv9Ymw==" }, - "fast-json-stable-stringify": { + "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" }, - "faye-websocket": { + "node_modules/faye-websocket": { "version": "0.11.4", "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", - "requires": { + "dependencies": { "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" } }, - "follow-redirects": { + "node_modules/follow-redirects": { "version": "1.15.9", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", - "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==" + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } }, - "http-parser-js": { + "node_modules/http-parser-js": { "version": "0.5.9", "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.9.tgz", "integrity": "sha512-n1XsPy3rXVxlqxVioEWdC+0+M+SQw0DpJynwtOPo1X+ZlvdzTLtDBIJJlDQTnwZIFJrZSzSGmIOUdP8tu+SgLw==" }, - "inherits": { + "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, - "is-typedarray": { + "node_modules/is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", "optional": true }, - "javascript-natural-sort": { + "node_modules/javascript-natural-sort": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz", "integrity": "sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==" }, - "jmespath": { + "node_modules/jmespath": { "version": "0.15.0", "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", - "integrity": "sha512-+kHj8HXArPfpPEKGLZ+kB5ONRTCiGQXo8RQYL0hH8t6pWXUBBK5KkkQmTNOwKK4LEsd0yTsgtjJVm4UBSZea4w==" + "integrity": "sha512-+kHj8HXArPfpPEKGLZ+kB5ONRTCiGQXo8RQYL0hH8t6pWXUBBK5KkkQmTNOwKK4LEsd0yTsgtjJVm4UBSZea4w==", + "engines": { + "node": ">= 0.6.0" + } }, - "jquery": { + "node_modules/jquery": { "version": "3.6.1", "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.1.tgz", "integrity": "sha512-opJeO4nCucVnsjiXOE+/PcCgYw9Gwpvs/a6B1LL/lQhwWwpbVEVYDZ1FokFr8PRc7ghYlrFPuyHuiiDNTQxmcw==" }, - "jquery-ui-dist": { + "node_modules/jquery-ui-dist": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/jquery-ui-dist/-/jquery-ui-dist-1.12.1.tgz", "integrity": "sha512-UnQQWIvxaP7s13FLx37WufEwDYLSXKpp9JHrqEYTP6GqQNM+RMVEwsJMoc163QlzEaAV5YVfWlgQU5FPjKBtSw==" }, - "jquery.fancytree": { + "node_modules/jquery.fancytree": { "version": "2.18.0", "resolved": "https://registry.npmjs.org/jquery.fancytree/-/jquery.fancytree-2.18.0.tgz", "integrity": "sha512-thZThwhAintFCB7wOBDh+Ibq9H+0hi6bnqsDDZfGW63tyXFijy7LZKNxZAuIoPXJyUfmfHHBpuZEYzyg6LjmkA==" }, - "json-lint": { + "node_modules/json-lint": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/json-lint/-/json-lint-0.1.0.tgz", - "integrity": "sha512-QoBMCAo3sFnAl2nvCcrt5NmjqMRejlghhMvZ0ykhgfNpp7ukp1te7dP6q2o4fkvl03t08t75njni+y6S7jiHLg==" + "integrity": "sha512-QoBMCAo3sFnAl2nvCcrt5NmjqMRejlghhMvZ0ykhgfNpp7ukp1te7dP6q2o4fkvl03t08t75njni+y6S7jiHLg==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "engines": { + "node": ">=0.5" + } }, - "json-schema-traverse": { + "node_modules/json-schema-traverse": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", "integrity": "sha512-4JD/Ivzg7PoW8NzdrBSr3UFwC9mHgvI7Z6z3QGBsSHgKaRTUDmyZAAKJo2UbG1kUVfS9WS8bi36N49U1xw43DA==" }, - "json-source-map": { + "node_modules/json-source-map": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/json-source-map/-/json-source-map-0.4.0.tgz", "integrity": "sha512-fVJ2mGl6pmYNmgseQch8X1ghdDntxeYgQQueypu9ZvttZwlSQuW4QztPBxgomRiRBidj5g7PtTW+7EqsTnEDNw==" }, - "jsoneditor": { + "node_modules/jsoneditor": { "version": "5.34.0", "resolved": "https://registry.npmjs.org/jsoneditor/-/jsoneditor-5.34.0.tgz", "integrity": "sha512-/F7L6oXuRkv2/FKFIL4NMWF0P+oVvSWLJPVEVP/7KGehBj6dtOp5FKdfLcNkIgbqzklXx/NDzHSXYlf64wqmuQ==", - "requires": { + "dependencies": { "ajv": "5.5.2", "brace": "0.11.1", "javascript-natural-sort": "0.7.1", @@ -278,217 +372,305 @@ "vanilla-picker": "2.8.0" } }, - "mobius1-selectr": { + "node_modules/mobius1-selectr": { "version": "2.4.10", "resolved": "https://registry.npmjs.org/mobius1-selectr/-/mobius1-selectr-2.4.10.tgz", "integrity": "sha512-U/pQ8jZwO7z3Mf9OYzJR6AKfleF5jSBIueKKxGMr/tgyLuTWgchgFyeaXpAIz3Cbp+7eIN1hw5D2gxc4cNnOkQ==" }, - "ms": { + "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, - "nanoid": { + "node_modules/nanoid": { "version": "3.3.8", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", - "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==" + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } }, - "next-tick": { + "node_modules/next-tick": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", - "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==" + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==", + "optional": true }, - "node-gyp-build": { + "node_modules/node-gyp-build": { "version": "4.8.4", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", - "optional": true + "optional": true, + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } }, - "picocolors": { + "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, - "picomodal": { + "node_modules/picomodal": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/picomodal/-/picomodal-3.0.0.tgz", "integrity": "sha512-FoR3TDfuLlqUvcEeK5ifpKSVVns6B4BQvc8SDF6THVMuadya6LLtji0QgUDSStw0ZR2J7I6UGi5V2V23rnPWTw==" }, - "postcss": { + "node_modules/postcss": { "version": "8.4.49", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.49.tgz", "integrity": "sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==", - "requires": { + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { "nanoid": "^3.3.7", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" } }, - "querystringify": { + "node_modules/querystringify": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==" }, - "requires-port": { + "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==" }, - "safe-buffer": { + "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] }, - "sockjs-client": { + "node_modules/sockjs-client": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.6.0.tgz", "integrity": "sha512-qVHJlyfdHFht3eBFZdKEXKTlb7I4IV41xnVNo8yUKA1UHcPJwgW2SvTq9LhnjjCywSkSK7c/e4nghU0GOoMCRQ==", - "requires": { + "dependencies": { "debug": "^3.2.7", "eventsource": "^1.1.0", "faye-websocket": "^0.11.4", "inherits": "^2.0.4", "url-parse": "^1.5.10" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://tidelift.com/funding/github/npm/sockjs-client" } }, - "source-map": { + "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "engines": { + "node": ">=0.10.0" + } }, - "source-map-js": { + "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==" + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "engines": { + "node": ">=0.10.0" + } }, - "stompjs": { + "node_modules/stompjs": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/stompjs/-/stompjs-2.3.3.tgz", "integrity": "sha512-5l/Ogz0DTFW7TrpHF0LAETGqM/so8UxNJvYZjJKqcX31EVprSQgnGkO80tZctPC/lFBDUrSFiTG3xd0R27XAIA==", - "requires": { - "websocket": "^1.0.35" - }, + "optionalDependencies": { + "websocket": "latest" + } + }, + "node_modules/stompjs/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "optional": true, "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "optional": true, - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "optional": true - }, - "websocket": { - "version": "1.0.35", - "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz", - "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==", - "optional": true, - "requires": { - "bufferutil": "^4.0.1", - "debug": "^2.2.0", - "es5-ext": "^0.10.63", - "typedarray-to-buffer": "^3.1.5", - "utf-8-validate": "^5.0.2", - "yaeti": "^0.0.6" - } - } + "ms": "2.0.0" } }, - "sweetalert2": { + "node_modules/stompjs/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "optional": true + }, + "node_modules/stompjs/node_modules/websocket": { + "version": "1.0.35", + "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz", + "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==", + "optional": true, + "dependencies": { + "bufferutil": "^4.0.1", + "debug": "^2.2.0", + "es5-ext": "^0.10.63", + "typedarray-to-buffer": "^3.1.5", + "utf-8-validate": "^5.0.2", + "yaeti": "^0.0.6" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/sweetalert2": { "version": "7.33.1", "resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-7.33.1.tgz", - "integrity": "sha512-69KYtyhtxejFG0HDb8aVhAwbpAWPSTZwaL5vxDHgojErD2KeFxTmRgmkbiLtMC8UdTFXRmvTPtZTF4459MUb7w==" + "integrity": "sha512-69KYtyhtxejFG0HDb8aVhAwbpAWPSTZwaL5vxDHgojErD2KeFxTmRgmkbiLtMC8UdTFXRmvTPtZTF4459MUb7w==", + "engines": { + "node": ">=0.10.0" + } }, - "type": { + "node_modules/type": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz", - "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==" + "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==", + "optional": true }, - "typedarray-to-buffer": { + "node_modules/typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", "optional": true, - "requires": { + "dependencies": { "is-typedarray": "^1.0.0" } }, - "url-parse": { + "node_modules/url-parse": { "version": "1.5.10", "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "requires": { + "dependencies": { "querystringify": "^2.1.1", "requires-port": "^1.0.0" } }, - "utf-8-validate": { + "node_modules/utf-8-validate": { "version": "5.0.10", "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, "optional": true, - "requires": { + "dependencies": { "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" } }, - "vanilla-picker": { + "node_modules/vanilla-picker": { "version": "2.8.0", "resolved": "https://registry.npmjs.org/vanilla-picker/-/vanilla-picker-2.8.0.tgz", "integrity": "sha512-NPBxrtLi2LA2mEyRLW+Lyt7Eqtm0t0SmKqscE5RaugXLtJXXjPzy6r65fqLiQkhRc2WoLnmj2m/EnTWKN4hL+g==", - "requires": { + "dependencies": { "@sphinxxxx/color-conversion": "^2.2.1", "drag-tracker": "^1.0.0" } }, - "vue": { + "node_modules/vue": { "version": "2.7.10", "resolved": "https://registry.npmjs.org/vue/-/vue-2.7.10.tgz", "integrity": "sha512-HmFC70qarSHPXcKtW8U8fgIkF6JGvjEmDiVInTkKZP0gIlEPhlVlcJJLkdGIDiNkIeA2zJPQTWJUI4iWe+AVfg==", - "requires": { + "deprecated": "Vue 2 has reached EOL and is no longer actively maintained. See https://v2.vuejs.org/eol/ for more details.", + "dependencies": { "@vue/compiler-sfc": "2.7.10", "csstype": "^3.1.0" } }, - "vue-axios": { + "node_modules/vue-axios": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/vue-axios/-/vue-axios-2.1.5.tgz", - "integrity": "sha512-th5xVbInVoyIoe+qY+9GCflEVezxAvztD4xpFF39SRQYqpoKD2qkmX8yv08jJG9a2SgNOCjirjJGSwg/wTrbmA==" + "integrity": "sha512-th5xVbInVoyIoe+qY+9GCflEVezxAvztD4xpFF39SRQYqpoKD2qkmX8yv08jJG9a2SgNOCjirjJGSwg/wTrbmA==", + "peerDependencies": { + "vue": ">= 1.0.0" + } }, - "vue-jsoneditor": { + "node_modules/vue-jsoneditor": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/vue-jsoneditor/-/vue-jsoneditor-1.0.13.tgz", "integrity": "sha512-dC4DBOmf9khDBzSauLLRI4AuoSha2A5L3q0ztR3tFDFGEYMJsk5G6ya2snyO3KkW8SyJKk+FcOfgAJtpXopa0A==", - "requires": { + "dependencies": { "jsoneditor": "^5.10.1", "vue": "^2.5.2" + }, + "engines": { + "node": ">= 4.0.0", + "npm": ">= 3.0.0" } }, - "websocket-driver": { + "node_modules/websocket-driver": { "version": "0.7.4", "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", - "requires": { + "dependencies": { "http-parser-js": ">=0.5.1", "safe-buffer": ">=5.1.0", "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" } }, - "websocket-extensions": { + "node_modules/websocket-extensions": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", - "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==" + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "engines": { + "node": ">=0.8.0" + } }, - "yaeti": { + "node_modules/yaeti": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==", - "optional": true + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "optional": true, + "engines": { + "node": ">=0.10.32" + } } } } diff --git a/build.gradle b/build.gradle index 1b311b710f..d3846ac578 100644 --- a/build.gradle +++ b/build.gradle @@ -55,7 +55,13 @@ processTestResources { } war { - dependsOn(':scadalts-ui:copyNewUiImages') + dependsOn( + ':scadalts-ui:copyNewUiJsSourceMap', + ':scadalts-ui:copyDataSourceJsSourceMap', + ':scadalts-ui:copyModernWatchListJsSourceMap', + ':scadalts-ui:copyPointHierarchyJsSourceMap', + ':scadalts-ui:copyViewsJsSourceMap' + ) from 'WebContent' webInf { from 'webapp-resources/' @@ -64,7 +70,13 @@ war { } task warDev(type: War) { - dependsOn(':scadalts-ui:copyNewUiWithSourceMap') + dependsOn( + ':scadalts-ui:copyNewUiJsSourceMap', + ':scadalts-ui:copyDataSourceJsSourceMap', + ':scadalts-ui:copyModernWatchListJsSourceMap', + ':scadalts-ui:copyPointHierarchyJsSourceMap', + ':scadalts-ui:copyViewsJsSourceMap' + ) from 'WebContent' webInf { from 'webapp-resources/' 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 339493c956..a647318868 100644 --- a/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java +++ b/src/br/org/scadabr/vo/exporter/util/SystemSettingsJSONWrapper.java @@ -43,7 +43,7 @@ public void jsonDeserialize(JsonReader reader, JsonObject json) Set> defaultValues = SystemSettingsDAO.DEFAULT_VALUES .entrySet(); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); for (Entry entry : defaultValues) { String key = entry.getKey(); diff --git a/src/com/serotonin/mango/MangoContextListener.java b/src/com/serotonin/mango/MangoContextListener.java index 0b6427bee7..8249f650c9 100644 --- a/src/com/serotonin/mango/MangoContextListener.java +++ b/src/com/serotonin/mango/MangoContextListener.java @@ -156,7 +156,7 @@ private void initialized(ServletContextEvent evt) { + knownContextPath + " to " + contextPath + ". Are there two instances of Scada-LTS running?"); } - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setValue(SystemSettingsDAO.SERVLET_CONTEXT_PATH, ctx.getContextPath()); eventManagerInitialize(ctx); diff --git a/src/com/serotonin/mango/db/DatabaseAccess.java b/src/com/serotonin/mango/db/DatabaseAccess.java index 1ca2c381b9..b81dc595a3 100644 --- a/src/com/serotonin/mango/db/DatabaseAccess.java +++ b/src/com/serotonin/mango/db/DatabaseAccess.java @@ -14,10 +14,14 @@ package com.serotonin.mango.db; 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; @@ -45,7 +49,6 @@ abstract public class DatabaseAccess { private final static Log log = LogFactory.getLog(DatabaseAccess.class); - @Deprecated public enum DatabaseType { DERBY { @Override @@ -64,12 +67,29 @@ DatabaseAccess getImpl() { 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(); + } }, POSTGRES { @Override DatabaseAccess getImpl() { return new PostgreSQLAccess(); } + + @Override + public int getBinarySqlType() { + return Types.BINARY; + } }, ORACLE11G { @Override @@ -78,20 +98,47 @@ DatabaseAccess getImpl() { } }; + 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(); + if ("postgresql".equals(normalized) || "pgsql".equals(normalized) || "pg".equals(normalized)) { + return POSTGRES; + } + if ("mssqlserver".equals(normalized) || "mssql".equals(normalized)) { + return MSSQL; + } + if ("mysqlserver".equals(normalized) || "mysql".equals(normalized)) { + return MYSQL; + } + 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(); } - @Deprecated 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() { @@ -119,13 +166,7 @@ public void initialize(ServletContext ctx) { if (!StringUtils.isEmpty(convertTypeStr)) { // Found a database type from which to convert. - String convertKey = normalizeDbKey(convertTypeStr); - if (StringUtils.isEmpty(convertKey)) { - throw new IllegalArgumentException( - "Unknown convert database type: " + convertTypeStr); - } - - DatabaseAccess sourceAccess = resolveDatabaseAccess(convertKey); + DatabaseAccess sourceAccess = resolveDatabaseAccess(DatabaseType.from(convertTypeStr)); if (sourceAccess == this) { throw new IllegalStateException( "convert.db.type must be different from db.type."); @@ -158,7 +199,7 @@ public void initialize(ServletContext ctx) { new UserDao().saveUser(user); // Record the current version. - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setValue( SystemSettingsDAO.DATABASE_SCHEMA_VERSION, Common.getVersion()); @@ -174,7 +215,7 @@ public void initialize(ServletContext ctx) { } } catch (CannotGetJdbcConnectionException e) { log.fatal("Unable to connect to database of type " - + getTypeKey(), e); + + getType().name(), e); throw e; } @@ -193,12 +234,28 @@ private void initDataSource() { } } - abstract public String getTypeKey(); + 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(); @@ -275,29 +332,13 @@ public PreparedStatement prepareStatement(Connection connection, return connection.prepareStatement(sql, 1); } - private static DatabaseAccess resolveDatabaseAccess(String dbKey) { - String normalized = normalizeDbKey(dbKey); - String beanName = "databaseAccess-" + normalized; + 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=" + normalized + throw new IllegalStateException("DB plugin not found for db.type=" + dbType.getKey() + ". Expected bean '" + beanName + "'."); } return access; } - - private static String normalizeDbKey(String dbType) { - if (dbType == null) { - return ""; - } - String normalized = dbType.trim().toLowerCase(); - if ("postgresql".equals(normalized) || "pgsql".equals(normalized) || "pg".equals(normalized)) { - return "postgres"; - } - if ("sqlserver".equals(normalized) || "sql-server".equals(normalized)) { - return "mssql"; - } - return normalized; - } - } diff --git a/src/com/serotonin/mango/db/DerbyAccess.java b/src/com/serotonin/mango/db/DerbyAccess.java index 315ec2884d..5866955c39 100644 --- a/src/com/serotonin/mango/db/DerbyAccess.java +++ b/src/com/serotonin/mango/db/DerbyAccess.java @@ -58,8 +58,8 @@ public class DerbyAccess extends DatabaseAccess { private EmbeddedXADataSource40 dataSource; @Override - public String getTypeKey() { - return "derby"; + public DatabaseType getType() { + return DatabaseType.DERBY; } @Override diff --git a/src/com/serotonin/mango/db/MSSQLAccess.java b/src/com/serotonin/mango/db/MSSQLAccess.java index dba6ba1ed6..b13fc7e2da 100644 --- a/src/com/serotonin/mango/db/MSSQLAccess.java +++ b/src/com/serotonin/mango/db/MSSQLAccess.java @@ -29,8 +29,8 @@ public class MSSQLAccess extends BasePooledAccess { @Override - public String getTypeKey() { - return "mssql"; + public DatabaseType getType() { + return DatabaseType.MSSQL; } @Override diff --git a/src/com/serotonin/mango/db/MySQLAccess.java b/src/com/serotonin/mango/db/MySQLAccess.java index 1ce36e8e75..f2e288f263 100644 --- a/src/com/serotonin/mango/db/MySQLAccess.java +++ b/src/com/serotonin/mango/db/MySQLAccess.java @@ -61,8 +61,8 @@ protected String getUrl(String propertyPrefix) { } @Override - public String getTypeKey() { - return "mysql"; + public DatabaseType getType() { + return DatabaseType.MYSQL; } @Override diff --git a/src/com/serotonin/mango/db/Oracle11GAccess.java b/src/com/serotonin/mango/db/Oracle11GAccess.java index 7071bca39b..db4d4d93cf 100644 --- a/src/com/serotonin/mango/db/Oracle11GAccess.java +++ b/src/com/serotonin/mango/db/Oracle11GAccess.java @@ -67,8 +67,8 @@ protected void initializeImpl(String propertyPrefix, String dataSourceName) { } @Override - public String getTypeKey() { - return "oracle11g"; + public DatabaseType getType() { + return DatabaseType.ORACLE11G; } @Override diff --git a/src/com/serotonin/mango/db/PostgreSQLAccess.java b/src/com/serotonin/mango/db/PostgreSQLAccess.java index 1736e0bf41..05e3d578df 100644 --- a/src/com/serotonin/mango/db/PostgreSQLAccess.java +++ b/src/com/serotonin/mango/db/PostgreSQLAccess.java @@ -59,8 +59,8 @@ protected String getUrl(String propertyPrefix) { } @Override - public String getTypeKey() { - return "postgres"; + public DatabaseType getType() { + return DatabaseType.POSTGRES; } @Override diff --git a/src/com/serotonin/mango/db/dao/DataSourceDao.java b/src/com/serotonin/mango/db/dao/DataSourceDao.java index 36d8d046ba..4d87b8b244 100644 --- a/src/com/serotonin/mango/db/dao/DataSourceDao.java +++ b/src/com/serotonin/mango/db/dao/DataSourceDao.java @@ -27,12 +27,12 @@ import java.util.ResourceBundle; import org.scada_lts.dao.DAO; -import org.scada_lts.web.beans.ApplicationBeans; import org.scada_lts.mango.adapter.MangoDataSource; import org.scada_lts.mango.service.DataSourceService; import org.springframework.dao.DataAccessException; import com.serotonin.db.spring.GenericResultSetExtractor; +import com.serotonin.mango.db.DatabaseAccess; import com.serotonin.mango.vo.dataSource.DataSourceVO; import com.serotonin.util.SerializationHelper; @@ -82,7 +82,7 @@ public Serializable extractData(ResultSet rs) if (!rs.next()) return null; - InputStream is = ApplicationBeans.getBinaryDataHandler().getBinaryStream(rs, 1); + InputStream is = DatabaseAccess.getDatabaseAccess().getBinaryStream(rs, 1); if (is == null) return null; @@ -97,7 +97,7 @@ public void savePersistentData(int id, Object data) { "update dataSources set rtdata=? where id=?", new Object[] { SerializationHelper.writeObject(data), id }, new int[] { - ApplicationBeans.getBinaryDataHandler().getBinarySqlType(), + DatabaseAccess.getDatabaseAccess().getBinarySqlType(), Types.INTEGER }); } } diff --git a/src/com/serotonin/mango/db/upgrade/DBUpgrade.java b/src/com/serotonin/mango/db/upgrade/DBUpgrade.java index d1bef2aaf0..de08be9099 100644 --- a/src/com/serotonin/mango/db/upgrade/DBUpgrade.java +++ b/src/com/serotonin/mango/db/upgrade/DBUpgrade.java @@ -86,7 +86,7 @@ public static void checkUpgrade() { LOG.warn("Upgrading instance from " + schemaVersion + " to " + upgrade.getNewSchemaVersion()); upgrade.upgrade(); - ISystemSettingsDAO systemSettingsDAO = org.scada_lts.web.beans.ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = org.scada_lts.web.beans.ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setValue( SystemSettingsDAO.DATABASE_SCHEMA_VERSION, upgrade.getNewSchemaVersion()); diff --git a/src/com/serotonin/mango/rt/RuntimeManager.java b/src/com/serotonin/mango/rt/RuntimeManager.java index e89cfed522..442a368528 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.getBean("pointEventDetectorDAO", IPointEventDetectorDAO.class); + 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.getBean("eventDAO", IEventDAO.class); 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.getBean("eventDAO", IEventDAO.class); 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 fcd41b6017..90a8ab15b9 100644 --- a/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java +++ b/src/com/serotonin/mango/rt/dataSource/sql/SqlDataSourceRT.java @@ -30,6 +30,7 @@ import com.serotonin.ShouldNeverHappenException; import com.serotonin.io.StreamUtils; 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; @@ -45,7 +46,6 @@ import com.serotonin.mango.vo.dataSource.sql.SqlPointLocatorVO; import com.serotonin.util.StringUtils; import com.serotonin.web.i18n.LocalizableMessage; -import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.jdbc.core.*; import static com.serotonin.mango.util.SqlDataSourceUtils.addLimitIfWithout; @@ -282,7 +282,7 @@ else if (dataType == DataTypes.NUMERIC) return new NumericValue(rs.getDouble(fieldName)); else if (dataType == DataTypes.IMAGE) { ByteArrayOutputStream out = new ByteArrayOutputStream(); - StreamUtils.transfer(ApplicationBeans.getBinaryDataHandler().getBinaryStream(rs, fieldName), 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 f3cb8dd790..25911c7bba 100644 --- a/src/com/serotonin/mango/rt/event/type/AuditEventType.java +++ b/src/com/serotonin/mango/rt/event/type/AuditEventType.java @@ -107,7 +107,7 @@ public static void setEventTypeAlarmLevel(int type, int alarmLevel) { EventTypeVO et = getEventType(type); et.setAlarmLevel(alarmLevel); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setIntValue(AUDIT_SETTINGS_PREFIX + type, alarmLevel); } 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 969f3abdd8..23d9cfe425 100644 --- a/src/com/serotonin/mango/rt/event/type/SystemEventType.java +++ b/src/com/serotonin/mango/rt/event/type/SystemEventType.java @@ -146,7 +146,7 @@ public static void setEventTypeAlarmLevel(int type, int alarmLevel) { if(et != null) { et.setAlarmLevel(alarmLevel); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + 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/web/dwr/DataSourceEditDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java index 340c85d9d9..070d0abdf8 100644 --- a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java @@ -396,7 +396,7 @@ public DwrResponseI18n togglePoint(int dataPointId) { User user = Common.getUser(); DataPointService dataPointService = new DataPointService(); DataPointVO dataPoint = dataPointService.getDataPoint(dataPointId); - DwrResponseI18n response = super.toggleDataPoint(dataPoint); + DwrResponseI18n response = super.toggleDataPointInternal(dataPoint); response.addData("points", GetDataPointsUtils.getDataPointsByDataSource(user, dataPoint.getDataSourceId(), dataPointService)); return response; } @@ -3180,4 +3180,4 @@ public DwrResponseI18n validateAndSaveDataPoint(DataPointVO dp) { return response; } -} \ No newline at end of file +} diff --git a/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java index 01ca5b5a2c..2382960bb5 100644 --- a/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java @@ -123,10 +123,10 @@ public int deleteDataSource(int dataSourceId) { public DwrResponseI18n toggleDataPoint(int dataPointId) { DataPointVO dataPoint = new DataPointDao().getDataPoint(dataPointId); - return toggleDataPoint(dataPoint); + return toggleDataPointInternal(dataPoint); } - public DwrResponseI18n toggleDataPoint(DataPointVO dataPoint) { + protected DwrResponseI18n toggleDataPointInternal(DataPointVO dataPoint) { Permissions.ensureDataSourcePermission(Common.getUser(), dataPoint.getDataSourceId()); diff --git a/src/com/serotonin/mango/web/dwr/EmportDwr.java b/src/com/serotonin/mango/web/dwr/EmportDwr.java index 9f314cc6c3..0f901a1fe2 100644 --- a/src/com/serotonin/mango/web/dwr/EmportDwr.java +++ b/src/com/serotonin/mango/web/dwr/EmportDwr.java @@ -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,7 @@ public boolean loadProject() { try { Permissions.ensureAdmin(user); stopRunningDataSources(); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.resetDataBase(); importer.importProject(); } catch (Exception e) { diff --git a/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java b/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java index 92fe4bb20a..542f6f17a6 100644 --- a/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java +++ b/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java @@ -247,7 +247,7 @@ public Map getDatabaseSize() { String dbType = checkTypeDB(); if (dbType.equalsIgnoreCase("mysql") || dbType.equalsIgnoreCase("postgres")) { - double size = ApplicationBeans.getSystemSettingsDAOBean().getDataBaseSize(); + double size = ApplicationBeans.getSystemSettingsDaoBean().getDatabaseSize(); if (size >= 0) { data.put("databaseSize", size + " MB"); data.put("filedataCount", 0); @@ -280,7 +280,7 @@ public void saveEmailSettings(String host, int port, String from, String name, boolean auth, String username, String password, boolean tls, int contentType) { Permissions.ensureAdmin(); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + 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); @@ -403,7 +403,7 @@ public void saveDataRetentionSettings(int eventPurgePeriodType, int futureDateLimitPeriodType, int futureDateLimitPeriods, int defaultPurgePeriod, int defaultPurgePeriodType, int valuesLimitForPurge) { Permissions.ensureAdmin(); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO .setIntValue(SystemSettingsDAO.EVENT_PURGE_PERIOD_TYPE, eventPurgePeriodType); @@ -465,7 +465,7 @@ public DwrResponseI18n saveColourSettings(String chartBackgroundColour, } if (!response.getHasMessages()) { - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setValue( SystemSettingsDAO.CHART_BACKGROUND_COLOUR, chartBackgroundColour); @@ -483,7 +483,7 @@ public DwrResponseI18n saveColourSettings(String chartBackgroundColour, public void saveInfoSettings(String newVersionNotificationLevel, String instanceDescription,String topDescriptionPrefix, String topDescription) { Permissions.ensureAdmin(); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setValue( SystemSettingsDAO.NEW_VERSION_NOTIFICATION_LEVEL, newVersionNotificationLevel); @@ -547,12 +547,24 @@ public void useMysqlDB() { } + public void usePostgresDB() { + Permissions.ensureAdmin(); + ConfigurationDB.usePostgresDB(); + } + + public void useMssqlDB() { Permissions.ensureAdmin(); ConfigurationDB.useMssqlDB(); } + public void useOracle11gDB() { + Permissions.ensureAdmin(); + ConfigurationDB.useOracle11gDB(); + } + + public String checkTypeDB() { try { DatabaseAccess databaseAccess = DatabaseAccess.getDatabaseAccess(); diff --git a/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java b/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java index fd244d8477..3de92b5065 100644 --- a/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java +++ b/src/com/serotonin/mango/web/mvc/controller/ScadaLocaleUtils.java @@ -81,7 +81,7 @@ public static void setSystemLanguage(String language) { if (locale == null) throw new IllegalArgumentException( "Locale for given language not found: " + language); - ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + ISystemSettingsDAO systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); systemSettingsDAO.setValue(SystemSettingsDAO.LANGUAGE, language); } diff --git a/src/org/scada_lts/cache/ViewHierarchyCache.java b/src/org/scada_lts/cache/ViewHierarchyCache.java index a59ff5a7f0..1ebcb4adb4 100644 --- a/src/org/scada_lts/cache/ViewHierarchyCache.java +++ b/src/org/scada_lts/cache/ViewHierarchyCache.java @@ -23,7 +23,6 @@ import org.apache.commons.logging.LogFactory; import org.scada_lts.service.ViewHierarchyService; import org.scada_lts.service.model.ViewHierarchyJSON; -import org.scada_lts.web.beans.ApplicationBeans; /** * Class responsible for buffering data of ViewHierarchy @@ -45,9 +44,7 @@ private ViewHierarchyCache() { private void initial() { LOG.info("Initial ViewHierarchyCache"); - ViewHierarchyService service = ApplicationBeans.getViewHierarchyServiceBean(); - - cache = service.getAll(); + cache = new ViewHierarchyService().getAll(); } public static ViewHierarchyCache getInstance() { @@ -64,7 +61,7 @@ public List getAll() { } public void refresh() { - cache = ApplicationBeans.getViewHierarchyServiceBean().getAll(); + cache = new ViewHierarchyService().getAll(); } } diff --git a/src/org/scada_lts/dao/IPointEventDetectorDAO.java b/src/org/scada_lts/dao/IPointEventDetectorDAO.java index c641011285..b03c0d712e 100644 --- a/src/org/scada_lts/dao/IPointEventDetectorDAO.java +++ b/src/org/scada_lts/dao/IPointEventDetectorDAO.java @@ -8,6 +8,7 @@ public interface IPointEventDetectorDAO { default void init() {}; List getPointEventDetectors(DataPointVO dataPoint); + List getPointEventDetectors(long limit, int offset); boolean isEventDetectorXidUnique(int dataPointId, String xid, int excludeId); int insert(int dataPointId, PointEventDetectorVO pointEventDetector); void update(int dataPointId, PointEventDetectorVO pointEventDetector); diff --git a/src/org/scada_lts/dao/ISystemSettingsDAO.java b/src/org/scada_lts/dao/ISystemSettingsDAO.java index 357aca1e5c..8827c92218 100644 --- a/src/org/scada_lts/dao/ISystemSettingsDAO.java +++ b/src/org/scada_lts/dao/ISystemSettingsDAO.java @@ -7,6 +7,6 @@ public interface ISystemSettingsDAO { public abstract void removeValue(java.lang.String arg0); public abstract java.lang.String getDatabaseSchemaVersion(java.lang.String arg0, java.lang.String arg1); public abstract void resetDataBase(); - public abstract double getDataBaseSize(); + public abstract double getDatabaseSize(); } diff --git a/src/org/scada_lts/dao/PointEventDetectorDAO.java b/src/org/scada_lts/dao/PointEventDetectorDAO.java index dacc27b457..2efe232389 100644 --- a/src/org/scada_lts/dao/PointEventDetectorDAO.java +++ b/src/org/scada_lts/dao/PointEventDetectorDAO.java @@ -475,6 +475,7 @@ public PointEventDetectorVO getPointEventDetector(String pointEventDetectorXid, } } + @Override public List getPointEventDetectors(long limit, int offset) { if (LOG.isTraceEnabled()) { LOG.trace("getPointEventDetector(long limit, int offset) limit:" +limit + ", offset:" + offset); diff --git a/src/org/scada_lts/dao/SystemSettingsDAO.java b/src/org/scada_lts/dao/SystemSettingsDAO.java index 35b84f2cae..b140951cd0 100644 --- a/src/org/scada_lts/dao/SystemSettingsDAO.java +++ b/src/org/scada_lts/dao/SystemSettingsDAO.java @@ -462,7 +462,8 @@ public void resetDataBase() { ApplicationBeans.getBean("userCommentCache", UserCommentCacheable.class).resetCache(); } - public double getDataBaseSize() { + @Override + public double getDatabaseSize() { final List size = new ArrayList<>(); diff --git a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java index c9799cfc87..73f6f1c8f6 100644 --- a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java @@ -3,28 +3,35 @@ import com.serotonin.mango.Common; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.event.PointEventDetectorVO; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.*; import org.scada_lts.web.beans.ApplicationBeans; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class PointEventDetectorDaoWithCache implements IPointEventDetectorDAO { + private static final Log LOG = LogFactory.getLog(PointEventDetectorDaoWithCache.class); + private final PointEventDetectorCacheable pointEventDetectorCache; + private final IPointEventDetectorDAO pointEventDetectorDAO; - public PointEventDetectorDaoWithCache(PointEventDetectorCacheable pointEventDetectorCache) { + public PointEventDetectorDaoWithCache(PointEventDetectorCacheable pointEventDetectorCache, + IPointEventDetectorDAO pointEventDetectorDAO) { this.pointEventDetectorCache = pointEventDetectorCache; + this.pointEventDetectorDAO = pointEventDetectorDAO; } @Override public void init() { IDataPointDAO dao = ApplicationBeans.getDataPointDAOBean(); List dataPoints = dao.getDataPoints(); - Map> pointEventDetectors = new PointEventDetectorDAO() - .getPointEventDetectors(Integer.MAX_VALUE, 0) + Map> pointEventDetectors = loadPointEventDetectors(Integer.MAX_VALUE, 0) .stream() .collect(Collectors.groupingBy(a -> a.njbGetDataPoint().getId())); for(DataPointVO dataPoint: dataPoints) { @@ -96,4 +103,26 @@ public PointEventDetectorVO getPointEventDetector(String pointEventDetectorXid, public int getDataPointId(int pointEventDetectorId) { return pointEventDetectorCache.selectDataPointIdByEventDetectorId(pointEventDetectorId); } + + @Override + public List getPointEventDetectors(long limit, int offset) { + if (LOG.isTraceEnabled()) { + LOG.trace("getPointEventDetector(long limit, int offset) limit:" + limit + ", offset:" + offset); + } + + try { + return loadPointEventDetectors(limit, offset); + } catch (Exception ex) { + LOG.warn(ex.getMessage(), ex); + return Collections.emptyList(); + } + } + + private List loadPointEventDetectors(long limit, int offset) { + if (limit <= 0 || offset < 0) { + return Collections.emptyList(); + } + + return pointEventDetectorDAO.getPointEventDetectors(limit, offset); + } } diff --git a/src/org/scada_lts/db/BinaryDataHandler.java b/src/org/scada_lts/db/BinaryDataHandler.java deleted file mode 100644 index 282ab10bfe..0000000000 --- a/src/org/scada_lts/db/BinaryDataHandler.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.scada_lts.db; - -import java.io.InputStream; -import java.sql.ResultSet; -import java.sql.SQLException; - -public interface BinaryDataHandler { - - InputStream getBinaryStream(ResultSet rs, int columnIndex) throws SQLException; - - InputStream getBinaryStream(ResultSet rs, String columnLabel) throws SQLException; - - int getBinarySqlType(); -} diff --git a/src/org/scada_lts/db/MysqlBinaryDataHandler.java b/src/org/scada_lts/db/MysqlBinaryDataHandler.java deleted file mode 100644 index 058187f4e7..0000000000 --- a/src/org/scada_lts/db/MysqlBinaryDataHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.scada_lts.db; - -import java.io.InputStream; -import java.sql.Blob; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; - -public class MysqlBinaryDataHandler implements BinaryDataHandler { - - @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 int getBinarySqlType() { - return Types.BLOB; - } -} diff --git a/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java b/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java index 515251aade..e8b6b3b2b6 100644 --- a/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java +++ b/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java @@ -1,6 +1,7 @@ package org.scada_lts.factory; import com.serotonin.mango.Common; +import com.serotonin.mango.db.DatabaseAccess.DatabaseType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.FactoryBean; @@ -78,21 +79,7 @@ public void setApplicationContext(ApplicationContext applicationContext) { private String resolveDbKey() { String dbType = Common.getEnvironmentProfile().getString("db.type", DEFAULT_DB_TYPE); - return normalizeDbKey(dbType); - } - - private static String normalizeDbKey(String dbType) { - if (dbType == null) { - return ""; - } - String normalized = dbType.trim().toLowerCase(); - if ("postgresql".equals(normalized) || "pgsql".equals(normalized) || "pg".equals(normalized)) { - return "postgres"; - } - if ("mssqlserver".equals(normalized) || "mssql-server".equals(normalized) || "mssql".equals(normalized)) { - return "mssql"; - } - return normalized; + return DatabaseType.from(dbType).getKey(); } private void ensureDbPluginLoaded(String dbKey) { diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index f187ccb8d0..7694be1127 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -546,10 +546,6 @@ static void add(BatchWriteBehindEntry e) { private int instancesSize; private int entriesSize; - public static void setPointValueDAO(IPointValueDAO dao) { - pointValueDAO = dao; - } - @Override public void work() { try { diff --git a/src/org/scada_lts/mango/service/SystemSettingsService.java b/src/org/scada_lts/mango/service/SystemSettingsService.java index b33f40fb5a..0bb75c1a75 100644 --- a/src/org/scada_lts/mango/service/SystemSettingsService.java +++ b/src/org/scada_lts/mango/service/SystemSettingsService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.serotonin.mango.Common; import com.serotonin.mango.db.DatabaseAccess; +import com.serotonin.mango.db.DatabaseAccess.DatabaseType; import com.serotonin.mango.db.dao.DataPointDao; import com.serotonin.mango.rt.dataImage.DataPointSyncMode; import com.serotonin.mango.rt.event.type.AuditEventType; @@ -54,7 +55,7 @@ public class SystemSettingsService { private final ISystemSettingsDAO systemSettingsDAO; public SystemSettingsService() { - systemSettingsDAO = ApplicationBeans.getSystemSettingsDAOBean(); + systemSettingsDAO = ApplicationBeans.getSystemSettingsDaoBean(); } public Map getSettings() { @@ -270,14 +271,23 @@ public String getDatabaseType() { } public void setDatabaseType(String databaseType) { - if (databaseType.equalsIgnoreCase("mysql")) { - ConfigurationDB.useMysqlDB(); - } else if (databaseType.equalsIgnoreCase("mssql")) { - ConfigurationDB.useMssqlDB(); - } else if (databaseType.equalsIgnoreCase("oracle11g")) { - ConfigurationDB.useOracle11gDB(); - } else { - ConfigurationDB.useDerbyDB(); + String dbKey = DatabaseType.from(databaseType).getKey(); + switch (dbKey) { + case "mysql": + ConfigurationDB.useMysqlDB(); + break; + case "postgres": + ConfigurationDB.usePostgresDB(); + break; + case "mssql": + ConfigurationDB.useMssqlDB(); + break; + case "oracle11g": + ConfigurationDB.useOracle11gDB(); + break; + default: + ConfigurationDB.useDerbyDB(); + break; } } @@ -302,7 +312,7 @@ public Map getDatabaseSize() { String dbType = getDatabaseType(); if (dbType.equalsIgnoreCase("mysql") || dbType.equalsIgnoreCase("postgres")) { - double size = systemSettingsDAO.getDataBaseSize(); + double size = systemSettingsDAO.getDatabaseSize(); if (size >= 0) { data.put("databaseSize", size + "MB"); data.put("filedataCount", 0); diff --git a/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java b/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java index 1865d79ed3..963107bbfe 100644 --- a/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java +++ b/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java @@ -9,6 +9,7 @@ import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.dao.watchlist.IWatchListDAO; import org.scada_lts.dao.watchlist.WatchListDAO; +import org.scada_lts.web.beans.ApplicationBeans; import java.util.Collections; import java.util.List; @@ -22,7 +23,7 @@ public class GetWatchListsWithAccess implements GetObjectsWithAccess relations; private final Set blocking; - InactiveEventsProviderImpl(EventDAO eventDAO, ScheduledExecuteInactiveEventDAO scheduledEventDAO, + InactiveEventsProviderImpl(IEventDAO eventDAO, ScheduledExecuteInactiveEventDAO scheduledEventDAO, CommunicationChannel communicationChannel, int dataFromBaseLimit) { this.eventDAO = eventDAO; this.scheduledEventDAO = scheduledEventDAO; @@ -45,7 +45,7 @@ class InactiveEventsProviderImpl implements InactiveEventsProvider { this.dataFromBaseLimit = dataFromBaseLimit; } - private static Set init(EventDAO eventDAO, + private static Set init(IEventDAO eventDAO, ScheduledExecuteInactiveEventDAO scheduledEventDAO, CommunicationChannel communicationChannel, Set exclude, diff --git a/src/org/scada_lts/service/ViewHierarchyService.java b/src/org/scada_lts/service/ViewHierarchyService.java index c599067023..c274082f42 100644 --- a/src/org/scada_lts/service/ViewHierarchyService.java +++ b/src/org/scada_lts/service/ViewHierarchyService.java @@ -27,6 +27,7 @@ import org.scada_lts.dao.model.viewshierarchy.ViewHierarchyNode; import org.scada_lts.dao.model.viewshierarchy.ViewInViewHierarchyNode; import org.scada_lts.service.model.ViewHierarchyJSON; +import org.scada_lts.web.beans.ApplicationBeans; import org.slf4j.profiler.Profiler; import com.serotonin.mango.view.View; @@ -56,6 +57,11 @@ public ViewHierarchyService(IViewHierarchyDAO vhDAO, IViewDAO viewDAO){ this.vhDAO = vhDAO; this.viewDAO = viewDAO; } + + public ViewHierarchyService(){ + this.vhDAO = ApplicationBeans.getBean("viewHierarchyDAO", IViewHierarchyDAO.class); + this.viewDAO = ApplicationBeans.getViewDaoBean(); + } private List getChildFolder(long l) { ArrayList lst = new ArrayList(); diff --git a/src/org/scada_lts/web/beans/ApplicationBeans.java b/src/org/scada_lts/web/beans/ApplicationBeans.java index 7563ae08ea..3c5e5371dd 100644 --- a/src/org/scada_lts/web/beans/ApplicationBeans.java +++ b/src/org/scada_lts/web/beans/ApplicationBeans.java @@ -14,7 +14,6 @@ import com.serotonin.mango.vo.permission.DataPointAccess; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.db.BinaryDataHandler; import org.scada_lts.dao.*; import org.scada_lts.dao.alarms.IAlarmsDAO; import org.scada_lts.dao.cache.*; @@ -168,14 +167,6 @@ public static ObjectMapper getObjectMapper() { return getBeanFromContext("objectMapper", ObjectMapper.class); } - public static BinaryDataHandler getBinaryDataHandler() { - BinaryDataHandler handler = getBeanFromContext("binaryDataHandler", BinaryDataHandler.class); - if (handler == null) { - throw new IllegalStateException("binaryDataHandler bean is missing."); - } - return handler; - } - public static class Lazy { private Lazy() {} @@ -227,10 +218,6 @@ private static ApplicationContext getBeansApplication() { return GetApplicationBeans.context() == null ? null : GetApplicationBeans.context(); } - public static ViewHierarchyService getViewHierarchyServiceBean() { - return getBean("viewHierarchyService", ViewHierarchyService.class); - } - public static IDataPointDAO getDataPointDAOBean(){ return getBean("dataPointDAO", IDataPointDAO.class); } @@ -259,7 +246,7 @@ public static IPendingEventsDAO getPendingEventsDAOBean() { return getBean("pendingEventsDAO", IPendingEventsDAO.class); } - public static ISystemSettingsDAO getSystemSettingsDAOBean() { + public static ISystemSettingsDAO getSystemSettingsDaoBean() { return getBean("systemSettingsDAO", ISystemSettingsDAO.class); } diff --git a/src/org/scada_lts/web/mvc/api/DataPointApiService.java b/src/org/scada_lts/web/mvc/api/DataPointApiService.java index 49adb9a05a..b0510b2343 100644 --- a/src/org/scada_lts/web/mvc/api/DataPointApiService.java +++ b/src/org/scada_lts/web/mvc/api/DataPointApiService.java @@ -292,17 +292,13 @@ private List searchDataPoint(HttpServletRequest request, boolean hasTypeOrSettableFilter = (searchDataPointJson.getDataTypes() != null && !searchDataPointJson.getDataTypes().isEmpty()) || (searchDataPointJson.getSettable() != null); - boolean hasExcludeIds = - searchDataPointJson.getExcludeIds() != null && !searchDataPointJson.getExcludeIds().isEmpty(); - if(!hasTypeOrSettableFilter && !hasExcludeIds) { + if(!hasTypeOrSettableFilter) { return dataPointService.getDataPoints(searchDataPointJson.getKeywordSearch(), searchDataPointJson.getExcludeIds(), searchDataPointJson.isStartsWith(), page, searchDataPointJson.getLimit()); } else { - // Exclude ids are handled by filterByExcludeIds below. - // Keep DAO query free from NOT IN to avoid SQL-dialect issues. List points = dataPointService.getDataPoints(searchDataPointJson.getKeywordSearch(), - null, searchDataPointJson.isStartsWith(), + searchDataPointJson.getExcludeIds(), searchDataPointJson.isStartsWith(), -1, -1); return filteredAndPaginationPoints(user, searchDataPointJson, points); } diff --git a/src/org/scada_lts/web/mvc/controller/SqlController.java b/src/org/scada_lts/web/mvc/controller/SqlController.java index 68929837a0..8b2ae4409d 100644 --- a/src/org/scada_lts/web/mvc/controller/SqlController.java +++ b/src/org/scada_lts/web/mvc/controller/SqlController.java @@ -44,8 +44,8 @@ import org.springframework.web.servlet.ModelAndView; import com.serotonin.mango.vo.permission.Permissions; +import com.serotonin.mango.db.DatabaseAccess; import com.serotonin.util.SerializationHelper; -import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.web.util.WebUtils; /** @@ -128,7 +128,7 @@ private static List> query(final String sql, final JdbcTemplate jdb row.add(rs.getString(i + 1)); else if (meta.getColumnType(i + 1) == Types.LONGVARBINARY || meta.getColumnType(i + 1) == Types.BLOB || meta.getColumnType(i + 1) == Types.BINARY) { - Object o = SerializationHelper.readObject(ApplicationBeans.getBinaryDataHandler().getBinaryStream(rs, i + 1)); + Object o = SerializationHelper.readObject(DatabaseAccess.getDatabaseAccess().getBinaryStream(rs, i + 1)); row.add("Serialized data(" + o + ")"); } else row.add(rs.getObject(i + 1)); diff --git a/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java b/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java index 2af2b03258..922a385ba0 100644 --- a/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java +++ b/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java @@ -156,7 +156,7 @@ public IsEventDetectorXidUniqueTest(PointEventDetectorVO pointEventDetector1, Po public void config() { PointEventDetectorDAO pointEventDetectorDaoMock = mock(PointEventDetectorDAO.class); PointEventDetectorCache pointEventDetectorCache = new PointEventDetectorCache(pointEventDetectorDaoMock); - subject = new PointEventDetectorDaoWithCache(pointEventDetectorCache); + subject = new PointEventDetectorDaoWithCache(pointEventDetectorCache, pointEventDetectorDaoMock); when(pointEventDetectorDaoMock.getPointEventDetector(eq(pointEventDetector1.getXid()), eq(dataPointId))).thenReturn(pointEventDetector1); when(pointEventDetectorDaoMock.getPointEventDetector(eq(pointEventDetector2.getXid()), eq(dataPointId))).thenReturn(pointEventDetector2); diff --git a/test/org/scada_lts/dao/SystemSettingsDaoTest.java b/test/org/scada_lts/dao/SystemSettingsDaoTest.java index 5406f45cb4..fdd51f132c 100644 --- a/test/org/scada_lts/dao/SystemSettingsDaoTest.java +++ b/test/org/scada_lts/dao/SystemSettingsDaoTest.java @@ -17,10 +17,9 @@ */ package org.scada_lts.dao; -import org.junit.Test; -import org.scada_lts.dao.report.IReportInstanceDAO; -import org.scada_lts.dao.report.ReportInstanceDAO; -import org.springframework.dao.EmptyResultDataAccessException; +import org.junit.Test; +import org.scada_lts.dao.report.IReportInstanceDAO; +import org.scada_lts.dao.report.ReportInstanceDAO; import static org.junit.Assert.assertTrue; @@ -31,7 +30,7 @@ */ public class SystemSettingsDaoTest extends TestDAO { - private static final ISystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO(); + private static final ISystemSettingsDAO systemSettingsDAO = new SystemSettingsDAO(); private static final String SETTING_NAME = "settingName"; private static final String SETTING_VALUE = "/ScadaLTS"; @@ -68,7 +67,7 @@ public void valueTest() { @Test public void databaseTest() { - double emptySize = systemSettingsDAO.getDataBaseSize(); + double emptySize = systemSettingsDAO.getDatabaseSize(); assertTrue(emptySize > 0); DAO.getInstance().getJdbcTemp().update("INSERT INTO datasources (`xid`,`name`,`dataSourceType`,`data`) " @@ -112,12 +111,12 @@ public void databaseTest() { + "runEndTime, recordCount, preventPurge) " + "VALUES (1, 'fName', 1, false, 2, 542145, 321, 123456, 32, true)"); - double sizeWithRecords = systemSettingsDAO.getDataBaseSize(); + double sizeWithRecords = systemSettingsDAO.getDatabaseSize(); assertTrue(sizeWithRecords > 0); assertTrue(sizeWithRecords >= emptySize); - IReportInstanceDAO reportInstanceDAO = new ReportInstanceDAO(); + IReportInstanceDAO reportInstanceDAO = new ReportInstanceDAO(); reportInstanceDAO.getReportInstance(1); systemSettingsDAO.resetDataBase(); From b305502eaa1670eb6e47e75ffa7ca80691acd9f6 Mon Sep 17 00:00:00 2001 From: patrykb0802 Date: Tue, 14 Apr 2026 09:29:29 +0200 Subject: [PATCH 4/7] #3249 Refactor DAO layer for modular architecture Rollback --- WebContent/resources/package-lock.json | 472 ++++++------------ build.gradle | 16 +- .../cache/DataSourcePointsCache.java | 92 +++- .../cache/UpdateDataSourcesPoints.java | 12 +- .../scada_lts/cache/ViewHierarchyCache.java | 4 +- .../scada_lts/utils/GetDataPointsUtils.java | 147 ++++-- 6 files changed, 321 insertions(+), 422 deletions(-) diff --git a/WebContent/resources/package-lock.json b/WebContent/resources/package-lock.json index 95a09e1fd7..2c0517e89c 100644 --- a/WebContent/resources/package-lock.json +++ b/WebContent/resources/package-lock.json @@ -1,367 +1,273 @@ { "name": "scada-lts-webapp", "version": "1.0.0", - "lockfileVersion": 3, + "lockfileVersion": 1, "requires": true, - "packages": { - "": { - "name": "scada-lts-webapp", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "axios": "0.21.4", - "bootstrap": "3.4.1", - "bootstrap3-dialog": "1.35.4", - "jquery": "3.6.1", - "jquery-ui-dist": "1.12.1", - "jquery.fancytree": "2.18.0", - "json-lint": "0.1.0", - "sockjs-client": "1.6.0", - "stompjs": "2.3.3", - "sweetalert2": "7.33.1", - "vue": "2.7.10", - "vue-axios": "2.1.5", - "vue-jsoneditor": "1.0.13" - } - }, - "node_modules/@babel/helper-string-parser": { + "dependencies": { + "@babel/helper-string-parser": { "version": "7.25.9", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", - "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", - "engines": { - "node": ">=6.9.0" - } + "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==" }, - "node_modules/@babel/helper-validator-identifier": { + "@babel/helper-validator-identifier": { "version": "7.25.9", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", - "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", - "engines": { - "node": ">=6.9.0" - } + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==" }, - "node_modules/@babel/parser": { + "@babel/parser": { "version": "7.26.5", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.5.tgz", "integrity": "sha512-SRJ4jYmXRqV1/Xc+TIVG84WjHBXKlxO9sHQnA2Pf12QQEAp1LOh6kDzNHXcUnbH1QI0FDoPPVOt+vyUDucxpaw==", - "dependencies": { + "requires": { "@babel/types": "^7.26.5" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" } }, - "node_modules/@babel/types": { + "@babel/types": { "version": "7.26.5", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.5.tgz", "integrity": "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg==", - "dependencies": { + "requires": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" - }, - "engines": { - "node": ">=6.9.0" } }, - "node_modules/@sphinxxxx/color-conversion": { + "@sphinxxxx/color-conversion": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/@sphinxxxx/color-conversion/-/color-conversion-2.2.2.tgz", "integrity": "sha512-XExJS3cLqgrmNBIP3bBw6+1oQ1ksGjFh0+oClDKFYpCCqx/hlqwWO5KO/S63fzUo67SxI9dMrF0y5T/Ey7h8Zw==" }, - "node_modules/@vue/compiler-sfc": { + "@vue/compiler-sfc": { "version": "2.7.10", "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-2.7.10.tgz", "integrity": "sha512-55Shns6WPxlYsz4WX7q9ZJBL77sKE1ZAYNYStLs6GbhIOMrNtjMvzcob6gu3cGlfpCR4bT7NXgyJ3tly2+Hx8Q==", - "dependencies": { + "requires": { "@babel/parser": "^7.18.4", "postcss": "^8.4.14", "source-map": "^0.6.1" } }, - "node_modules/ajv": { + "ajv": { "version": "5.5.2", "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", "integrity": "sha512-Ajr4IcMXq/2QmMkEmSvxqfLN5zGmJ92gHXAeOXq1OekoH2rfDNsgdDoL2f7QaRCy7G/E6TpxBVdRuNraMztGHw==", - "dependencies": { + "requires": { "co": "^4.6.0", "fast-deep-equal": "^1.0.0", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.3.0" } }, - "node_modules/axios": { + "axios": { "version": "0.21.4", "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", - "dependencies": { + "requires": { "follow-redirects": "^1.14.0" } }, - "node_modules/bootstrap": { + "bootstrap": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-3.4.1.tgz", - "integrity": "sha512-yN5oZVmRCwe5aKwzRj6736nSmKDX7pLYwsXiCj/EYmo16hODaBiT4En5btW/jhBF/seV+XMx3aYwukYC3A49DA==", - "deprecated": "This version of Bootstrap is no longer supported. Please upgrade to the latest version.", - "engines": { - "node": ">=6" - } + "integrity": "sha512-yN5oZVmRCwe5aKwzRj6736nSmKDX7pLYwsXiCj/EYmo16hODaBiT4En5btW/jhBF/seV+XMx3aYwukYC3A49DA==" }, - "node_modules/bootstrap3-dialog": { + "bootstrap3-dialog": { "version": "1.35.4", "resolved": "https://registry.npmjs.org/bootstrap3-dialog/-/bootstrap3-dialog-1.35.4.tgz", "integrity": "sha512-wHrJmqASIEsZWhHhfq9q0QhhGI8AnSh4tAAjUGK0MfMZjZ6vFl0niDZs5IwFDChCKKjcgFiFnXxLLoJ6nvyI2A==" }, - "node_modules/brace": { + "brace": { "version": "0.11.1", "resolved": "https://registry.npmjs.org/brace/-/brace-0.11.1.tgz", "integrity": "sha512-Fc8Ne62jJlKHiG/ajlonC4Sd66Pq68fFwK4ihJGNZpGqboc324SQk+lRvMzpPRuJOmfrJefdG8/7JdWX4bzJ2Q==" }, - "node_modules/bufferutil": { + "bufferutil": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz", "integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==", - "hasInstallScript": true, "optional": true, - "dependencies": { + "requires": { "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" } }, - "node_modules/co": { + "co": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==" }, - "node_modules/csstype": { + "csstype": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==" }, - "node_modules/d": { + "d": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz", "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==", - "optional": true, - "dependencies": { + "requires": { "es5-ext": "^0.10.64", "type": "^2.7.2" - }, - "engines": { - "node": ">=0.12" } }, - "node_modules/debug": { + "debug": { "version": "3.2.7", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dependencies": { + "requires": { "ms": "^2.1.1" } }, - "node_modules/drag-tracker": { + "drag-tracker": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/drag-tracker/-/drag-tracker-1.0.0.tgz", "integrity": "sha512-BSGDl37YXpW49dLMRfiDExxzD3yPOpLEBGx05Wed3z2sk2+Qd5dFvHCSVFTPsGTeltGBtkRB4qhLhSKv6tvBKw==" }, - "node_modules/es5-ext": { + "es5-ext": { "version": "0.10.64", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz", "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==", - "hasInstallScript": true, - "optional": true, - "dependencies": { + "requires": { "es6-iterator": "^2.0.3", "es6-symbol": "^3.1.3", "esniff": "^2.0.1", "next-tick": "^1.1.0" - }, - "engines": { - "node": ">=0.10" } }, - "node_modules/es6-iterator": { + "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", - "optional": true, - "dependencies": { + "requires": { "d": "1", "es5-ext": "^0.10.35", "es6-symbol": "^3.1.1" } }, - "node_modules/es6-symbol": { + "es6-symbol": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz", "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==", - "optional": true, - "dependencies": { + "requires": { "d": "^1.0.2", "ext": "^1.7.0" - }, - "engines": { - "node": ">=0.12" } }, - "node_modules/esniff": { + "esniff": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz", "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==", - "optional": true, - "dependencies": { + "requires": { "d": "^1.0.1", "es5-ext": "^0.10.62", "event-emitter": "^0.3.5", "type": "^2.7.2" - }, - "engines": { - "node": ">=0.10" } }, - "node_modules/event-emitter": { + "event-emitter": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", "integrity": "sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==", - "optional": true, - "dependencies": { + "requires": { "d": "1", "es5-ext": "~0.10.14" } }, - "node_modules/eventsource": { + "eventsource": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-1.1.2.tgz", - "integrity": "sha512-xAH3zWhgO2/3KIniEKYPr8plNSzlGINOUqYj0m0u7AB81iRw8b/3E73W6AuU+6klLbaSFmZnaETQ2lXPfAydrA==", - "engines": { - "node": ">=0.12.0" - } + "integrity": "sha512-xAH3zWhgO2/3KIniEKYPr8plNSzlGINOUqYj0m0u7AB81iRw8b/3E73W6AuU+6klLbaSFmZnaETQ2lXPfAydrA==" }, - "node_modules/ext": { + "ext": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", - "optional": true, - "dependencies": { + "requires": { "type": "^2.7.2" } }, - "node_modules/fast-deep-equal": { + "fast-deep-equal": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz", "integrity": "sha512-fueX787WZKCV0Is4/T2cyAdM4+x1S3MXXOAhavE1ys/W42SHAPacLTQhucja22QBYrfGw50M2sRiXPtTGv9Ymw==" }, - "node_modules/fast-json-stable-stringify": { + "fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" }, - "node_modules/faye-websocket": { + "faye-websocket": { "version": "0.11.4", "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", - "dependencies": { + "requires": { "websocket-driver": ">=0.5.1" - }, - "engines": { - "node": ">=0.8.0" } }, - "node_modules/follow-redirects": { + "follow-redirects": { "version": "1.15.9", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", - "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==" }, - "node_modules/http-parser-js": { + "http-parser-js": { "version": "0.5.9", "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.9.tgz", "integrity": "sha512-n1XsPy3rXVxlqxVioEWdC+0+M+SQw0DpJynwtOPo1X+ZlvdzTLtDBIJJlDQTnwZIFJrZSzSGmIOUdP8tu+SgLw==" }, - "node_modules/inherits": { + "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, - "node_modules/is-typedarray": { + "is-typedarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", "optional": true }, - "node_modules/javascript-natural-sort": { + "javascript-natural-sort": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz", "integrity": "sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==" }, - "node_modules/jmespath": { + "jmespath": { "version": "0.15.0", "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", - "integrity": "sha512-+kHj8HXArPfpPEKGLZ+kB5ONRTCiGQXo8RQYL0hH8t6pWXUBBK5KkkQmTNOwKK4LEsd0yTsgtjJVm4UBSZea4w==", - "engines": { - "node": ">= 0.6.0" - } + "integrity": "sha512-+kHj8HXArPfpPEKGLZ+kB5ONRTCiGQXo8RQYL0hH8t6pWXUBBK5KkkQmTNOwKK4LEsd0yTsgtjJVm4UBSZea4w==" }, - "node_modules/jquery": { + "jquery": { "version": "3.6.1", "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.1.tgz", "integrity": "sha512-opJeO4nCucVnsjiXOE+/PcCgYw9Gwpvs/a6B1LL/lQhwWwpbVEVYDZ1FokFr8PRc7ghYlrFPuyHuiiDNTQxmcw==" }, - "node_modules/jquery-ui-dist": { + "jquery-ui-dist": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/jquery-ui-dist/-/jquery-ui-dist-1.12.1.tgz", "integrity": "sha512-UnQQWIvxaP7s13FLx37WufEwDYLSXKpp9JHrqEYTP6GqQNM+RMVEwsJMoc163QlzEaAV5YVfWlgQU5FPjKBtSw==" }, - "node_modules/jquery.fancytree": { + "jquery.fancytree": { "version": "2.18.0", "resolved": "https://registry.npmjs.org/jquery.fancytree/-/jquery.fancytree-2.18.0.tgz", "integrity": "sha512-thZThwhAintFCB7wOBDh+Ibq9H+0hi6bnqsDDZfGW63tyXFijy7LZKNxZAuIoPXJyUfmfHHBpuZEYzyg6LjmkA==" }, - "node_modules/json-lint": { + "json-lint": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/json-lint/-/json-lint-0.1.0.tgz", - "integrity": "sha512-QoBMCAo3sFnAl2nvCcrt5NmjqMRejlghhMvZ0ykhgfNpp7ukp1te7dP6q2o4fkvl03t08t75njni+y6S7jiHLg==", - "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", - "engines": { - "node": ">=0.5" - } + "integrity": "sha512-QoBMCAo3sFnAl2nvCcrt5NmjqMRejlghhMvZ0ykhgfNpp7ukp1te7dP6q2o4fkvl03t08t75njni+y6S7jiHLg==" }, - "node_modules/json-schema-traverse": { + "json-schema-traverse": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz", "integrity": "sha512-4JD/Ivzg7PoW8NzdrBSr3UFwC9mHgvI7Z6z3QGBsSHgKaRTUDmyZAAKJo2UbG1kUVfS9WS8bi36N49U1xw43DA==" }, - "node_modules/json-source-map": { + "json-source-map": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/json-source-map/-/json-source-map-0.4.0.tgz", "integrity": "sha512-fVJ2mGl6pmYNmgseQch8X1ghdDntxeYgQQueypu9ZvttZwlSQuW4QztPBxgomRiRBidj5g7PtTW+7EqsTnEDNw==" }, - "node_modules/jsoneditor": { + "jsoneditor": { "version": "5.34.0", "resolved": "https://registry.npmjs.org/jsoneditor/-/jsoneditor-5.34.0.tgz", "integrity": "sha512-/F7L6oXuRkv2/FKFIL4NMWF0P+oVvSWLJPVEVP/7KGehBj6dtOp5FKdfLcNkIgbqzklXx/NDzHSXYlf64wqmuQ==", - "dependencies": { + "requires": { "ajv": "5.5.2", "brace": "0.11.1", "javascript-natural-sort": "0.7.1", @@ -372,305 +278,217 @@ "vanilla-picker": "2.8.0" } }, - "node_modules/mobius1-selectr": { + "mobius1-selectr": { "version": "2.4.10", "resolved": "https://registry.npmjs.org/mobius1-selectr/-/mobius1-selectr-2.4.10.tgz", "integrity": "sha512-U/pQ8jZwO7z3Mf9OYzJR6AKfleF5jSBIueKKxGMr/tgyLuTWgchgFyeaXpAIz3Cbp+7eIN1hw5D2gxc4cNnOkQ==" }, - "node_modules/ms": { + "ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, - "node_modules/nanoid": { + "nanoid": { "version": "3.3.8", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", - "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } + "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==" }, - "node_modules/next-tick": { + "next-tick": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", - "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==", - "optional": true + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==" }, - "node_modules/node-gyp-build": { + "node-gyp-build": { "version": "4.8.4", "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", - "optional": true, - "bin": { - "node-gyp-build": "bin.js", - "node-gyp-build-optional": "optional.js", - "node-gyp-build-test": "build-test.js" - } + "optional": true }, - "node_modules/picocolors": { + "picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, - "node_modules/picomodal": { + "picomodal": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/picomodal/-/picomodal-3.0.0.tgz", "integrity": "sha512-FoR3TDfuLlqUvcEeK5ifpKSVVns6B4BQvc8SDF6THVMuadya6LLtji0QgUDSStw0ZR2J7I6UGi5V2V23rnPWTw==" }, - "node_modules/postcss": { + "postcss": { "version": "8.4.49", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.49.tgz", "integrity": "sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "dependencies": { + "requires": { "nanoid": "^3.3.7", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" } }, - "node_modules/querystringify": { + "querystringify": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==" }, - "node_modules/requires-port": { + "requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==" }, - "node_modules/safe-buffer": { + "safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" }, - "node_modules/sockjs-client": { + "sockjs-client": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/sockjs-client/-/sockjs-client-1.6.0.tgz", "integrity": "sha512-qVHJlyfdHFht3eBFZdKEXKTlb7I4IV41xnVNo8yUKA1UHcPJwgW2SvTq9LhnjjCywSkSK7c/e4nghU0GOoMCRQ==", - "dependencies": { + "requires": { "debug": "^3.2.7", "eventsource": "^1.1.0", "faye-websocket": "^0.11.4", "inherits": "^2.0.4", "url-parse": "^1.5.10" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://tidelift.com/funding/github/npm/sockjs-client" } }, - "node_modules/source-map": { + "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "engines": { - "node": ">=0.10.0" - } + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" }, - "node_modules/source-map-js": { + "source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "engines": { - "node": ">=0.10.0" - } + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==" }, - "node_modules/stompjs": { + "stompjs": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/stompjs/-/stompjs-2.3.3.tgz", "integrity": "sha512-5l/Ogz0DTFW7TrpHF0LAETGqM/so8UxNJvYZjJKqcX31EVprSQgnGkO80tZctPC/lFBDUrSFiTG3xd0R27XAIA==", - "optionalDependencies": { - "websocket": "latest" - } - }, - "node_modules/stompjs/node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "optional": true, - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/stompjs/node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "optional": true - }, - "node_modules/stompjs/node_modules/websocket": { - "version": "1.0.35", - "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz", - "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==", - "optional": true, - "dependencies": { - "bufferutil": "^4.0.1", - "debug": "^2.2.0", - "es5-ext": "^0.10.63", - "typedarray-to-buffer": "^3.1.5", - "utf-8-validate": "^5.0.2", - "yaeti": "^0.0.6" + "requires": { + "websocket": "^1.0.35" }, - "engines": { - "node": ">=4.0.0" + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "optional": true, + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "optional": true + }, + "websocket": { + "version": "1.0.35", + "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz", + "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==", + "optional": true, + "requires": { + "bufferutil": "^4.0.1", + "debug": "^2.2.0", + "es5-ext": "^0.10.63", + "typedarray-to-buffer": "^3.1.5", + "utf-8-validate": "^5.0.2", + "yaeti": "^0.0.6" + } + } } }, - "node_modules/sweetalert2": { + "sweetalert2": { "version": "7.33.1", "resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-7.33.1.tgz", - "integrity": "sha512-69KYtyhtxejFG0HDb8aVhAwbpAWPSTZwaL5vxDHgojErD2KeFxTmRgmkbiLtMC8UdTFXRmvTPtZTF4459MUb7w==", - "engines": { - "node": ">=0.10.0" - } + "integrity": "sha512-69KYtyhtxejFG0HDb8aVhAwbpAWPSTZwaL5vxDHgojErD2KeFxTmRgmkbiLtMC8UdTFXRmvTPtZTF4459MUb7w==" }, - "node_modules/type": { + "type": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz", - "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==", - "optional": true + "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==" }, - "node_modules/typedarray-to-buffer": { + "typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", "optional": true, - "dependencies": { + "requires": { "is-typedarray": "^1.0.0" } }, - "node_modules/url-parse": { + "url-parse": { "version": "1.5.10", "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dependencies": { + "requires": { "querystringify": "^2.1.1", "requires-port": "^1.0.0" } }, - "node_modules/utf-8-validate": { + "utf-8-validate": { "version": "5.0.10", "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, "optional": true, - "dependencies": { + "requires": { "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" } }, - "node_modules/vanilla-picker": { + "vanilla-picker": { "version": "2.8.0", "resolved": "https://registry.npmjs.org/vanilla-picker/-/vanilla-picker-2.8.0.tgz", "integrity": "sha512-NPBxrtLi2LA2mEyRLW+Lyt7Eqtm0t0SmKqscE5RaugXLtJXXjPzy6r65fqLiQkhRc2WoLnmj2m/EnTWKN4hL+g==", - "dependencies": { + "requires": { "@sphinxxxx/color-conversion": "^2.2.1", "drag-tracker": "^1.0.0" } }, - "node_modules/vue": { + "vue": { "version": "2.7.10", "resolved": "https://registry.npmjs.org/vue/-/vue-2.7.10.tgz", "integrity": "sha512-HmFC70qarSHPXcKtW8U8fgIkF6JGvjEmDiVInTkKZP0gIlEPhlVlcJJLkdGIDiNkIeA2zJPQTWJUI4iWe+AVfg==", - "deprecated": "Vue 2 has reached EOL and is no longer actively maintained. See https://v2.vuejs.org/eol/ for more details.", - "dependencies": { + "requires": { "@vue/compiler-sfc": "2.7.10", "csstype": "^3.1.0" } }, - "node_modules/vue-axios": { + "vue-axios": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/vue-axios/-/vue-axios-2.1.5.tgz", - "integrity": "sha512-th5xVbInVoyIoe+qY+9GCflEVezxAvztD4xpFF39SRQYqpoKD2qkmX8yv08jJG9a2SgNOCjirjJGSwg/wTrbmA==", - "peerDependencies": { - "vue": ">= 1.0.0" - } + "integrity": "sha512-th5xVbInVoyIoe+qY+9GCflEVezxAvztD4xpFF39SRQYqpoKD2qkmX8yv08jJG9a2SgNOCjirjJGSwg/wTrbmA==" }, - "node_modules/vue-jsoneditor": { + "vue-jsoneditor": { "version": "1.0.13", "resolved": "https://registry.npmjs.org/vue-jsoneditor/-/vue-jsoneditor-1.0.13.tgz", "integrity": "sha512-dC4DBOmf9khDBzSauLLRI4AuoSha2A5L3q0ztR3tFDFGEYMJsk5G6ya2snyO3KkW8SyJKk+FcOfgAJtpXopa0A==", - "dependencies": { + "requires": { "jsoneditor": "^5.10.1", "vue": "^2.5.2" - }, - "engines": { - "node": ">= 4.0.0", - "npm": ">= 3.0.0" } }, - "node_modules/websocket-driver": { + "websocket-driver": { "version": "0.7.4", "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", - "dependencies": { + "requires": { "http-parser-js": ">=0.5.1", "safe-buffer": ">=5.1.0", "websocket-extensions": ">=0.1.1" - }, - "engines": { - "node": ">=0.8.0" } }, - "node_modules/websocket-extensions": { + "websocket-extensions": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", - "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", - "engines": { - "node": ">=0.8.0" - } + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==" }, - "node_modules/yaeti": { + "yaeti": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==", - "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", - "optional": true, - "engines": { - "node": ">=0.10.32" - } + "optional": true } } } diff --git a/build.gradle b/build.gradle index d3846ac578..1b311b710f 100644 --- a/build.gradle +++ b/build.gradle @@ -55,13 +55,7 @@ processTestResources { } war { - dependsOn( - ':scadalts-ui:copyNewUiJsSourceMap', - ':scadalts-ui:copyDataSourceJsSourceMap', - ':scadalts-ui:copyModernWatchListJsSourceMap', - ':scadalts-ui:copyPointHierarchyJsSourceMap', - ':scadalts-ui:copyViewsJsSourceMap' - ) + dependsOn(':scadalts-ui:copyNewUiImages') from 'WebContent' webInf { from 'webapp-resources/' @@ -70,13 +64,7 @@ war { } task warDev(type: War) { - dependsOn( - ':scadalts-ui:copyNewUiJsSourceMap', - ':scadalts-ui:copyDataSourceJsSourceMap', - ':scadalts-ui:copyModernWatchListJsSourceMap', - ':scadalts-ui:copyPointHierarchyJsSourceMap', - ':scadalts-ui:copyViewsJsSourceMap' - ) + dependsOn(':scadalts-ui:copyNewUiWithSourceMap') from 'WebContent' webInf { from 'webapp-resources/' diff --git a/src/org/scada_lts/cache/DataSourcePointsCache.java b/src/org/scada_lts/cache/DataSourcePointsCache.java index 2564460ca8..42d2ac4c17 100644 --- a/src/org/scada_lts/cache/DataSourcePointsCache.java +++ b/src/org/scada_lts/cache/DataSourcePointsCache.java @@ -4,12 +4,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.config.ScadaConfig; -import org.scada_lts.dao.IDataPointDAO; +import org.scada_lts.mango.service.DataPointService; import org.scada_lts.quartz.CronTriggerScheduler; import org.scada_lts.web.beans.ApplicationBeans; import java.io.IOException; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.stream.Collectors; public class DataSourcePointsCache implements IDataPointsCacheWhenStart { @@ -18,9 +21,10 @@ public class DataSourcePointsCache implements IDataPointsCacheWhenStart { private boolean cacheEnabled = false; private static DataSourcePointsCache instance = null; + private final DataPointService dataPointService = new DataPointService(); - private Map> dss = new TreeMap<>(); - + private Map> dss = new ConcurrentHashMap<>(); + private DataSourcePointsCache() { } @@ -33,19 +37,33 @@ public static DataSourcePointsCache getInstance() { } @Override + @Deprecated(since = "2.8.1") public List getDataPoints(Long dataSourceId) { LOG.info("I'm using a cache with datasources points"); if (cacheEnabled) { - return dss.get(dataSourceId); + return dss.get(dataSourceId != null ? dataSourceId.intValue() : -1); } else { throw new RuntimeException("Cache may work only when scada cacheEnabled"); } } + @Override + public List getDataPoints(int dataSourceId) { + + LOG.info("I'm using a cache with datasources points"); + + if (cacheEnabled) { + return dss.get(dataSourceId); + } else { + return dataPointService.getDataPoints(dataSourceId, null); + } + } + + @Deprecated(since = "2.8.1") public void setData(Map> dss) { - this.dss = dss; + this.dss = dss.entrySet().stream().collect(Collectors.toMap(a -> a.getKey().intValue(), Map.Entry::getValue)); } @Override @@ -69,24 +87,23 @@ public boolean isCacheEnabled() { @Override public void cacheInitialize() { - - IDataPointDAO dao = ApplicationBeans.getBean("dataPointDAO", IDataPointDAO.class); - - List dps = dao.getDataPoints(); + + List dps = dataPointService.getDataPoints(null, true); dss = composeCashData(dps); cacheEnabled = true; } - - public Map> composeCashData(List dps) { + + @Deprecated(since = "2.8.1") + public Map> composeCashDataOld(List dps) { - Map> dss = new TreeMap<>(); - if (dps != null && dps.size()>0) { + Map> dss = new ConcurrentHashMap<>(); + if (dps != null && !dps.isEmpty()) { for (DataPointVO dp : dps) { List cacheDs = dss.get((long)dp.getDataSourceId()); if (cacheDs==null) { - cacheDs = new ArrayList<>(); + cacheDs = new CopyOnWriteArrayList<>(); cacheDs.add(dp); dss.put((long) dp.getDataSourceId(), cacheDs); } else { @@ -97,6 +114,48 @@ public Map> composeCashData(List dps) { return dss; } + public Map> composeCashData(List dps) { + + Map> dss = new ConcurrentHashMap<>(); + if (dps != null && !dps.isEmpty()) { + for (DataPointVO dp : dps) { + List cacheDs = dss.get(dp.getDataSourceId()); + if (cacheDs==null) { + cacheDs = new CopyOnWriteArrayList<>(); + cacheDs.add(dp); + dss.put(dp.getDataSourceId(), cacheDs); + } else { + cacheDs.add(dp); + } + } + } + return dss; + } + + @Override + public DataPointVO getDataPoint(int dataPointId) { + if (cacheEnabled) { + return getPoints(this.dss).stream() + .filter(point -> point.getId() == dataPointId) + .findFirst() + .orElse(null); + } else { + return dataPointService.getDataPoint(dataPointId); + } + } + + @Override + public DataPointVO getDataPoint(String dataPointXid) { + if (cacheEnabled) { + return getPoints(this.dss).stream() + .filter(point -> point.getXid().equals(dataPointXid)) + .findFirst() + .orElse(null); + } else { + return dataPointService.getDataPoint(dataPointXid); + } + } + private void cronInitialize() throws java.io.IOException { if (LOG.isTraceEnabled()) { @@ -106,4 +165,9 @@ private void cronInitialize() throws java.io.IOException { ApplicationBeans.getBean("updateDataSourcesPointsScheduler", CronTriggerScheduler.class).schedule(cronExpression); } + private static List getPoints(Map> pointsBySource) { + return pointsBySource.values().stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } } diff --git a/src/org/scada_lts/cache/UpdateDataSourcesPoints.java b/src/org/scada_lts/cache/UpdateDataSourcesPoints.java index bc60ffbafc..af8ac6cd14 100644 --- a/src/org/scada_lts/cache/UpdateDataSourcesPoints.java +++ b/src/org/scada_lts/cache/UpdateDataSourcesPoints.java @@ -1,32 +1,22 @@ package org.scada_lts.cache; import com.serotonin.mango.util.LoggingUtils; -import com.serotonin.mango.vo.DataPointVO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.StatefulJob; -import org.scada_lts.dao.IDataPointDAO; -import org.scada_lts.web.beans.ApplicationBeans; - -import java.util.List; -import java.util.Map; public class UpdateDataSourcesPoints implements StatefulJob{ private static final Log LOG = LogFactory.getLog(UpdateDataSourcesPoints.class); - private final IDataPointDAO dao = ApplicationBeans.getDataPointDAOBean(); - @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { try { LOG.trace("UpdateEventDetectors"); - List dps = dao.getDataPoints(); - Map> dss = DataSourcePointsCache.getInstance().composeCashData(dps); - DataSourcePointsCache.getInstance().setData(dss); + DataSourcePointsCache.getInstance().cacheInitialize(); } catch (Exception ex) { LOG.error(LoggingUtils.causeInfo(ex), ex); } diff --git a/src/org/scada_lts/cache/ViewHierarchyCache.java b/src/org/scada_lts/cache/ViewHierarchyCache.java index 1ebcb4adb4..87c7cf62c1 100644 --- a/src/org/scada_lts/cache/ViewHierarchyCache.java +++ b/src/org/scada_lts/cache/ViewHierarchyCache.java @@ -44,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() { diff --git a/src/org/scada_lts/utils/GetDataPointsUtils.java b/src/org/scada_lts/utils/GetDataPointsUtils.java index 572f1d8f44..503b372943 100644 --- a/src/org/scada_lts/utils/GetDataPointsUtils.java +++ b/src/org/scada_lts/utils/GetDataPointsUtils.java @@ -5,6 +5,8 @@ import com.serotonin.db.KeyValuePair; import com.serotonin.mango.Common; import com.serotonin.mango.DataTypes; +import com.serotonin.mango.rt.dataSource.PointLocatorRT; +import com.serotonin.mango.rt.event.handlers.SetPointHandlerRT; import com.serotonin.mango.view.View; import com.serotonin.mango.view.component.CompoundChild; import com.serotonin.mango.view.component.CompoundComponent; @@ -13,19 +15,19 @@ import com.serotonin.mango.vo.DataPointExtendedNameComparator; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.User; +import com.serotonin.mango.vo.dataSource.AbstractPointLocatorVO; import com.serotonin.mango.vo.dataSource.meta.MetaPointLocatorVO; import com.serotonin.mango.vo.event.EventHandlerVO; import com.serotonin.mango.vo.link.PointLinkVO; import com.serotonin.mango.vo.permission.Permissions; -import com.serotonin.mango.vo.publish.PublishedPointVO; import com.serotonin.mango.vo.publish.PublisherVO; -import com.serotonin.mango.vo.report.ReportPointVO; import com.serotonin.mango.vo.report.ReportVO; import com.serotonin.mango.web.dwr.beans.DataPointBean; +import com.serotonin.web.dwr.DwrResponseI18n; +import com.serotonin.web.i18n.LocalizableMessage; import org.scada_lts.mango.service.DataPointService; import org.scada_lts.mango.service.EventService; import org.scada_lts.permissions.service.GetDataPointsWithAccess; -import org.springframework.dao.EmptyResultDataAccessException; import java.util.*; import java.util.function.Function; @@ -67,7 +69,7 @@ public static Set getDataPointsByView(User user, View view, DataP public static Set getTargetDataPointsByPointLinks(User user, List pointLinks, DataPointService dataPointService) { Set dataPoints = new HashSet<>(); for (PointLinkVO pointLinkVO : pointLinks) { - DataPointVO targetDataPoint = safeGetDataPoint(dataPointService, pointLinkVO.getTargetPointId()); + DataPointVO targetDataPoint = dataPointService.getDataPoint(pointLinkVO.getTargetPointId()); if(targetDataPoint != null && targetDataPoint.getPointLocator() != null && targetDataPoint.getPointLocator().isSettable() && GetDataPointsWithAccess.hasDataPointSetPermission(user, targetDataPoint)) @@ -79,7 +81,7 @@ public static Set getTargetDataPointsByPointLinks(User user, List public static Set getSourceDataPointsByPointLinks(User user, List pointLinks, DataPointService dataPointService) { Set dataPoints = new HashSet<>(); for (PointLinkVO pointLinkVO : pointLinks) { - DataPointVO sourceDataPoint = safeGetDataPoint(dataPointService, pointLinkVO.getSourcePointId()); + DataPointVO sourceDataPoint = dataPointService.getDataPoint(pointLinkVO.getSourcePointId()); if(sourceDataPoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, sourceDataPoint)) dataPoints.add(new DataPointBean(sourceDataPoint)); } @@ -97,15 +99,8 @@ public static Set getDataPointsByEventHandlers() { } public static List getDataPointsByContext(MetaPointLocatorVO locator, User user, DataPointService dataPointService) { - return getDataPointsByContext(locator, user, dataPointService, DataPointBean::new); - } - - public static List getDataPointsByContext(MetaPointLocatorVO locator, User user, DataPointService dataPointService, Function converter) { - return dataPointService.getDataPoints(locator.getContext().stream() - .map(IntValuePair::getKey) - .collect(Collectors.toSet()), user).stream() - .map(converter) - .collect(Collectors.toList()); + List context = locator.getContext(); + return getPointsByContext(context, user, dataPointService).stream().map(DataPointBean::new).collect(Collectors.toList()); } public static List getDataPointsByContext(User user, List allPoints, @@ -116,7 +111,7 @@ public static List getDataPointsByContext(User user, List a)); + contextPoints.addAll(getPointsByContext(pointLocatorVO.getContext(), user, dataPointService)); } } if(comparator != null) { @@ -176,38 +171,21 @@ private static Set getDataPointIdsByViewComponents(View view) { return ids; } - private static DataPointVO safeGetDataPoint(DataPointService dataPointService, int pointId) { - if(pointId < 1) { - return null; - } - try { - return dataPointService.getDataPoint(pointId); - } catch (EmptyResultDataAccessException ex) { - return null; - } - } - private static Set getDataPointsByEventHandlers(List eventHandlers, DataPointService dataPointService, User user) { Set dataPoints = new HashSet<>(); for (EventHandlerVO eventHandler : eventHandlers) { - if(eventHandler.getHandlerType() == EventHandlerVO.TYPE_SET_POINT) { + if(eventHandler.createRuntime() instanceof SetPointHandlerRT) { DataPointVO targetPoint = dataPointService.getDataPoint(eventHandler.getTargetPointId()); + DataPointVO activePoint = dataPointService.getDataPoint(eventHandler.getActivePointId()); + DataPointVO inactivePoint = dataPointService.getDataPoint(eventHandler.getInactivePointId()); if (targetPoint != null && GetDataPointsWithAccess.hasDataPointSetPermission(user, targetPoint)) { dataPoints.add(targetPoint); } - - if (eventHandler.getActiveAction() == EventHandlerVO.SET_ACTION_POINT_VALUE) { - DataPointVO activePoint = dataPointService.getDataPoint(eventHandler.getActivePointId()); - if (activePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, activePoint)) { - dataPoints.add(activePoint); - } + if (activePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, activePoint)) { + dataPoints.add(activePoint); } - - if (eventHandler.getInactiveAction() == EventHandlerVO.SET_ACTION_POINT_VALUE) { - DataPointVO inactivePoint = dataPointService.getDataPoint(eventHandler.getInactivePointId()); - if (inactivePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, inactivePoint)) { - dataPoints.add(inactivePoint); - } + if (inactivePoint != null && GetDataPointsWithAccess.hasDataPointReadPermission(user, inactivePoint)) { + dataPoints.add(inactivePoint); } } } @@ -232,8 +210,11 @@ private static List getDataPointsByView(User user, View view, Function List getDataPointsByReport(User user, ReportVO report, Function converter, DataPointService dataPointService) { - Set ids = report.getPoints().stream().map(ReportPointVO::getPointId).collect(Collectors.toSet()); - return dataPointService.getDataPoints(ids).stream() + List context = report.getPoints() + .stream() + .map(reportPointVO -> new IntValuePair(reportPointVO.getPointId(), "")) + .collect(Collectors.toList()); + return getPointsByContext(context, user, dataPointService).stream() .filter(point -> GetDataPointsWithAccess.hasDataPointReadPermission(user, point)) .map(converter) .collect(Collectors.toList()); @@ -241,11 +222,7 @@ private static List getDataPointsByReport(User user, ReportVO report, Fun private static List getDataPointsByScript(User user, ContextualizedScriptVO contextualizedScriptVO, Function converter, DataPointService dataPointService) { - Set ids = new HashSet<>(); - for(IntValuePair pair : contextualizedScriptVO.getPointsOnContext()) { - ids.add(pair.getKey()); - } - return dataPointService.getDataPoints(ids).stream() + return getPointsByContext(contextualizedScriptVO.getPointsOnContext(), user, dataPointService).stream() .filter(point -> GetDataPointsWithAccess.hasDataPointReadPermission(user, point)) .map(converter) .collect(Collectors.toList()); @@ -262,15 +239,11 @@ private static List getDataPointsByDataSource(User user, int dataSourceId } private static List getDataPointsByPublishers(User user, List> publishers, Function converter, DataPointService dataPointService) { - Set ids = new HashSet<>(); - - for (PublisherVO publisher: publishers) { - List points = (List) publisher.getPoints(); - for(PublishedPointVO point: points) { - ids.add(point.getDataPointId()); - } - } - return dataPointService.getDataPoints(ids).stream() + List context = publishers.stream() + .flatMap(a -> a.getPoints().stream()) + .map(a -> new IntValuePair(a.getDataPointId(), "")) + .collect(Collectors.toList()); + return getPointsByContext(context, user, dataPointService).stream() .filter(dp -> dp.getPointLocator().getDataTypeId() != DataTypes.IMAGE) .filter(point -> GetDataPointsWithAccess.hasDataPointReadPermission(user, point)) .sorted(DataPointExtendedNameComparator.instance) @@ -295,4 +268,68 @@ private static int convertToInt(String value) { return 0; } } + + private static List getPointsByContext(List context, User user, DataPointService dataPointService) { + Set ids = context.stream() + .map(IntValuePair::getKey) + .collect(Collectors.toSet()); + + List points = dataPointService.getDataPoints(ids, user); + List notExist = findNotExists(context, points); + points.addAll(notExist); + return points; + } + + private static List findNotExists(List context, List points) { + Set fromDatabaseIds = points.stream() + .map(DataPointVO::getId) + .collect(Collectors.toSet()); + List notExist = new ArrayList<>(); + for(IntValuePair id: context) { + if(!fromDatabaseIds.contains(id.getKey())) { + DataPointVO dataPoint = new DataPointVO(-1,-1,-1); + dataPoint.setId(id.getKey()); + dataPoint.setName("Unknown"); + dataPoint.setXid("Unknown"); + dataPoint.setPointLocator(new AbstractPointLocatorVO() { + @Override + public int getDataTypeId() { + return 0; + } + + @Override + public LocalizableMessage getConfigurationDescription() { + return super.getDataTypeMessage(); + } + + @Override + public boolean isSettable() { + return false; + } + + @Override + public PointLocatorRT createRuntime() { + return null; + } + + @Override + public void validate(DwrResponseI18n response) { + + } + + @Override + public void addProperties(List list) { + + } + + @Override + public void addPropertyChanges(List list, Object o) { + + } + }); + notExist.add(dataPoint); + } + } + return notExist; + } } From e666e400daee805a55e64c89bf96b7ab8b383b67 Mon Sep 17 00:00:00 2001 From: patrykb0802 Date: Tue, 14 Apr 2026 12:10:28 +0200 Subject: [PATCH 5/7] #3249 Refactor DAO layer for modular architecture --- WebContent/WEB-INF/applicationContext.xml | 1 - .../serotonin/mango/db/DatabaseAccess.java | 161 ++++++++++++++- .../mango/web/dwr/DataSourceEditDwr.java | 2 +- .../mango/web/dwr/DataSourceListDwr.java | 4 +- .../mango/web/dwr/SystemSettingsDwr.java | 59 +++--- .../scada_lts/dao/IPointEventDetectorDAO.java | 1 - src/org/scada_lts/dao/ISystemSettingsDAO.java | 10 +- src/org/scada_lts/dao/IViewDAO.java | 26 +-- .../scada_lts/dao/PointEventDetectorDAO.java | 1 - src/org/scada_lts/dao/PointLinkDAO.java | 40 ++-- src/org/scada_lts/dao/ViewDAO.java | 12 +- .../cache/PointEventDetectorDaoWithCache.java | 46 ++--- .../scada_lts/dao/cache/ViewDaoWithCache.java | 23 --- .../mango/service/DataPointService.java | 2 +- .../mango/service/PointValueService.java | 8 +- .../mango/service/SystemSettingsService.java | 20 +- .../migration/dao/OnlyMigrationViewDAO.java | 184 ++++++++++++++---- .../service/ViewHierarchyService.java | 2 + .../scada_lts/web/beans/ApplicationBeans.java | 3 +- .../web/mvc/api/DataPointApiService.java | 6 +- .../RuntimeManagerCreateDataPointRtTest.java | 2 +- .../rt/dataImage/PointValueCacheTest.java | 3 +- .../config/ConfigDataPointRtTest.java | 2 +- .../AbstractStartStopDataPointsUtilsTest.java | 2 +- test/utils/ScriptTestUtils.java | 3 +- test/utils/mock/PowerMockUtils.java | 3 +- 26 files changed, 409 insertions(+), 217 deletions(-) diff --git a/WebContent/WEB-INF/applicationContext.xml b/WebContent/WEB-INF/applicationContext.xml index 94b1263c54..b5f40c369c 100644 --- a/WebContent/WEB-INF/applicationContext.xml +++ b/WebContent/WEB-INF/applicationContext.xml @@ -399,7 +399,6 @@ - diff --git a/src/com/serotonin/mango/db/DatabaseAccess.java b/src/com/serotonin/mango/db/DatabaseAccess.java index b81dc595a3..e3299043d3 100644 --- a/src/com/serotonin/mango/db/DatabaseAccess.java +++ b/src/com/serotonin/mango/db/DatabaseAccess.java @@ -13,6 +13,8 @@ */ package com.serotonin.mango.db; +import br.org.scadabr.db.configuration.ConfigurationDB; + import java.io.File; import java.io.InputStream; import java.io.OutputStream; @@ -49,18 +51,113 @@ 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 @@ -79,6 +176,21 @@ public InputStream getBinaryStream(ResultSet rs, String columnLabel) throws SQLE 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 @@ -90,12 +202,32 @@ DatabaseAccess getImpl() { 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() { @@ -108,16 +240,20 @@ public static DatabaseType from(String dbType) { } String normalized = dbType.trim().toLowerCase(); - if ("postgresql".equals(normalized) || "pgsql".equals(normalized) || "pg".equals(normalized)) { - return POSTGRES; - } - if ("mssqlserver".equals(normalized) || "mssql".equals(normalized)) { - return MSSQL; - } - if ("mysqlserver".equals(normalized) || "mysql".equals(normalized)) { - return MYSQL; + 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()); } - return DatabaseType.valueOf(normalized.toUpperCase()); } public InputStream getBinaryStream(ResultSet rs, int columnIndex) throws SQLException { @@ -133,6 +269,13 @@ public int getBinarySqlType() { } 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() { diff --git a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java index fa3361650a..7e2ca59e7a 100644 --- a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java @@ -397,7 +397,7 @@ public DwrResponseI18n togglePoint(int dataPointId) { User user = Common.getUser(); DataPointService dataPointService = new DataPointService(); DataPointVO dataPoint = dataPointService.getDataPoint(dataPointId); - DwrResponseI18n response = super.toggleDataPointInternal(dataPoint); + DwrResponseI18n response = super.toggleDataPoint(dataPoint); response.addData("points", GetDataPointsUtils.getDataPointsByDataSource(user, dataPoint.getDataSourceId(), dataPointService)); return response; } diff --git a/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java index 2382960bb5..01ca5b5a2c 100644 --- a/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataSourceListDwr.java @@ -123,10 +123,10 @@ public int deleteDataSource(int dataSourceId) { public DwrResponseI18n toggleDataPoint(int dataPointId) { DataPointVO dataPoint = new DataPointDao().getDataPoint(dataPointId); - return toggleDataPointInternal(dataPoint); + return toggleDataPoint(dataPoint); } - protected DwrResponseI18n toggleDataPointInternal(DataPointVO dataPoint) { + public DwrResponseI18n toggleDataPoint(DataPointVO dataPoint) { Permissions.ensureDataSourcePermission(Common.getUser(), dataPoint.getDataSourceId()); diff --git a/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java b/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java index 542f6f17a6..a43f2dbc90 100644 --- a/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java +++ b/src/com/serotonin/mango/web/dwr/SystemSettingsDwr.java @@ -231,33 +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)); - - String dbType = checkTypeDB(); - if (dbType.equalsIgnoreCase("mysql") || dbType.equalsIgnoreCase("postgres")) { - double size = ApplicationBeans.getSystemSettingsDaoBean().getDatabaseSize(); - if (size >= 0) { - 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); - } else { - data.put("databaseSize", "(" + getMessage("common.unknown") + ")"); + + + 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. @@ -565,16 +571,21 @@ public void useOracle11gDB() { } - public String checkTypeDB() { + private DatabaseAccess.DatabaseType resolveDatabaseType() { try { DatabaseAccess databaseAccess = DatabaseAccess.getDatabaseAccess(); if (databaseAccess != null) { - return databaseAccess.getTypeKey(); + return databaseAccess.getType(); } } catch (Exception ignore) { // fallback to env.properties } - return Common.getEnvironmentProfile().getString("db.type", "mysql"); + return DatabaseAccess.DatabaseType.from(Common.getEnvironmentProfile().getString("db.type", "mysql")); + } + + + public String checkTypeDB() { + return resolveDatabaseType().getKey(); } diff --git a/src/org/scada_lts/dao/IPointEventDetectorDAO.java b/src/org/scada_lts/dao/IPointEventDetectorDAO.java index b03c0d712e..c641011285 100644 --- a/src/org/scada_lts/dao/IPointEventDetectorDAO.java +++ b/src/org/scada_lts/dao/IPointEventDetectorDAO.java @@ -8,7 +8,6 @@ public interface IPointEventDetectorDAO { default void init() {}; List getPointEventDetectors(DataPointVO dataPoint); - List getPointEventDetectors(long limit, int offset); boolean isEventDetectorXidUnique(int dataPointId, String xid, int excludeId); int insert(int dataPointId, PointEventDetectorVO pointEventDetector); void update(int dataPointId, PointEventDetectorVO pointEventDetector); diff --git a/src/org/scada_lts/dao/ISystemSettingsDAO.java b/src/org/scada_lts/dao/ISystemSettingsDAO.java index 8827c92218..52c641fdca 100644 --- a/src/org/scada_lts/dao/ISystemSettingsDAO.java +++ b/src/org/scada_lts/dao/ISystemSettingsDAO.java @@ -1,11 +1,11 @@ package org.scada_lts.dao; public interface ISystemSettingsDAO { - public abstract void setValue(java.lang.String arg0, java.lang.String arg1); - public abstract void setIntValue(java.lang.String arg0, int arg1); - public abstract void setBooleanValue(java.lang.String arg0, boolean arg1); - public abstract void removeValue(java.lang.String arg0); - public abstract java.lang.String getDatabaseSchemaVersion(java.lang.String arg0, java.lang.String arg1); + public abstract void setValue(java.lang.String key, java.lang.String value); + public abstract void setIntValue(java.lang.String key, int value); + public abstract void setBooleanValue(java.lang.String key, boolean value); + public abstract void removeValue(java.lang.String key); + public abstract java.lang.String getDatabaseSchemaVersion(java.lang.String key, java.lang.String defaultValue); public abstract void resetDataBase(); public abstract double getDatabaseSize(); } diff --git a/src/org/scada_lts/dao/IViewDAO.java b/src/org/scada_lts/dao/IViewDAO.java index 228344b9ac..3269717030 100644 --- a/src/org/scada_lts/dao/IViewDAO.java +++ b/src/org/scada_lts/dao/IViewDAO.java @@ -12,33 +12,9 @@ public interface IViewDAO extends ScadaRepository { default void init() {} - List findAll(); - - List filtered(String filter, String order, Object[] argsFilter, long limit); - - void update(View entity); - - void delete(View entity); - - void deleteViewForUser(int viewId); - - void deleteViewForUser(int viewId, int userId); - - void batchUpdateInfoUsers(View view); - - List findIdentifiers(); - - List findBaseIdentifiers(); - - View save(View entity); - - void delete(Integer id); - - View findById(Integer id); - View findByName(String name); - View findByXid(String xid); + void deleteViewForUser(int viewId, int userId); List selectViewIdentifiersWithAccess(int userId, int profileId); diff --git a/src/org/scada_lts/dao/PointEventDetectorDAO.java b/src/org/scada_lts/dao/PointEventDetectorDAO.java index 2efe232389..dacc27b457 100644 --- a/src/org/scada_lts/dao/PointEventDetectorDAO.java +++ b/src/org/scada_lts/dao/PointEventDetectorDAO.java @@ -475,7 +475,6 @@ public PointEventDetectorVO getPointEventDetector(String pointEventDetectorXid, } } - @Override public List getPointEventDetectors(long limit, int offset) { if (LOG.isTraceEnabled()) { LOG.trace("getPointEventDetector(long limit, int offset) limit:" +limit + ", offset:" + offset); diff --git a/src/org/scada_lts/dao/PointLinkDAO.java b/src/org/scada_lts/dao/PointLinkDAO.java index 3a6e3874ae..b7038c0e3a 100644 --- a/src/org/scada_lts/dao/PointLinkDAO.java +++ b/src/org/scada_lts/dao/PointLinkDAO.java @@ -21,14 +21,17 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; +import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.List; /** @@ -71,7 +74,7 @@ public class PointLinkDAO implements IPointLinkDAO { + COLUMN_NAME_EVENT_TYPE + ", " + COLUMN_NAME_DISABLED + ") " - + "values (?,?,?,?,?,?) RETURNING id"; + + "values (?,?,?,?,?,?) "; private static final String POINT_LINK_UPDATE = "" + "update pointLinks set " @@ -178,18 +181,25 @@ public int insert(final PointLinkVO pointLink) { LOG.trace("insertPointLink(PointLinkVO pointLink) pointLink:" + pointLink.toString()); } - return DAO.getInstance().getJdbcTemp().queryForObject( - POINT_LINK_INSERT, - new Object[]{ - pointLink.getXid(), - pointLink.getSourcePointId(), - pointLink.getTargetPointId(), - pointLink.getScript(), - pointLink.getEvent(), - DAO.boolToChar(pointLink.isDisabled()) - }, - Integer.class - ); + KeyHolder keyHolder = new GeneratedKeyHolder(); + + DAO.getInstance().getJdbcTemp().update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(POINT_LINK_INSERT, Statement.RETURN_GENERATED_KEYS); + new ArgumentPreparedStatementSetter(new Object[] { + pointLink.getXid(), + pointLink.getSourcePointId(), + pointLink.getTargetPointId(), + pointLink.getScript(), + pointLink.getEvent(), + DAO.boolToChar(pointLink.isDisabled())} + ).setValues(ps); + return ps; + } + }, keyHolder); + + return keyHolder.getKey().intValue(); } @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) diff --git a/src/org/scada_lts/dao/ViewDAO.java b/src/org/scada_lts/dao/ViewDAO.java index cac81c7a7f..33e82d544f 100644 --- a/src/org/scada_lts/dao/ViewDAO.java +++ b/src/org/scada_lts/dao/ViewDAO.java @@ -486,14 +486,18 @@ public View findById(Integer id) { } @Override - public View findByName(String name) { - return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT + " where " + VIEW_FILTER_BASE_ON_NAME, new Object[] {name}, new ViewRowMapper()); + public View findByXid(String xid) { + try { + return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT+ " where " + VIEW_FILTER_BASE_ON_XID, new Object[]{xid}, new ViewRowMapper()); + } catch (EmptyResultDataAccessException e) { + return null; + } } @Override - public View findByXid(String xid) { + public View findByName(String name) { try { - return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT+ " where " + VIEW_FILTER_BASE_ON_XID, new Object[]{xid}, new ViewRowMapper()); + return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT + " where " + VIEW_FILTER_BASE_ON_NAME, new Object[]{name}, new ViewRowMapper()); } catch (EmptyResultDataAccessException e) { return null; } diff --git a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java index 73f6f1c8f6..0be887d61a 100644 --- a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java @@ -16,29 +16,29 @@ public class PointEventDetectorDaoWithCache implements IPointEventDetectorDAO { - private static final Log LOG = LogFactory.getLog(PointEventDetectorDaoWithCache.class); - private final PointEventDetectorCacheable pointEventDetectorCache; - private final IPointEventDetectorDAO pointEventDetectorDAO; - public PointEventDetectorDaoWithCache(PointEventDetectorCacheable pointEventDetectorCache, - IPointEventDetectorDAO pointEventDetectorDAO) { + public PointEventDetectorDaoWithCache(PointEventDetectorCacheable pointEventDetectorCache) { this.pointEventDetectorCache = pointEventDetectorCache; - this.pointEventDetectorDAO = pointEventDetectorDAO; } @Override public void init() { - IDataPointDAO dao = ApplicationBeans.getDataPointDAOBean(); - List dataPoints = dao.getDataPoints(); - Map> pointEventDetectors = loadPointEventDetectors(Integer.MAX_VALUE, 0) + IDataPointDAO dataPointDAO = ApplicationBeans.getDataPointDAOBean(); + PointEventDetectorDAO rawPointEventDetectorDAO = + ApplicationBeans.getBean("pointEventDetectorDAO", PointEventDetectorDAO.class); + + List dataPoints = dataPointDAO.getDataPoints(); + Map> pointEventDetectors = rawPointEventDetectorDAO + .getPointEventDetectors(Integer.MAX_VALUE, 0) .stream() .collect(Collectors.groupingBy(a -> a.njbGetDataPoint().getId())); - for(DataPointVO dataPoint: dataPoints) { + + for (DataPointVO dataPoint : dataPoints) { List detectors = pointEventDetectors.get(dataPoint.getId()); - if(detectors != null && !detectors.isEmpty()) { + if (detectors != null && !detectors.isEmpty()) { dataPoint.setEventDetectors(detectors); - for(PointEventDetectorVO detector: detectors) { + for (PointEventDetectorVO detector : detectors) { detector.njbSetDataPoint(dataPoint); } } @@ -103,26 +103,4 @@ public PointEventDetectorVO getPointEventDetector(String pointEventDetectorXid, public int getDataPointId(int pointEventDetectorId) { return pointEventDetectorCache.selectDataPointIdByEventDetectorId(pointEventDetectorId); } - - @Override - public List getPointEventDetectors(long limit, int offset) { - if (LOG.isTraceEnabled()) { - LOG.trace("getPointEventDetector(long limit, int offset) limit:" + limit + ", offset:" + offset); - } - - try { - return loadPointEventDetectors(limit, offset); - } catch (Exception ex) { - LOG.warn(ex.getMessage(), ex); - return Collections.emptyList(); - } - } - - private List loadPointEventDetectors(long limit, int offset) { - if (limit <= 0 || offset < 0) { - return Collections.emptyList(); - } - - return pointEventDetectorDAO.getPointEventDetectors(limit, offset); - } } diff --git a/src/org/scada_lts/dao/cache/ViewDaoWithCache.java b/src/org/scada_lts/dao/cache/ViewDaoWithCache.java index 57ff753956..a8a95e50a3 100644 --- a/src/org/scada_lts/dao/cache/ViewDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/ViewDaoWithCache.java @@ -34,11 +34,6 @@ public void init() { } } - @Override - public List filtered(String filter, String order, Object[] argsFilter, long limit) { - return ApplicationBeans.getBean("viewDAO", IViewDAO.class).filtered(filter, order, argsFilter, limit); - } - @Override public View save(View view) { return viewCache.save(view); @@ -49,13 +44,6 @@ public void update(View view) { viewCache.update(view); } - @Override - public void delete(View entity) { - if (entity != null) { - delete(entity.getId()); - } - } - @Override public void delete(Integer id) { viewCache.delete(id); @@ -75,11 +63,6 @@ public List findAll() { return views; } - @Override - public void batchUpdateInfoUsers(View view) { - ApplicationBeans.getBean("viewDAO", IViewDAO.class).batchUpdateInfoUsers(view); - } - @Override public List selectViewPermissions(int userId) { return viewCache.selectViewPermissions(userId); @@ -113,7 +96,6 @@ public View findById(Integer viewId) { return viewCache.findById(viewId); } - @Override public View findByName(String name) { if(name == null) { return null; @@ -164,11 +146,6 @@ public List selectViewWithAccess(int userId, int profileId) { .collect(Collectors.toList()); } - @Override - public void deleteViewForUser(int viewId) { - ApplicationBeans.getBean("viewDAO", IViewDAO.class).deleteViewForUser(viewId); - } - @Override public void deleteViewForUser(int viewId, int userId) { viewCache.deleteViewForUser(viewId, userId); diff --git a/src/org/scada_lts/mango/service/DataPointService.java b/src/org/scada_lts/mango/service/DataPointService.java index 38a936e17d..6193405380 100644 --- a/src/org/scada_lts/mango/service/DataPointService.java +++ b/src/org/scada_lts/mango/service/DataPointService.java @@ -88,7 +88,7 @@ public class DataPointService implements MangoDataPoint { private final IDataPointUserDAO dataPointUserDAO ; - private static final IPointValueDAO pointValueDAO = ApplicationBeans.getPointValueDAOBean(); + private static final IPointValueDAO pointValueDAO = ApplicationBeans.getPointValueDaoBean(); private final IWatchListDAO watchListDAO; diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index 7694be1127..08f2f728f8 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -75,14 +75,14 @@ public class PointValueService implements MangoPointValues { private static List UNSAVED_POINT_VALUES = new ArrayList(); private static final int POINT_VALUE_INSERT_VALUES_COUNT = 4; - private IPointValueDAO pointValueDAO; + private final IPointValueDAO pointValueDAO; private DataPointService dataPointService = new DataPointService(); private DataSourceService dataSourceService = new DataSourceService(); private static final Log LOG = LogFactory.getLog(PointValueService.class); public PointValueService() { - pointValueDAO = ApplicationBeans.getPointValueDAOBean(); + pointValueDAO = ApplicationBeans.getPointValueDaoBean(); } /** @@ -504,7 +504,7 @@ static class BatchWriteBehind extends AbstractBeforeAfterWorkItem { "BatchWriteBehind.ENTRIES_MONITOR", null); private static final IntegerMonitor INSTANCES_MONITOR = new IntegerMonitor( "BatchWriteBehind.INSTANCES_MONITOR", null); - private static IPointValueDAO pointValueDAO; + private final IPointValueDAO pointValueDAO; static { @@ -518,7 +518,7 @@ static class BatchWriteBehind extends AbstractBeforeAfterWorkItem { } public BatchWriteBehind() { - pointValueDAO = ApplicationBeans.getPointValueDAOBean(); + this.pointValueDAO = ApplicationBeans.getPointValueDaoBean(); } static void add(BatchWriteBehindEntry e) { diff --git a/src/org/scada_lts/mango/service/SystemSettingsService.java b/src/org/scada_lts/mango/service/SystemSettingsService.java index 0bb75c1a75..324c1c369e 100644 --- a/src/org/scada_lts/mango/service/SystemSettingsService.java +++ b/src/org/scada_lts/mango/service/SystemSettingsService.java @@ -1,6 +1,5 @@ package org.scada_lts.mango.service; -import br.org.scadabr.db.configuration.ConfigurationDB; import com.fasterxml.jackson.databind.ObjectMapper; import com.serotonin.mango.Common; import com.serotonin.mango.db.DatabaseAccess; @@ -271,24 +270,7 @@ public String getDatabaseType() { } public void setDatabaseType(String databaseType) { - String dbKey = DatabaseType.from(databaseType).getKey(); - switch (dbKey) { - case "mysql": - ConfigurationDB.useMysqlDB(); - break; - case "postgres": - ConfigurationDB.usePostgresDB(); - break; - case "mssql": - ConfigurationDB.useMssqlDB(); - break; - case "oracle11g": - ConfigurationDB.useOracle11gDB(); - break; - default: - ConfigurationDB.useDerbyDB(); - break; - } + DatabaseType.from(databaseType).applyConfiguration(); } public Map getDatabaseSize() { diff --git a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationViewDAO.java b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationViewDAO.java index fd66a30277..24e565e08b 100644 --- a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationViewDAO.java +++ b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationViewDAO.java @@ -25,16 +25,23 @@ import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.*; import org.scada_lts.dao.model.BaseObjectIdentifier; +import org.scada_lts.dao.model.BaseObjectIdentifierRowMapper; import org.scada_lts.dao.model.IdName; import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.dao.model.ScadaObjectIdentifierRowMapper; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.sql.*; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -93,7 +100,23 @@ public final class OnlyMigrationViewDAO implements IViewDAO { + COLUMN_NAME_NAME+" " + "from " + "mangoViews"; - + + private static final String VIEW_BASE_IDENTIFIER_SELECT = "" + +"select " + + COLUMN_NAME_ID+", " + + COLUMN_NAME_XID+" " + + "from " + + "mangoViews"; + + private static final String VIEW_FILTER_BASE_ON_ID="" + +COLUMN_NAME_ID+"=?"; + + private static final String VIEW_FILTER_BASE_ON_XID="" + +COLUMN_NAME_XID+"=?"; + + private static final String VIEW_FILTER_BASE_ON_NAME="" + +COLUMN_NAME_NAME+"=?"; + private static final String VIEW_UPDATE = "" +"update mangoViews set " + COLUMN_NAME_XID+"=?, " @@ -106,6 +129,18 @@ public final class OnlyMigrationViewDAO implements IViewDAO { + COLUMN_NAME_MODIFICATION_TIME+"=CURRENT_TIMESTAMP " + "where " + COLUMN_NAME_ID+"=?"; + + private static final String VIEW_INSERT = "" + +"insert mangoViews (" + + COLUMN_NAME_XID+", " + + COLUMN_NAME_NAME+", " + + COLUMN_NAME_BACKGROUND+", " + + COLUMN_NAME_USER_ID+", " + + COLUMN_NAME_ANONYMOUS_ACCESS+", " + + COLUMN_NAME_DATA+"," + + COLUMN_NAME_HEIGHT+", " + + COLUMN_NAME_WIDTH+") " + + "values (?,?,?,?,?,?,?,?)"; private static final String VIEW_DELETE = "" +"delete " @@ -125,6 +160,16 @@ public final class OnlyMigrationViewDAO implements IViewDAO { + "where " + COLUMN_NAME_MVU_USER_ID+"=?"; + private static final String VIEW_USER_BASE_ON_VIEW_ID = "" + +"select " + + COLUMN_NAME_MVU_VIEW_ID+", " + + COLUMN_NAME_MVU_USER_ID+", " + + COLUMN_NAME_MVU_ACCESS_TYPE+" " + + "from " + + "mangoViewUsers " + + "where " + + COLUMN_NAME_MVU_VIEW_ID+"=?"; + public static final String VIEW_FILTERED_BASE_ON_USER_ID_USERS_PROFILE_ID = "" + COLUMN_NAME_USER_ID+"=? or " + "id in (select "+COLUMN_NAME_MVU_VIEW_ID+" from mangoViewUsers where "+COLUMN_NAME_MVU_USER_ID+"=? and "+COLUMN_NAME_MVU_ACCESS_TYPE+">?) or " @@ -172,6 +217,17 @@ public final class OnlyMigrationViewDAO implements IViewDAO { + "where " + COLUMN_NAME_UP_USER_PRFILE_ID+ "=?"; + private static final String SHARE_USERS_BY_USERS_PROFILE_AND_VIEW_ID = "" + + "select userProfile.id, userProfile.name, permission " + + "from usersProfiles as userProfile " + + "inner join viewUsersProfiles as viewUserProfile " + + "on userProfile.id=viewUserProfile.userProfileId " + + "where viewUserProfile.viewId = ?"; + + private static final String VIEW_IDENTIFIER_SELECT_ORDER_BY_NAME = VIEW_IDENTIFIER_SELECT + " order by " + COLUMN_NAME_NAME; + + private static final String VIEW_BASE_IDENTIFIER_SELECT_ORDER_BY_ID = VIEW_BASE_IDENTIFIER_SELECT + " order by " + COLUMN_NAME_ID; + // @formatter:on // RowMapper @@ -225,6 +281,37 @@ public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(VIEW_SELECT, new Object[]{}, new ViewRowMapper() ); } + @Override + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + public View save(View entity) { + if (LOG.isTraceEnabled()) { + LOG.trace(entity); + } + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + DAO.getInstance().getJdbcTemp().update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(VIEW_INSERT, Statement.RETURN_GENERATED_KEYS); + new ArgumentPreparedStatementSetter(new Object[] { + entity.getXid(), + entity.getName(), + entity.getBackgroundFilename(), + entity.getUserId(), + entity.getAnonymousAccess(), + new SerializationData().writeObject(entity), + entity.getHeight(), + entity.getWidth() + }).setValues(ps); + return ps; + } + }, keyHolder); + + entity.setId(keyHolder.getKey().intValue()); + return entity; + } + //TO rewrite order for example Object[] with column to order. public List filtered(String filter, String order, Object[] argsFilter, long limit) { @@ -260,6 +347,11 @@ public void delete(View entity) { DAO.getInstance().getJdbcTemp().update(VIEW_DELETE, new Object[] { entity.getId() }); } + @Override + public void delete(Integer id) { + DAO.getInstance().getJdbcTemp().update(VIEW_DELETE, new Object[] { id }); + } + public void deleteViewForUser(int viewId) { DAO.getInstance().getJdbcTemp().update(VIEW_USER_DELETE, new Object[]{viewId}); } @@ -281,7 +373,42 @@ public void setValues(PreparedStatement ps, int i) } }); } - + + @Override + public void init() { + IViewDAO.super.init(); + } + + @Override + public View findById(Integer id) { + try { + return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT + " where " + VIEW_FILTER_BASE_ON_ID, + new Object[]{id}, new ViewRowMapper()); + } catch (EmptyResultDataAccessException e) { + return null; + } + } + + @Override + public View findByXid(String xid) { + try { + return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT + " where " + VIEW_FILTER_BASE_ON_XID, + new Object[]{xid}, new ViewRowMapper()); + } catch (EmptyResultDataAccessException e) { + return null; + } + } + + @Override + public View findByName(String name) { + try { + return DAO.getInstance().getJdbcTemp().queryForObject(VIEW_SELECT + " where " + VIEW_FILTER_BASE_ON_NAME, + new Object[]{name}, new ViewRowMapper()); + } catch (EmptyResultDataAccessException e) { + return null; + } + } + public void deleteViewForUser(int viewId, int userId) { DAO.getInstance().getJdbcTemp().update(VIEW_USER_DELETE_BASE_ON_VIEW_ID_USER_ID, new Object[]{viewId, userId}); } @@ -360,8 +487,8 @@ public List selectViewIdentifiersWithAccess(int userId, i .build()); } - public List findIdentifiers() { - return DAO.getInstance().getJdbcTemp().query(VIEW_IDENTIFIER_SELECT, new Object[]{}, + public List findIdentifiers() { + return DAO.getInstance().getJdbcTemp().query(VIEW_IDENTIFIER_SELECT_ORDER_BY_NAME, new Object[]{}, new ScadaObjectIdentifierRowMapper.Builder() .idColumnName(COLUMN_NAME_ID) .xidColumnName(COLUMN_NAME_XID) @@ -370,42 +497,33 @@ public List findIdentifiers() { } @Override - public View save(View entity) { - throw new UnsupportedOperationException(); - } - - @Override - public void delete(Integer integer) { - throw new UnsupportedOperationException(); + public List findBaseIdentifiers() { + return DAO.getInstance().getJdbcTemp().query(VIEW_BASE_IDENTIFIER_SELECT_ORDER_BY_ID, new Object[]{}, + new BaseObjectIdentifierRowMapper.Builder() + .idColumnName(COLUMN_NAME_ID) + .xidColumnName(COLUMN_NAME_XID) + .build()); } @Override public List selectShareUsers(int viewId) { - throw new UnsupportedOperationException(); + return DAO.getInstance().getJdbcTemp().query(VIEW_USER_BASE_ON_VIEW_ID, new Object[]{viewId}, new ViewUserRowMapper()); } @Override public List selectShareUsersFromProfile(int viewId) { - throw new UnsupportedOperationException(); - } - - @Override - public View findById(Integer integer) { - throw new UnsupportedOperationException(); - } - - @Override - public View findByXid(String xid) { - throw new UnsupportedOperationException(); - } - - @Override - public View findByName(String name) { - throw new UnsupportedOperationException(); - } - - @Override - public List findBaseIdentifiers() { - throw new UnsupportedOperationException(); + if (LOG.isTraceEnabled()) { + LOG.trace("selectViewShareUsers(int viewId) viewId:" + viewId); + } + try { + return DAO.getInstance().getJdbcTemp().query(SHARE_USERS_BY_USERS_PROFILE_AND_VIEW_ID, + new Object[]{viewId}, + ShareUserRowMapper.defaultName()); + } catch (EmptyResultDataAccessException ex) { + return Collections.emptyList(); + } catch (Exception ex) { + LOG.error(ex.getMessage(), ex); + return Collections.emptyList(); + } } } diff --git a/src/org/scada_lts/service/ViewHierarchyService.java b/src/org/scada_lts/service/ViewHierarchyService.java index c274082f42..d420ea1195 100644 --- a/src/org/scada_lts/service/ViewHierarchyService.java +++ b/src/org/scada_lts/service/ViewHierarchyService.java @@ -31,6 +31,7 @@ import org.slf4j.profiler.Profiler; import com.serotonin.mango.view.View; +import org.springframework.stereotype.Service; /** * Service for views hierarchy. @@ -38,6 +39,7 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ +@Service public class ViewHierarchyService { private static final Log LOG = LogFactory.getLog(ViewHierarchyService.class); diff --git a/src/org/scada_lts/web/beans/ApplicationBeans.java b/src/org/scada_lts/web/beans/ApplicationBeans.java index 3c5e5371dd..e26976533e 100644 --- a/src/org/scada_lts/web/beans/ApplicationBeans.java +++ b/src/org/scada_lts/web/beans/ApplicationBeans.java @@ -29,7 +29,6 @@ import org.scada_lts.permissions.service.*; import org.scada_lts.dao.report.IReportInstanceUserCommentDAO; import org.scada_lts.service.IHighestAlarmLevelService; -import org.scada_lts.service.ViewHierarchyService; import org.scada_lts.web.ws.services.DataPointServiceWebSocket; import org.scada_lts.web.ws.services.UserEventServiceWebSocket; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -222,7 +221,7 @@ public static IDataPointDAO getDataPointDAOBean(){ return getBean("dataPointDAO", IDataPointDAO.class); } - public static IPointValueDAO getPointValueDAOBean(){ + public static IPointValueDAO getPointValueDaoBean(){ return getBean("pointValueDAO", IPointValueDAO.class); } diff --git a/src/org/scada_lts/web/mvc/api/DataPointApiService.java b/src/org/scada_lts/web/mvc/api/DataPointApiService.java index b0510b2343..68dedf9bb0 100644 --- a/src/org/scada_lts/web/mvc/api/DataPointApiService.java +++ b/src/org/scada_lts/web/mvc/api/DataPointApiService.java @@ -289,10 +289,8 @@ private List searchDataPoint(HttpServletRequest request, try { if(user.isAdmin()) { int page = searchDataPointJson.getPage(); - boolean hasTypeOrSettableFilter = - (searchDataPointJson.getDataTypes() != null && !searchDataPointJson.getDataTypes().isEmpty()) - || (searchDataPointJson.getSettable() != null); - if(!hasTypeOrSettableFilter) { + if((searchDataPointJson.getDataTypes() == null || searchDataPointJson.getDataTypes().isEmpty()) + && (searchDataPointJson.getSettable() == null)) { return dataPointService.getDataPoints(searchDataPointJson.getKeywordSearch(), searchDataPointJson.getExcludeIds(), searchDataPointJson.isStartsWith(), page, searchDataPointJson.getLimit()); diff --git a/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java b/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java index d91ea6dbc0..61d17ae355 100644 --- a/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java +++ b/test/com/serotonin/mango/rt/RuntimeManagerCreateDataPointRtTest.java @@ -50,7 +50,7 @@ public void config() throws Exception { .thenReturn(new ArrayList<>()); mockStatic(org.scada_lts.web.beans.ApplicationBeans.class); - when(org.scada_lts.web.beans.ApplicationBeans.getPointValueDAOBean()) + when(org.scada_lts.web.beans.ApplicationBeans.getPointValueDaoBean()) .thenReturn(pointValueDAOMock); DAO dao = mock(DAO.class); diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java index 9f5902154c..fc6fc5cf90 100644 --- a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java +++ b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java @@ -22,7 +22,6 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.scada_lts.dao.DAO; import org.scada_lts.dao.IUserDAO; -import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.login.ILoggedUsers; import org.scada_lts.mango.service.PointValueService; @@ -67,7 +66,7 @@ public void config() throws Exception { PointValueDAOMemory memoryDao = new PointValueDAOMemory(userDAO); when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); - when(ApplicationBeans.getPointValueDAOBean()) + when(ApplicationBeans.getPointValueDaoBean()) .thenReturn(memoryDao); SystemSettingsService systemSettingsService = mock(SystemSettingsService.class); diff --git a/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java b/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java index 6ba1496eeb..bbf8ab2103 100644 --- a/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java +++ b/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java @@ -192,7 +192,7 @@ private void preconfig() throws Exception { .thenAnswer(a -> pointValueDAOMemory.getPointValue((long)a.getArgument(0))); mockStatic(ApplicationBeans.class); - when(ApplicationBeans.getPointValueDAOBean()).thenReturn(pointValueDAOMock); + when(ApplicationBeans.getPointValueDaoBean()).thenReturn(pointValueDAOMock); DatabaseAccess dbAccessMock = mock(DatabaseAccess.class); when(ApplicationBeans.getBean("databaseAccess", DatabaseAccess.class)).thenReturn(dbAccessMock); diff --git a/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java b/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java index 55386a8501..c271b53448 100644 --- a/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java +++ b/test/com/serotonin/mango/util/AbstractStartStopDataPointsUtilsTest.java @@ -70,7 +70,7 @@ public void config() throws Exception { PowerMockUtils.configDaoMock(); IPointValueDAO dao = mock(IPointValueDAO.class); - PowerMockito.when(ApplicationBeans.getPointValueDAOBean()) + PowerMockito.when(ApplicationBeans.getPointValueDaoBean()) .thenReturn(dao); when(dao.getLatestPointValue(anyInt())).thenReturn(null); when(dao.findByIdAndTs(anyInt(), anyLong())).thenReturn(Collections.emptyList()); diff --git a/test/utils/ScriptTestUtils.java b/test/utils/ScriptTestUtils.java index 7a06cffa90..80abe25610 100644 --- a/test/utils/ScriptTestUtils.java +++ b/test/utils/ScriptTestUtils.java @@ -9,7 +9,6 @@ import com.serotonin.mango.rt.dataImage.types.MangoValue; import com.serotonin.mango.rt.dataSource.DataSourceRT; import com.serotonin.mango.vo.DataPointVO; -import com.serotonin.mango.vo.DataPointVO.LoggingTypes; import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.dataSource.PointLocatorVO; import com.serotonin.mango.vo.dataSource.virtual.VirtualPointLocatorVO; @@ -73,7 +72,7 @@ public static void configMock(RuntimeManager runtimeManager, ScriptContextObject DataPointServiceWebSocket dataPointServiceWebSocket = mock(DataPointServiceWebSocket.class); when(ApplicationBeans.getDataPointServiceWebSocketBean()).thenReturn(dataPointServiceWebSocket); IPointValueDAO pointValueDaoMock = mock(IPointValueDAO.class); - when(ApplicationBeans.getPointValueDAOBean()) + when(ApplicationBeans.getPointValueDaoBean()) .thenReturn(pointValueDaoMock); when(pointValueDaoMock.applyBounds(anyDouble())).thenAnswer(inv -> inv.getArgument(0)); diff --git a/test/utils/mock/PowerMockUtils.java b/test/utils/mock/PowerMockUtils.java index b204262806..f96a1aaa2a 100644 --- a/test/utils/mock/PowerMockUtils.java +++ b/test/utils/mock/PowerMockUtils.java @@ -28,7 +28,6 @@ import static com.serotonin.mango.util.ThreadPoolExecutorUtils.createForkJoinPool; import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.*; public class PowerMockUtils { @@ -117,7 +116,7 @@ public static void mockPointValueDAOBean() throws Exception { when(dao.applyBounds(anyDouble())).thenAnswer(inv -> inv.getArgument(0)); mockStatic(ApplicationBeans.class); - when(ApplicationBeans.getPointValueDAOBean()) + when(ApplicationBeans.getPointValueDaoBean()) .thenReturn(dao); PointValueService pvs = mock(PointValueService.class); From 11f7a5bd9859f8772b59a8fda6d5f6b875460ea7 Mon Sep 17 00:00:00 2001 From: Limraj Date: Tue, 14 Apr 2026 16:48:13 +0200 Subject: [PATCH 6/7] #3249 Refactor DAO layer for modular architecture - Corrected PointEventDetectorDaoWithCache; - Added utils classes: CacheUtils, ObjectsPaginationUtils; --- .../scada_lts/dao/IPointEventDetectorDAO.java | 2 ++ .../scada_lts/dao/PointEventDetectorDAO.java | 21 ++++++++--- .../cache/PointEventDetectorDaoWithCache.java | 28 +++++++++------ src/org/scada_lts/utils/CacheUtils.java | 36 +++++++++++++++++++ .../utils/ObjectsPaginationUtils.java | 21 +++++++++++ .../dao/IsEventDetectorXidUniqueTest.java | 4 +-- 6 files changed, 96 insertions(+), 16 deletions(-) create mode 100644 src/org/scada_lts/utils/CacheUtils.java create mode 100644 src/org/scada_lts/utils/ObjectsPaginationUtils.java diff --git a/src/org/scada_lts/dao/IPointEventDetectorDAO.java b/src/org/scada_lts/dao/IPointEventDetectorDAO.java index c641011285..038a84e8bc 100644 --- a/src/org/scada_lts/dao/IPointEventDetectorDAO.java +++ b/src/org/scada_lts/dao/IPointEventDetectorDAO.java @@ -8,6 +8,8 @@ public interface IPointEventDetectorDAO { default void init() {}; List getPointEventDetectors(DataPointVO dataPoint); + List getPointEventDetectors(); + List getPointEventDetectors(long offset, int limit); boolean isEventDetectorXidUnique(int dataPointId, String xid, int excludeId); int insert(int dataPointId, PointEventDetectorVO pointEventDetector); void update(int dataPointId, PointEventDetectorVO pointEventDetector); diff --git a/src/org/scada_lts/dao/PointEventDetectorDAO.java b/src/org/scada_lts/dao/PointEventDetectorDAO.java index dacc27b457..6f8a3f86a5 100644 --- a/src/org/scada_lts/dao/PointEventDetectorDAO.java +++ b/src/org/scada_lts/dao/PointEventDetectorDAO.java @@ -475,15 +475,28 @@ public PointEventDetectorVO getPointEventDetector(String pointEventDetectorXid, } } - public List getPointEventDetectors(long limit, int offset) { + @Override + public List getPointEventDetectors() { + return getPointEventDetectors(-1, -1); + } + + @Override + public List getPointEventDetectors(long offset, int limit) { if (LOG.isTraceEnabled()) { LOG.trace("getPointEventDetector(long limit, int offset) limit:" +limit + ", offset:" + offset); } - - String templateSelectWhereIdOrderBy = POINT_EVENT_DETECTOR_SELECT + "order by " + COLUMN_NAME_ID + " LIMIT ? OFFSET ?"; + String templateSelectWhereIdOrderBy; + Object[] args; + if(limit == -1 && offset == -1) { + templateSelectWhereIdOrderBy = POINT_EVENT_DETECTOR_SELECT + "order by " + COLUMN_NAME_ID; + args = new Object[]{}; + } else { + templateSelectWhereIdOrderBy = POINT_EVENT_DETECTOR_SELECT + "order by " + COLUMN_NAME_ID + " LIMIT ? OFFSET ?"; + args = new Object[]{limit, offset}; + } try { - return DAO.getInstance().getJdbcTemp().query(templateSelectWhereIdOrderBy, new Object[]{limit, offset}, new PointEventDetectorDataPointIdRowMapper()); + return DAO.getInstance().getJdbcTemp().query(templateSelectWhereIdOrderBy, args, new PointEventDetectorDataPointIdRowMapper()); } catch (EmptyResultDataAccessException ex) { return Collections.emptyList(); } catch (IncorrectResultSizeDataAccessException ex) { diff --git a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java index 0be887d61a..bbeb97d7b4 100644 --- a/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/PointEventDetectorDaoWithCache.java @@ -3,15 +3,12 @@ import com.serotonin.mango.Common; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.vo.event.PointEventDetectorVO; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.*; +import org.scada_lts.utils.CacheUtils; +import org.scada_lts.utils.ObjectsPaginationUtils; import org.scada_lts.web.beans.ApplicationBeans; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; public class PointEventDetectorDaoWithCache implements IPointEventDetectorDAO { @@ -25,12 +22,12 @@ public PointEventDetectorDaoWithCache(PointEventDetectorCacheable pointEventDete @Override public void init() { IDataPointDAO dataPointDAO = ApplicationBeans.getDataPointDAOBean(); - PointEventDetectorDAO rawPointEventDetectorDAO = - ApplicationBeans.getBean("pointEventDetectorDAO", PointEventDetectorDAO.class); + IPointEventDetectorDAO pointEventDetectorDAO = + ApplicationBeans.getBean("pointEventDetectorDAO", IPointEventDetectorDAO.class); List dataPoints = dataPointDAO.getDataPoints(); - Map> pointEventDetectors = rawPointEventDetectorDAO - .getPointEventDetectors(Integer.MAX_VALUE, 0) + Map> pointEventDetectors = pointEventDetectorDAO + .getPointEventDetectors() .stream() .collect(Collectors.groupingBy(a -> a.njbGetDataPoint().getId())); @@ -40,6 +37,7 @@ public void init() { dataPoint.setEventDetectors(detectors); for (PointEventDetectorVO detector : detectors) { detector.njbSetDataPoint(dataPoint); + pointEventDetectorCache.selectPointEventDetector(detector.getId()); } } pointEventDetectorCache.put(dataPoint.getId(), detectors == null ? new ArrayList<>() : detectors); @@ -103,4 +101,14 @@ public PointEventDetectorVO getPointEventDetector(String pointEventDetectorXid, public int getDataPointId(int pointEventDetectorId) { return pointEventDetectorCache.selectDataPointIdByEventDetectorId(pointEventDetectorId); } + + @Override + public List getPointEventDetectors() { + return CacheUtils.getAllValues("point_event_detector", Comparator.comparing(PointEventDetectorVO::getId)); + } + + @Override + public List getPointEventDetectors(long offset, int limit) { + return ObjectsPaginationUtils.pagination(getPointEventDetectors(), offset, limit); + } } diff --git a/src/org/scada_lts/utils/CacheUtils.java b/src/org/scada_lts/utils/CacheUtils.java new file mode 100644 index 0000000000..958ddf9758 --- /dev/null +++ b/src/org/scada_lts/utils/CacheUtils.java @@ -0,0 +1,36 @@ +package org.scada_lts.utils; + +import org.scada_lts.web.beans.ApplicationBeans; + +import javax.cache.Cache; +import javax.cache.CacheManager; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +public class CacheUtils { + + public static List getAllValues(String cacheName, Comparator comparator) { + CacheManager cacheManager = ApplicationBeans.getBean("ehcache", CacheManager.class); + Cache cache = cacheManager.getCache(cacheName); + return StreamSupport.stream(cache.spliterator(), false) + .filter(Objects::nonNull) + .filter(entry -> entry.getValue() != null) + .map(Cache.Entry::getValue) + .sorted(comparator) + .collect(Collectors.toList()); + } + + public static List getAllKeys(String cacheName, Comparator comparator) { + CacheManager cacheManager = ApplicationBeans.getBean("ehcache", CacheManager.class); + Cache cache = cacheManager.getCache(cacheName); + return StreamSupport.stream(cache.spliterator(), false) + .filter(Objects::nonNull) + .filter(entry -> entry.getKey() != null) + .map(Cache.Entry::getKey) + .sorted(comparator) + .collect(Collectors.toList()); + } +} diff --git a/src/org/scada_lts/utils/ObjectsPaginationUtils.java b/src/org/scada_lts/utils/ObjectsPaginationUtils.java new file mode 100644 index 0000000000..0035cfc12b --- /dev/null +++ b/src/org/scada_lts/utils/ObjectsPaginationUtils.java @@ -0,0 +1,21 @@ +package org.scada_lts.utils; + +import java.util.List; +import java.util.stream.Collectors; + +public class ObjectsPaginationUtils { + + public static List pagination(List list, int page, int limit) { + return list.stream() + .skip((long) (page - 1) * limit) + .limit(limit) + .collect(Collectors.toList()); + } + + public static List pagination(List list, long offset, int limit) { + return list.stream() + .skip(offset) + .limit(limit) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java b/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java index 922a385ba0..8b01a31352 100644 --- a/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java +++ b/test/org/scada_lts/dao/IsEventDetectorXidUniqueTest.java @@ -154,9 +154,9 @@ public IsEventDetectorXidUniqueTest(PointEventDetectorVO pointEventDetector1, Po @Before public void config() { - PointEventDetectorDAO pointEventDetectorDaoMock = mock(PointEventDetectorDAO.class); + IPointEventDetectorDAO pointEventDetectorDaoMock = mock(IPointEventDetectorDAO.class); PointEventDetectorCache pointEventDetectorCache = new PointEventDetectorCache(pointEventDetectorDaoMock); - subject = new PointEventDetectorDaoWithCache(pointEventDetectorCache, pointEventDetectorDaoMock); + subject = new PointEventDetectorDaoWithCache(pointEventDetectorCache); when(pointEventDetectorDaoMock.getPointEventDetector(eq(pointEventDetector1.getXid()), eq(dataPointId))).thenReturn(pointEventDetector1); when(pointEventDetectorDaoMock.getPointEventDetector(eq(pointEventDetector2.getXid()), eq(dataPointId))).thenReturn(pointEventDetector2); From 678ee678ef1f26cafffc2e04293c781be490b9d2 Mon Sep 17 00:00:00 2001 From: patrykb0802 Date: Wed, 15 Apr 2026 09:24:59 +0200 Subject: [PATCH 7/7] #3249 Refactor DAO layer for modular architecture --- WebContent/WEB-INF/applicationContext.xml | 39 ------ .../serotonin/mango/rt/RuntimeManager.java | 6 +- src/com/serotonin/mango/vo/User.java | 2 +- .../scada_lts/cache/PointHierarchyCache.java | 2 +- src/org/scada_lts/dao/ISynopticPanelDAO.java | 15 --- src/org/scada_lts/dao/IUsersProfileDAO.java | 4 - src/org/scada_lts/dao/IViewDAO.java | 1 - src/org/scada_lts/dao/IViewHierarchyDAO.java | 16 --- .../scada_lts/dao/cache/ViewDaoWithCache.java | 3 +- .../dao/event/ICompoundEventDetectorDAO.java | 14 -- src/org/scada_lts/dao/event/IEventDAO.java | 8 -- .../scada_lts/dao/event/IUserEventDAO.java | 32 +++-- .../pointhierarchy/IPointHierarchyXidDAO.java | 43 +++--- .../IPointValueAdnnotationsDAO.java | 18 ++- .../dao/watchlist/IWatchListDAO.java | 8 -- .../ReactivationConnectHttpRetriever.java | 2 +- .../factory/DatabaseAwareBeanFactory.java | 127 ++++-------------- .../service/CompoundEventDetectorService.java | 2 +- .../mango/service/DataPointService.java | 8 +- .../mango/service/DataSourceService.java | 4 +- .../scada_lts/mango/service/EventService.java | 2 +- .../mango/service/MailingListService.java | 2 +- .../service/MaintenanceEventService.java | 2 +- .../mango/service/PointLinkService.java | 2 +- .../mango/service/PublisherService.java | 2 +- .../mango/service/ReportService.java | 8 +- .../mango/service/ScheduledEventService.java | 2 +- .../mango/service/ScriptService.java | 2 +- .../mango/service/WatchListService.java | 2 +- .../service/GetWatchListsWithAccess.java | 2 +- .../service/SynopticPanelService.java | 4 +- .../service/ViewHierarchyService.java | 2 +- .../scada_lts/web/beans/ApplicationBeans.java | 77 +++++++++++ .../cache/DeletePointHierarchyCacheTest.java | 20 ++- ...OnBaseParentIdPointHierarchyCacheTest.java | 19 +-- 35 files changed, 203 insertions(+), 299 deletions(-) diff --git a/WebContent/WEB-INF/applicationContext.xml b/WebContent/WEB-INF/applicationContext.xml index b5f40c369c..abf6de4bfc 100644 --- a/WebContent/WEB-INF/applicationContext.xml +++ b/WebContent/WEB-INF/applicationContext.xml @@ -80,47 +80,36 @@ - - - - - - - - - - - @@ -210,11 +199,9 @@ - - @@ -259,136 +246,110 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/com/serotonin/mango/rt/RuntimeManager.java b/src/com/serotonin/mango/rt/RuntimeManager.java index 442a368528..c386ed98e2 100644 --- a/src/com/serotonin/mango/rt/RuntimeManager.java +++ b/src/com/serotonin/mango/rt/RuntimeManager.java @@ -463,7 +463,7 @@ public void saveDataPoint(DataPointVO point) { if (!ped.getDef().supports(dataType)) // Remove the detector. peds.remove(); - IPointEventDetectorDAO pointEventDetectorDAO = ApplicationBeans.getBean("pointEventDetectorDAO", IPointEventDetectorDAO.class); + IPointEventDetectorDAO pointEventDetectorDAO = ApplicationBeans.getPointEventDetectorDaoBean(); AuditEventUtils.raiseAuditDetectorEvent(point, ped, pointEventDetectorDAO); } @@ -1002,7 +1002,7 @@ private void stopMaintenanceEvent(int id) { } private void startSendEmailForInactiveEvent(MailingList mailingList, ScheduledExecuteInactiveEventService inactiveEmailsService) { - IEventDAO eventDAO = ApplicationBeans.getBean("eventDAO", IEventDAO.class); + IEventDAO eventDAO = ApplicationBeans.getEventDaoBean(); CommunicationChannel channel = CommunicationChannel.newEmailChannel(mailingList, new SystemSettingsService()); ScheduledExecuteInactiveEventRT sendEmail = new ScheduledExecuteInactiveEventRT(inactiveEmailsService, InactiveEventsProvider.newInstance(eventDAO, ScheduledExecuteInactiveEventDAO.getInstance(), @@ -1013,7 +1013,7 @@ private void startSendEmailForInactiveEvent(MailingList mailingList, ScheduledEx } private void startSendSmsForInactiveEvent(MailingList mailingList, ScheduledExecuteInactiveEventService inactiveEmailsService) { - IEventDAO eventDAO = ApplicationBeans.getBean("eventDAO", IEventDAO.class); + IEventDAO eventDAO = ApplicationBeans.getEventDaoBean(); CommunicationChannel channel = CommunicationChannel.newSmsChannel(mailingList, new SystemSettingsService()); ScheduledExecuteInactiveEventRT sendSms = new ScheduledExecuteInactiveEventRT(inactiveEmailsService, InactiveEventsProvider.newInstance(eventDAO, ScheduledExecuteInactiveEventDAO.getInstance(), diff --git a/src/com/serotonin/mango/vo/User.java b/src/com/serotonin/mango/vo/User.java index b91b93c0f6..61821a56f0 100644 --- a/src/com/serotonin/mango/vo/User.java +++ b/src/com/serotonin/mango/vo/User.java @@ -587,7 +587,7 @@ public void jsonDeserializePermissions(JsonReader reader, JsonObject json) } } - IUsersProfileDAO usersProfileDAO = ApplicationBeans.getBean("usersProfileDAO", IUsersProfileDAO.class); + IUsersProfileDAO usersProfileDAO = ApplicationBeans.getUsersProfileDaoBean(); String userProfileXid = json.getString("userProfileXid"); Integer userProfileId = json.getInt("userProfile"); if (userProfileXid != null && !userProfileXid.isEmpty()) { diff --git a/src/org/scada_lts/cache/PointHierarchyCache.java b/src/org/scada_lts/cache/PointHierarchyCache.java index 785bfa2584..d6f1ebab6f 100644 --- a/src/org/scada_lts/cache/PointHierarchyCache.java +++ b/src/org/scada_lts/cache/PointHierarchyCache.java @@ -105,7 +105,7 @@ public void updateData() throws Exception { for (PointHierarchyNode ph : lstHierarchy) { addFolder(ph); } - IPointHierarchyDAO pointHierarchyDAO = ApplicationBeans.getBean("pointHierarchyDAO", IPointHierarchyDAO.class); + IPointHierarchyDAO pointHierarchyDAO = ApplicationBeans.getPointHierarchyDaoBean(); List lstPointHierarchy = pointHierarchyDAO.getPointsHierarchy(); Collections.sort(lstPointHierarchy, PointHierarchyComparator.getInst()); diff --git a/src/org/scada_lts/dao/ISynopticPanelDAO.java b/src/org/scada_lts/dao/ISynopticPanelDAO.java index 81ea89ad49..7422664f25 100644 --- a/src/org/scada_lts/dao/ISynopticPanelDAO.java +++ b/src/org/scada_lts/dao/ISynopticPanelDAO.java @@ -1,21 +1,6 @@ package org.scada_lts.dao; -import org.scada_lts.dao.model.ScadaObjectIdentifier; import org.scada_lts.service.model.SynopticPanel; -import org.springframework.dao.EmptyResultDataAccessException; - -import java.util.List; public interface ISynopticPanelDAO extends CrudOperations { - SynopticPanel create(SynopticPanel entity); - - List getSimpleList(); - - List getAll(); - - SynopticPanel getById(int id) throws EmptyResultDataAccessException; - - SynopticPanel update(SynopticPanel entity); - - int delete(int id); } diff --git a/src/org/scada_lts/dao/IUsersProfileDAO.java b/src/org/scada_lts/dao/IUsersProfileDAO.java index a9fe1827f4..32ad687dc3 100644 --- a/src/org/scada_lts/dao/IUsersProfileDAO.java +++ b/src/org/scada_lts/dao/IUsersProfileDAO.java @@ -4,16 +4,12 @@ import br.org.scadabr.vo.permission.WatchListAccess; import br.org.scadabr.vo.usersProfiles.UsersProfileVO; import com.serotonin.mango.vo.permission.DataPointAccess; -import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; -@Component public interface IUsersProfileDAO extends GenerateXid { - String generateUniqueXid(String prefix); - Optional selectProfileById(int profileId); Optional selectProfileByXid(String profileXid); diff --git a/src/org/scada_lts/dao/IViewDAO.java b/src/org/scada_lts/dao/IViewDAO.java index 3269717030..7b63908db0 100644 --- a/src/org/scada_lts/dao/IViewDAO.java +++ b/src/org/scada_lts/dao/IViewDAO.java @@ -3,7 +3,6 @@ import br.org.scadabr.vo.permission.ViewAccess; import com.serotonin.mango.view.ShareUser; import com.serotonin.mango.view.View; -import org.scada_lts.dao.model.BaseObjectIdentifier; import org.scada_lts.dao.model.ScadaObjectIdentifier; import java.util.List; diff --git a/src/org/scada_lts/dao/IViewHierarchyDAO.java b/src/org/scada_lts/dao/IViewHierarchyDAO.java index cfd73406c4..4a86445e8c 100644 --- a/src/org/scada_lts/dao/IViewHierarchyDAO.java +++ b/src/org/scada_lts/dao/IViewHierarchyDAO.java @@ -8,21 +8,5 @@ public interface IViewHierarchyDAO extends GenericHierarchyDAO { int ROOT_ID = -1; - List getAll(); - - List getNode(long l); - List getViewInHierarchyNode(); - - int add(ViewHierarchyNode node); - - int update(ViewHierarchyNode node); - - int moveFolder(int id, int newParentId); - - int moveView(int id, int newParentId); - - int delView(int id); - - int delFolder(int id); } diff --git a/src/org/scada_lts/dao/cache/ViewDaoWithCache.java b/src/org/scada_lts/dao/cache/ViewDaoWithCache.java index a8a95e50a3..0288641fdb 100644 --- a/src/org/scada_lts/dao/cache/ViewDaoWithCache.java +++ b/src/org/scada_lts/dao/cache/ViewDaoWithCache.java @@ -26,7 +26,7 @@ public ViewDaoWithCache(ViewCacheable viewCache) { @Override public void init() { - IViewDAO viewDao = ApplicationBeans.getBean("viewDAO", IViewDAO.class); + IViewDAO viewDao = ApplicationBeans.getViewDaoBean(); List views = viewDao.findAll(); for(View view: views) { applyShareUsers(view); @@ -96,6 +96,7 @@ public View findById(Integer viewId) { return viewCache.findById(viewId); } + @Override public View findByName(String name) { if(name == null) { return null; diff --git a/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java b/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java index 37edbe8daa..db7ed41e3b 100644 --- a/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java +++ b/src/org/scada_lts/dao/event/ICompoundEventDetectorDAO.java @@ -3,21 +3,7 @@ import com.serotonin.mango.vo.event.CompoundEventDetectorVO; import org.scada_lts.dao.GenericDAO; -import java.util.List; - public interface ICompoundEventDetectorDAO extends GenericDAO { - List findAll(); - - CompoundEventDetectorVO findById(Object[] pk); - CompoundEventDetectorVO findByXId(Object[] pk); - - List filtered(String filter, Object[] argsFilter, long limit); - - Object[] create(CompoundEventDetectorVO entity); - - void update(CompoundEventDetectorVO entity); - - void delete(CompoundEventDetectorVO entity); } diff --git a/src/org/scada_lts/dao/event/IEventDAO.java b/src/org/scada_lts/dao/event/IEventDAO.java index e5b99b6cf0..f8147554bc 100644 --- a/src/org/scada_lts/dao/event/IEventDAO.java +++ b/src/org/scada_lts/dao/event/IEventDAO.java @@ -17,14 +17,6 @@ import java.util.Set; public interface IEventDAO extends GenericDaoCR { - List findAll(); - - EventInstance findById(Object[] pk); - - List filtered(String filter, Object[] argsFilter, long limit); - - Object[] create(EventInstance entity); - List findEventsWithLimit(int typeId, int typeRef, int limit, int offset); SQLPageWithTotal findEvents( diff --git a/src/org/scada_lts/dao/event/IUserEventDAO.java b/src/org/scada_lts/dao/event/IUserEventDAO.java index d37cf38642..56a859d0f2 100644 --- a/src/org/scada_lts/dao/event/IUserEventDAO.java +++ b/src/org/scada_lts/dao/event/IUserEventDAO.java @@ -1,16 +1,24 @@ package org.scada_lts.dao.event; -public interface IUserEventDAO extends org.scada_lts.dao.GenericDaoCR { - public abstract java.util.List findAll(); - public abstract org.scada_lts.dao.model.event.UserEvent findById(java.lang.Object[] arg0); - public abstract java.util.List filtered(java.lang.String arg0, java.lang.Object[] arg1, long arg2); - public abstract java.lang.Object[] create(org.scada_lts.dao.model.event.UserEvent arg0); - public abstract void batchUpdate(int arg0, java.util.List arg1, boolean arg2); - public abstract void updateAck(long arg0, boolean arg1); - public abstract void silenceEvent(long arg0, int arg1); - public abstract void unsilenceEvent(long arg0, int arg1); - public abstract void silenceEvents(java.util.List arg0, int arg1); - public abstract void unsilenceEvents(java.util.List arg0, int arg1); - public abstract void delete(int arg0); +import org.scada_lts.dao.GenericDaoCR; +import org.scada_lts.dao.model.event.UserEvent; + +import java.util.List; + +public interface IUserEventDAO extends GenericDaoCR { + + void batchUpdate(int userId, List eventIds, boolean silence); + + void updateAck(long eventId, boolean alarmWentOff); + + void silenceEvent(long eventId, int userId); + + void unsilenceEvent(long eventId, int userId); + + void silenceEvents(List eventIds, int userId); + + void unsilenceEvents(List eventIds, int userId); + + void delete(int eventId); } diff --git a/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java b/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java index 1d410a1e71..549cb266f1 100644 --- a/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java +++ b/src/org/scada_lts/dao/pointhierarchy/IPointHierarchyXidDAO.java @@ -1,24 +1,27 @@ package org.scada_lts.dao.pointhierarchy; -public interface IPointHierarchyXidDAO extends org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO { - public abstract java.util.List getPointsHierarchy(); - public abstract com.serotonin.mango.vo.DataPointVO getPointsHierarchy(int arg0); - public abstract java.util.Map> getFolderList(); - public abstract boolean updateTitle(int arg0, java.lang.String arg1); - public abstract boolean updateParentIdDataPoint(int arg0, int arg1); - public abstract boolean updateParentId(int arg0, int arg1); - public abstract int insert(int arg0, java.lang.String arg1); - public abstract int insert(int arg0, int arg1, java.lang.String arg2); - public abstract void delete(); - public abstract boolean deleteFolder(int arg0, int arg1); - public abstract boolean updateNameFolder(java.lang.String arg0, java.lang.String arg1); - public abstract boolean updateParentPoint(java.lang.String arg0, java.lang.String arg1); - public abstract boolean updateParentPoint(java.lang.String arg0, java.lang.Integer arg1); - public abstract boolean updateFolder(java.lang.String arg0, java.lang.String arg1); - public abstract void add(org.scada_lts.web.mvc.api.dto.FolderPointHierarchy arg0); - public abstract org.scada_lts.web.mvc.api.dto.FolderPointHierarchy folderCheckExist(java.lang.String arg0); - public abstract java.util.List getFolders(); - public abstract void deleteFolderXid(java.lang.String arg0); - public abstract java.lang.String getFolderXid(int arg0); +import org.scada_lts.web.mvc.api.dto.FolderPointHierarchy; + +import java.util.List; + +public interface IPointHierarchyXidDAO extends IPointHierarchyDAO { + + boolean updateNameFolder(String xidFolder, String newName); + + boolean updateParentPoint(String xidPoint, String xidFolder); + + boolean updateParentPoint(String xidPoint, Integer folderId); + + boolean updateFolder(String xidFolder, String newParentXidFolder); + + void add(FolderPointHierarchy folderPointHierarchy); + + FolderPointHierarchy folderCheckExist(String xidFolder); + + List getFolders(); + + void deleteFolderXid(String xidFolder); + + String getFolderXid(int folderId); } diff --git a/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java b/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java index 15d6063c7f..4e2d0db3de 100644 --- a/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java +++ b/src/org/scada_lts/dao/pointvalues/IPointValueAdnnotationsDAO.java @@ -1,11 +1,15 @@ package org.scada_lts.dao.pointvalues; -public interface IPointValueAdnnotationsDAO extends org.scada_lts.dao.GenericDaoCR { - public abstract java.util.List findAll(); - public abstract org.scada_lts.dao.model.point.PointValueAdnnotation findById(java.lang.Object[] arg0); - public abstract java.util.List filtered(java.lang.String arg0, java.lang.Object[] arg1, long arg2); - public abstract java.lang.Object[] create(org.scada_lts.dao.model.point.PointValueAdnnotation arg0); - public abstract void update(int arg0); - public abstract void updateAnnotations(java.util.List arg0); +import org.scada_lts.dao.GenericDaoCR; +import org.scada_lts.dao.model.point.PointValue; +import org.scada_lts.dao.model.point.PointValueAdnnotation; + +import java.util.List; + +public interface IPointValueAdnnotationsDAO extends GenericDaoCR { + + void update(int pointValueId); + + void updateAnnotations(List pointValues); } diff --git a/src/org/scada_lts/dao/watchlist/IWatchListDAO.java b/src/org/scada_lts/dao/watchlist/IWatchListDAO.java index 9295d99a8b..7c953be7d7 100644 --- a/src/org/scada_lts/dao/watchlist/IWatchListDAO.java +++ b/src/org/scada_lts/dao/watchlist/IWatchListDAO.java @@ -11,14 +11,6 @@ public interface IWatchListDAO extends GenericDaoCR { - List findAll(); - - WatchList findById(Object[] pk); - - List filtered(String filter, Object[] argsFilter, long limit); - - Object[] create(WatchList entity); - WatchList findByXId(String xid); List getWatchListUsers(int watchListId); diff --git a/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java b/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java index cf2a159241..f05f6d56ec 100644 --- a/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java +++ b/src/org/scada_lts/ds/reactivation/ReactivationConnectHttpRetriever.java @@ -33,7 +33,7 @@ public void execute(JobExecutionContext jobExecutionContext) throws JobExecution int id = (int) entry.getValue(); String name = (String) entry.getKey(); - IDataSourceDAO dao = ApplicationBeans.getBean("dataSourceDAO", IDataSourceDAO.class); + IDataSourceDAO dao = ApplicationBeans.getDataSourceDaoBean(); DataSourceVO ds = dao.getDataSource(id); HttpRetrieverDataSourceVO hrds = (HttpRetrieverDataSourceVO) ds; diff --git a/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java b/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java index e8b6b3b2b6..7e1a6ae242 100644 --- a/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java +++ b/src/org/scada_lts/factory/DatabaseAwareBeanFactory.java @@ -2,127 +2,50 @@ import com.serotonin.mango.Common; import com.serotonin.mango.db.DatabaseAccess.DatabaseType; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -public class DatabaseAwareBeanFactory implements FactoryBean, ApplicationContextAware { +public class DatabaseAwareBeanFactory implements FactoryBean, BeanNameAware, BeanFactoryAware - private static final Log LOG = LogFactory.getLog(DatabaseAwareBeanFactory.class); - private static final String DEFAULT_DB_TYPE = "mysql"; - private static final String DB_PLUGIN_CONFIG_PATTERN = "classpath*:META-INF/scadalts-db/%s.xml"; - private static final Object DB_PLUGIN_LOAD_MONITOR = new Object(); - private static final Set DB_PLUGIN_LOAD_ATTEMPTS = Collections.synchronizedSet(new HashSet()); +{ - private ApplicationContext applicationContext; - private String prefix; - - public void setPrefix(String prefix) { - this.prefix = prefix; - } + private String beanName; + private Class type; + private BeanFactory beanFactory; @Override - public T getObject() { - if (applicationContext == null) { - throw new IllegalStateException("ApplicationContext is not set for DatabaseAwareBeanFactory."); - } - if (prefix == null || prefix.trim().isEmpty()) { - throw new IllegalStateException("Bean prefix is not set for DatabaseAwareBeanFactory."); - } - - String dbKey = resolveDbKey(); - String targetBeanName = buildBeanName(dbKey); - if (applicationContext.containsBean(targetBeanName)) { - return getBean(targetBeanName); - } - - ensureDbPluginLoaded(dbKey); - if (applicationContext.containsBean(targetBeanName)) { - return getBean(targetBeanName); - } - - String msg = "DB plugin not found for db.type=" + dbKey + ". Expected bean '" + targetBeanName - + "'. Verify DB plugin JAR and META-INF/scadalts-db/" + dbKey + ".xml are present on classpath."; - LOG.error(msg); - throw new IllegalStateException(msg); + public void setBeanName(String beanName) { + this.beanName = beanName; } @Override - public Class getObjectType() { - if (applicationContext == null || prefix == null || prefix.trim().isEmpty()) { - return Object.class; - } - String dbKey = resolveDbKey(); - Class type = applicationContext.getType(buildBeanName(dbKey)); - return type == null ? Object.class : type; + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + this.type = beanFactory.getType(getDaoBeanName()); } @Override - public boolean isSingleton() { - return true; + public T getObject() { + return beanFactory.getBean(getDaoBeanName(), getObjectType()); } @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - private String resolveDbKey() { - String dbType = Common.getEnvironmentProfile().getString("db.type", DEFAULT_DB_TYPE); - return DatabaseType.from(dbType).getKey(); - } - - private void ensureDbPluginLoaded(String dbKey) { - if (!(applicationContext instanceof ConfigurableApplicationContext)) { - return; - } - - String databaseAccessBeanName = "databaseAccess-" + dbKey; - if (applicationContext.containsBean(databaseAccessBeanName)) { - return; - } - - synchronized (DB_PLUGIN_LOAD_MONITOR) { - if (applicationContext.containsBean(databaseAccessBeanName)) { - return; - } - if (DB_PLUGIN_LOAD_ATTEMPTS.contains(dbKey)) { - return; - } - DB_PLUGIN_LOAD_ATTEMPTS.add(dbKey); - - ConfigurableApplicationContext configurable = (ConfigurableApplicationContext) applicationContext; - ConfigurableListableBeanFactory beanFactory = configurable.getBeanFactory(); - if (!(beanFactory instanceof BeanDefinitionRegistry)) { - return; - } - - BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; - XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); - String pattern = String.format(DB_PLUGIN_CONFIG_PATTERN, dbKey); - int loaded = reader.loadBeanDefinitions(pattern); - if (loaded > 0) { - LOG.info("Loaded " + loaded + " DB plugin bean definition(s) from " + pattern); - } - } + public Class getObjectType() { + return (Class) type; } - private String buildBeanName(String dbKey) { - return prefix + "-" + dbKey; + @Override + public boolean isSingleton() { + return true; } - @SuppressWarnings("unchecked") - private T getBean(String beanName) { - return (T) applicationContext.getBean(beanName); + public String getDaoBeanName() { + String dbType = Common.getEnvironmentProfile().getString("db.type", "derby"); + String dbKey = DatabaseType.from(dbType).getKey(); + return beanName + "-" + dbKey; } } diff --git a/src/org/scada_lts/mango/service/CompoundEventDetectorService.java b/src/org/scada_lts/mango/service/CompoundEventDetectorService.java index 320c750af6..4a5804d102 100644 --- a/src/org/scada_lts/mango/service/CompoundEventDetectorService.java +++ b/src/org/scada_lts/mango/service/CompoundEventDetectorService.java @@ -37,7 +37,7 @@ public class CompoundEventDetectorService implements MangoCompoundEventDetector private final ICompoundEventDetectorDAO cedDao; public CompoundEventDetectorService() { - cedDao = ApplicationBeans.getBean("compoundEventDetectorDAO", ICompoundEventDetectorDAO.class); + cedDao = ApplicationBeans.getCompoundEventDetectorDaoBean(); } @Override diff --git a/src/org/scada_lts/mango/service/DataPointService.java b/src/org/scada_lts/mango/service/DataPointService.java index 6193405380..3017f1c058 100644 --- a/src/org/scada_lts/mango/service/DataPointService.java +++ b/src/org/scada_lts/mango/service/DataPointService.java @@ -92,7 +92,7 @@ public class DataPointService implements MangoDataPoint { private final IWatchListDAO watchListDAO; - private static final IPointLinkDAO pointLinkDAO = ApplicationBeans.getBean("pointLinkDAO", IPointLinkDAO.class); + private static final IPointLinkDAO pointLinkDAO = ApplicationBeans.getPointLinkDaoBean(); private final PointHierarchyService pointHierarchyService; @@ -102,10 +102,10 @@ public class DataPointService implements MangoDataPoint { public DataPointService() { this.dataPointDAO = ApplicationBeans.getDataPointDAOBean(); - this.dataSourceDAO = ApplicationBeans.getBean("dataSourceDAO", IDataSourceDAO.class); - this.pointHierarchyDAO = ApplicationBeans.getBean("pointHierarchyDAO", IPointHierarchyDAO.class); + this.dataSourceDAO = ApplicationBeans.getDataSourceDaoBean(); + this.pointHierarchyDAO = ApplicationBeans.getPointHierarchyDaoBean(); this.dataPointUserDAO = ApplicationBeans.getDataPointUserDAOBean(); - this.watchListDAO = ApplicationBeans.getBean("watchListDAO", IWatchListDAO.class); + this.watchListDAO = ApplicationBeans.getWatchListDaoBean(); this.pointHierarchyService = ApplicationBeans.getBean("pointHierarchyService", PointHierarchyService.class); this.userCommentDAO = ApplicationBeans.getUserCommentDaoBean(); this.getDataPointsWithAccess = new GetDataPointsWithAccess(dataPointDAO); diff --git a/src/org/scada_lts/mango/service/DataSourceService.java b/src/org/scada_lts/mango/service/DataSourceService.java index f482bbc9d0..e70e454507 100644 --- a/src/org/scada_lts/mango/service/DataSourceService.java +++ b/src/org/scada_lts/mango/service/DataSourceService.java @@ -62,7 +62,7 @@ public class DataSourceService implements MangoDataSource { private final GetObjectsWithAccess, User> getDataSourcesWithAccess; public DataSourceService() { - this.dataSourceDAO = ApplicationBeans.getBean("dataSourceDAO", IDataSourceDAO.class); + this.dataSourceDAO = ApplicationBeans.getDataSourceDaoBean(); this.dataPointService = new DataPointService(); this.getDataSourcesWithAccess = new GetDataSourcesWithAccess(dataSourceDAO, ApplicationBeans.getDataPointDAOBean()); } @@ -172,7 +172,7 @@ public void deleteDataSource(final int dataSourceId) { @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) private void deleteInTransaction(final int dataSourceId) { - IMaintenanceEventDAO meDAO = ApplicationBeans.getBean("maintenanceEventDAO", IMaintenanceEventDAO.class); + IMaintenanceEventDAO meDAO = ApplicationBeans.getMaintenanceEventDaoBean(); meDAO.deleteMaintenanceEventsForDataSource(dataSourceId); dataSourceDAO.delete(dataSourceId); UsersProfileService usersProfileService = new UsersProfileService(); diff --git a/src/org/scada_lts/mango/service/EventService.java b/src/org/scada_lts/mango/service/EventService.java index e5de29f383..51b23d60e0 100644 --- a/src/org/scada_lts/mango/service/EventService.java +++ b/src/org/scada_lts/mango/service/EventService.java @@ -73,7 +73,7 @@ public class EventService implements MangoEvent { private final SystemSettingsService systemSettingsService; public EventService() { - eventDAO = ApplicationBeans.getBean("eventDAO", IEventDAO.class); + eventDAO = ApplicationBeans.getEventDaoBean(); userEventDAO = ApplicationBeans.getUserEventDAOBean(); userCommentDAO = ApplicationBeans.getUserCommentDaoBean(); systemSettingsService = ApplicationBeans.getBean("systemSettingsService", SystemSettingsService.class); diff --git a/src/org/scada_lts/mango/service/MailingListService.java b/src/org/scada_lts/mango/service/MailingListService.java index bad6ede96e..9b3b029b53 100644 --- a/src/org/scada_lts/mango/service/MailingListService.java +++ b/src/org/scada_lts/mango/service/MailingListService.java @@ -50,7 +50,7 @@ public class MailingListService implements MangoMailingList { //TODO // @Resource - private static final IMailingListDAO mailingListDAO = ApplicationBeans.getBean("mailingListDAO", IMailingListDAO.class); + private static final IMailingListDAO mailingListDAO = ApplicationBeans.getMailingListDaoBean(); //TODO // @Resource diff --git a/src/org/scada_lts/mango/service/MaintenanceEventService.java b/src/org/scada_lts/mango/service/MaintenanceEventService.java index 506e0c010b..a11915e144 100644 --- a/src/org/scada_lts/mango/service/MaintenanceEventService.java +++ b/src/org/scada_lts/mango/service/MaintenanceEventService.java @@ -36,7 +36,7 @@ */ public class MaintenanceEventService implements MangoMaintenanceEvent { - private final IMaintenanceEventDAO maintenanceEventDAO = ApplicationBeans.getBean("maintenanceEventDAO", IMaintenanceEventDAO.class); + private final IMaintenanceEventDAO maintenanceEventDAO = ApplicationBeans.getMaintenanceEventDaoBean(); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/PointLinkService.java b/src/org/scada_lts/mango/service/PointLinkService.java index 220ab0b16a..5a6b5b89aa 100644 --- a/src/org/scada_lts/mango/service/PointLinkService.java +++ b/src/org/scada_lts/mango/service/PointLinkService.java @@ -35,7 +35,7 @@ */ public class PointLinkService implements MangoPointLink { - private static IPointLinkDAO pointLinkDAO = ApplicationBeans.getBean("pointLinkDAO", IPointLinkDAO.class); + private static IPointLinkDAO pointLinkDAO = ApplicationBeans.getPointLinkDaoBean(); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/PublisherService.java b/src/org/scada_lts/mango/service/PublisherService.java index e45647e1f0..2cfd33846e 100644 --- a/src/org/scada_lts/mango/service/PublisherService.java +++ b/src/org/scada_lts/mango/service/PublisherService.java @@ -36,7 +36,7 @@ */ public class PublisherService implements MangoPublisher { - private final IPublisherDAO publisherDAO = ApplicationBeans.getBean("publisherDAO", IPublisherDAO.class); + private final IPublisherDAO publisherDAO = ApplicationBeans.getPublisherDaoBean(); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/ReportService.java b/src/org/scada_lts/mango/service/ReportService.java index 57738b92d9..6c4b651e26 100644 --- a/src/org/scada_lts/mango/service/ReportService.java +++ b/src/org/scada_lts/mango/service/ReportService.java @@ -62,10 +62,10 @@ public class ReportService implements MangoReport { private GetReportInstancesWithAccess getReportInstancesWithAccess; public ReportService() { - this.reportDAO = ApplicationBeans.getBean("reportDAO", IReportDAO.class); - this.reportInstanceDAO = ApplicationBeans.getBean("reportInstanceDAO", IReportInstanceDAO.class); - this.reportInstanceDataDAO = ApplicationBeans.getBean("reportInstanceDataDAO", IReportInstanceDataDAO.class); - this.reportInstancePointDAO = ApplicationBeans.getBean("reportInstancePointDAO", IReportInstancePointDAO.class); + this.reportDAO = ApplicationBeans.getReportDaoBean(); + this.reportInstanceDAO = ApplicationBeans.getReportInstanceDaoBean(); + this.reportInstanceDataDAO = ApplicationBeans.getReportInstanceDataDaoBean(); + this.reportInstancePointDAO = ApplicationBeans.getReportInstancePointDaoBean(); this.reportInstanceUserCommentDAO = ApplicationBeans.getReportInstanceUserCommentDAOBean(); this.getReportsWithAccess = new GetReportsWithAccess(reportDAO); this.getReportInstancesWithAccess = new GetReportInstancesWithAccess(reportInstanceDAO); diff --git a/src/org/scada_lts/mango/service/ScheduledEventService.java b/src/org/scada_lts/mango/service/ScheduledEventService.java index 87349cad73..474ee71d07 100644 --- a/src/org/scada_lts/mango/service/ScheduledEventService.java +++ b/src/org/scada_lts/mango/service/ScheduledEventService.java @@ -35,7 +35,7 @@ */ public class ScheduledEventService implements MangoScheduledEvent { - private final IScheduledEventDAO scheduledEventDAO = ApplicationBeans.getBean("scheduledEventDAO", IScheduledEventDAO.class); + private final IScheduledEventDAO scheduledEventDAO = ApplicationBeans.getScheduledEventDaoBean(); @Override public String generateUniqueXid() { diff --git a/src/org/scada_lts/mango/service/ScriptService.java b/src/org/scada_lts/mango/service/ScriptService.java index 9b87e76ff2..c56fc8a235 100644 --- a/src/org/scada_lts/mango/service/ScriptService.java +++ b/src/org/scada_lts/mango/service/ScriptService.java @@ -13,7 +13,7 @@ @Service public class ScriptService implements MangoScript { - private final IScriptDAO scriptDAO = ApplicationBeans.getBean("scriptDAO", IScriptDAO.class); + private final IScriptDAO scriptDAO = ApplicationBeans.getScriptDaoBean(); @Override public void saveScript(final ScriptVO vo) { diff --git a/src/org/scada_lts/mango/service/WatchListService.java b/src/org/scada_lts/mango/service/WatchListService.java index f66cc4892a..17fd94746f 100644 --- a/src/org/scada_lts/mango/service/WatchListService.java +++ b/src/org/scada_lts/mango/service/WatchListService.java @@ -55,7 +55,7 @@ public class WatchListService implements MangoWatchList { private GetObjectsWithAccess getObjectsWithAccess; public WatchListService() { - this.watchListDAO = ApplicationBeans.getBean("watchListDAO", IWatchListDAO.class); + this.watchListDAO = ApplicationBeans.getWatchListDaoBean(); this.getShareUsers = ApplicationBeans.getWatchListGetShareUsersBean(); this.usersProfileService = ApplicationBeans.getUsersProfileService(); this.getObjectsWithAccess = new GetWatchListsWithAccess(watchListDAO); diff --git a/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java b/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java index 963107bbfe..9ddc52d287 100644 --- a/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java +++ b/src/org/scada_lts/permissions/service/GetWatchListsWithAccess.java @@ -23,7 +23,7 @@ public class GetWatchListsWithAccess implements GetObjectsWithAccess getSimpleSynopticPanelsList() { return synopticPanelDAO.getSimpleList(); @@ -45,4 +45,4 @@ public int deleteSynopticPanel(int id) { public String generateXid() { return DAO.getInstance().generateUniqueXid(SynopticPanel.XID_PREFIX, "synopticPanels");} -} \ No newline at end of file +} diff --git a/src/org/scada_lts/service/ViewHierarchyService.java b/src/org/scada_lts/service/ViewHierarchyService.java index d420ea1195..088f34803d 100644 --- a/src/org/scada_lts/service/ViewHierarchyService.java +++ b/src/org/scada_lts/service/ViewHierarchyService.java @@ -61,7 +61,7 @@ public ViewHierarchyService(IViewHierarchyDAO vhDAO, IViewDAO viewDAO){ } public ViewHierarchyService(){ - this.vhDAO = ApplicationBeans.getBean("viewHierarchyDAO", IViewHierarchyDAO.class); + this.vhDAO = ApplicationBeans.getViewHierarchyDaoBean(); this.viewDAO = ApplicationBeans.getViewDaoBean(); } diff --git a/src/org/scada_lts/web/beans/ApplicationBeans.java b/src/org/scada_lts/web/beans/ApplicationBeans.java index e26976533e..d9aff3cbf8 100644 --- a/src/org/scada_lts/web/beans/ApplicationBeans.java +++ b/src/org/scada_lts/web/beans/ApplicationBeans.java @@ -17,18 +17,27 @@ import org.scada_lts.dao.*; import org.scada_lts.dao.alarms.IAlarmsDAO; import org.scada_lts.dao.cache.*; +import org.scada_lts.dao.event.ICompoundEventDetectorDAO; +import org.scada_lts.dao.event.IEventDAO; import org.scada_lts.dao.event.IUserEventDAO; +import org.scada_lts.dao.mailingList.IMailingListDAO; import org.scada_lts.dao.mailingList.IMailingListInactiveDAO; import org.scada_lts.dao.mailingList.IMailingListMemberDAO; +import org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO; import org.scada_lts.dao.pointhierarchy.IPointHierarchyXidDAO; import org.scada_lts.dao.pointvalues.IPointValueAdnnotationsDAO; import org.scada_lts.dao.pointvalues.IPointValueAmChartDAO; +import org.scada_lts.dao.report.IReportDAO; +import org.scada_lts.dao.report.IReportInstanceDAO; +import org.scada_lts.dao.report.IReportInstanceDataDAO; +import org.scada_lts.dao.report.IReportInstancePointDAO; import org.scada_lts.mango.service.UserCommentService; import org.scada_lts.mango.service.UsersProfileService; import org.scada_lts.permissions.service.*; import org.scada_lts.dao.report.IReportInstanceUserCommentDAO; import org.scada_lts.service.IHighestAlarmLevelService; +import org.scada_lts.dao.watchlist.IWatchListDAO; import org.scada_lts.web.ws.services.DataPointServiceWebSocket; import org.scada_lts.web.ws.services.UserEventServiceWebSocket; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -229,10 +238,18 @@ public static IDataPointUserDAO getDataPointUserDAOBean() { return getBean("dataPointUserDAO", IDataPointUserDAO.class); } + public static IDataSourceDAO getDataSourceDaoBean() { + return getBean("dataSourceDAO", IDataSourceDAO.class); + } + public static IEventDetectorTemplateDAO getEventDetectorTemplateDAOBean() { return getBean("eventDetectorTemplateDAO", IEventDetectorTemplateDAO.class); } + public static IEventDAO getEventDaoBean() { + return getBean("eventDAO", IEventDAO.class); + } + public static IFlexProjectDAO getFlexProjectDAOBean() { return getBean("flexProjectDAO", IFlexProjectDAO.class); } @@ -241,10 +258,18 @@ public static IHierarchyDAO getHierarchyDAOBean() { return getBean("hierarchyDAO", IHierarchyDAO.class); } + public static IMailingListDAO getMailingListDaoBean() { + return getBean("mailingListDAO", IMailingListDAO.class); + } + public static IPendingEventsDAO getPendingEventsDAOBean() { return getBean("pendingEventsDAO", IPendingEventsDAO.class); } + public static IPointHierarchyDAO getPointHierarchyDaoBean() { + return getBean("pointHierarchyDAO", IPointHierarchyDAO.class); + } + public static ISystemSettingsDAO getSystemSettingsDaoBean() { return getBean("systemSettingsDAO", ISystemSettingsDAO.class); } @@ -265,6 +290,10 @@ public static IPointHierarchyXidDAO getPointHierarchyXidDAOBean() { return getBean("pointHierarchyXidDAO", IPointHierarchyXidDAO.class); } + public static IPointLinkDAO getPointLinkDaoBean() { + return getBean("pointLinkDAO", IPointLinkDAO.class); + } + public static IPointValueAdnnotationsDAO getPointValueAdnnotationsDAOBean() { return getBean("pointValueAdnnotationsDAO", IPointValueAdnnotationsDAO.class); } @@ -273,10 +302,58 @@ public static IPointValueAmChartDAO getPointValueAmChartDAOBean() { return getBean("pointValueAmChartDAO", IPointValueAmChartDAO.class); } + public static ICompoundEventDetectorDAO getCompoundEventDetectorDaoBean() { + return getBean("compoundEventDetectorDAO", ICompoundEventDetectorDAO.class); + } + + public static IMaintenanceEventDAO getMaintenanceEventDaoBean() { + return getBean("maintenanceEventDAO", IMaintenanceEventDAO.class); + } + + public static IPublisherDAO getPublisherDaoBean() { + return getBean("publisherDAO", IPublisherDAO.class); + } + + public static IReportDAO getReportDaoBean() { + return getBean("reportDAO", IReportDAO.class); + } + + public static IReportInstanceDAO getReportInstanceDaoBean() { + return getBean("reportInstanceDAO", IReportInstanceDAO.class); + } + + public static IReportInstanceDataDAO getReportInstanceDataDaoBean() { + return getBean("reportInstanceDataDAO", IReportInstanceDataDAO.class); + } + + public static IReportInstancePointDAO getReportInstancePointDaoBean() { + return getBean("reportInstancePointDAO", IReportInstancePointDAO.class); + } + public static IReportInstanceUserCommentDAO getReportInstanceUserCommentDAOBean() { return getBean("reportInstanceUserCommentDAO", IReportInstanceUserCommentDAO.class); } + public static IScheduledEventDAO getScheduledEventDaoBean() { + return getBean("scheduledEventDAO", IScheduledEventDAO.class); + } + + public static IScriptDAO getScriptDaoBean() { + return getBean("scriptDAO", IScriptDAO.class); + } + + public static ISynopticPanelDAO getSynopticPanelDaoBean() { + return getBean("synopticPanelDAO", ISynopticPanelDAO.class); + } + + public static IViewHierarchyDAO getViewHierarchyDaoBean() { + return getBean("viewHierarchyDAO", IViewHierarchyDAO.class); + } + + public static IWatchListDAO getWatchListDaoBean() { + return getBean("watchListDAO", IWatchListDAO.class); + } + public static IAlarmsDAO getAlarmsDAOBean() { return getBean("alarmsDAO", IAlarmsDAO.class); } diff --git a/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java b/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java index 9bff0cdf96..7ceef5fc14 100644 --- a/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java +++ b/test/org/scada_lts/cache/DeletePointHierarchyCacheTest.java @@ -21,8 +21,6 @@ import java.util.Collections; import java.util.List; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @@ -59,7 +57,7 @@ public static Object[][] data() { ), 0, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point2root, folder4root, folder5root, folder6root), + Arrays.asList(folder4root, folder5root, folder6root, point2root), }, new Object[]{ Arrays.asList( @@ -83,7 +81,7 @@ public static Object[][] data() { ), 6, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point8folder6, point9folder6, folder7folder6), + Arrays.asList(folder7folder6, point8folder6, point9folder6), }, new Object[]{ @@ -102,7 +100,7 @@ public static Object[][] data() { ), 0, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point1root, point2root, point3root, folder4root, folder5root, folder6root), + Arrays.asList(folder4root, folder5root, folder6root, point1root, point2root, point3root), }, new Object[]{ Arrays.asList( @@ -142,7 +140,7 @@ public static Object[][] data() { ), 0, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point1root, point2root, folder4root, folder5root, folder6root), + Arrays.asList(folder4root, folder5root, folder6root, point1root, point2root), }, new Object[]{ Arrays.asList( @@ -166,7 +164,7 @@ public static Object[][] data() { ), 6, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point9folder6, folder7folder6), + Arrays.asList(folder7folder6, point9folder6), }, new Object[]{ Arrays.asList( @@ -205,8 +203,8 @@ public void config() throws Exception { Collections.sort(folderHierarchy, PointHierarchyComparator.getInst()); - when(hierarchyDAOMock.getHierarchy()).thenReturn(pointHierarchy); - when(pointHierarchyDAOMock.getPointsHierarchy()).thenReturn(folderHierarchy); + when(hierarchyDAOMock.getHierarchy()).thenReturn(folderHierarchy); + when(pointHierarchyDAOMock.getPointsHierarchy()).thenReturn(pointHierarchy); PowerMockito.whenNew(HierarchyDAO.class) .withAnyArguments() @@ -218,10 +216,10 @@ public void config() throws Exception { PowerMockito.mockStatic(ApplicationBeans.class); - when(ApplicationBeans.getBean(eq("pointHierarchyDAO"), any(Class.class))) - .thenReturn(pointHierarchyDAOMock); when(ApplicationBeans.getHierarchyDAOBean()) .thenReturn(hierarchyDAOMock); + when(ApplicationBeans.getPointHierarchyDaoBean()) + .thenReturn(pointHierarchyDAOMock); this.pointHierarchyCache = new PointHierarchyCache(true); } diff --git a/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java b/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java index 196694392a..3e56ecb5d1 100644 --- a/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java +++ b/test/org/scada_lts/cache/OnBaseParentIdPointHierarchyCacheTest.java @@ -14,7 +14,6 @@ import org.scada_lts.dao.model.pointhierarchy.PointHierarchyComparator; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyDataSource; import org.scada_lts.dao.model.pointhierarchy.PointHierarchyNode; -import org.scada_lts.dao.pointhierarchy.IPointHierarchyDAO; import org.scada_lts.dao.pointhierarchy.PointHierarchyDAO; import org.scada_lts.web.beans.ApplicationBeans; @@ -22,8 +21,6 @@ import java.util.Collections; import java.util.List; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @@ -58,7 +55,7 @@ public static Object[][] data() { 0, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point1root, point2root, point3root, folder4root, folder5root, folder6root), + Arrays.asList(folder4root, folder5root, folder6root, point1root, point2root, point3root), }, new Object[]{ 4, @@ -76,7 +73,7 @@ public static Object[][] data() { 6, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(point8folder6, point9folder6, folder7folder6), + Arrays.asList(folder7folder6, point8folder6, point9folder6), }, new Object[]{ 7, @@ -88,7 +85,7 @@ public static Object[][] data() { 8, Arrays.asList(point1root, point2root, point3root, point4folder4, point5folder4, point6folder5, point7folder5, point8folder6, point9folder6, point10folder7, point11folder7), Arrays.asList(folder4root, folder5root, folder6root, folder7folder6), - Arrays.asList(), + null, }, }; } @@ -117,8 +114,8 @@ public void config() throws Exception { Collections.sort(folderHierarchy, PointHierarchyComparator.getInst()); - when(hierarchyDAOMock.getHierarchy()).thenReturn(pointHierarchy); - when(pointHierarchyDAOMock.getPointsHierarchy()).thenReturn(folderHierarchy); + when(hierarchyDAOMock.getHierarchy()).thenReturn(folderHierarchy); + when(pointHierarchyDAOMock.getPointsHierarchy()).thenReturn(pointHierarchy); whenNew(HierarchyDAO.class) .withAnyArguments() @@ -130,12 +127,10 @@ public void config() throws Exception { PowerMockito.mockStatic(ApplicationBeans.class); - when(ApplicationBeans.getBean( - eq("pointHierarchyDAO"), - (Class) any(Class.class))) - .thenReturn(pointHierarchyDAOMock); when(ApplicationBeans.getHierarchyDAOBean()) .thenReturn(hierarchyDAOMock); + when(ApplicationBeans.getPointHierarchyDaoBean()) + .thenReturn(pointHierarchyDAOMock); this.pointHierarchyCache = new PointHierarchyCache(true); }