From b6b7268377c991026d5139d64160209fcc9f3ec8 Mon Sep 17 00:00:00 2001 From: kamiljarmusik Date: Mon, 1 Jan 2024 23:41:12 +0100 Subject: [PATCH 1/6] #2798 Corrected History Annotation Change Point Value By User --- .../serotonin/mango/rt/RuntimeManager.java | 5 - .../rt/dataImage/AnnotatedPointValueTime.java | 42 ++-- .../rt/dataImage/DataPointNonSyncRT.java | 7 - .../mango/rt/dataImage/DataPointRT.java | 15 -- .../rt/dataImage/DataPointSynchronizedRT.java | 10 - .../mango/rt/dataImage/PointValueCache.java | 51 +---- .../mango/rt/dataImage/PointValueTime.java | 26 +-- .../mango/rt/dataImage/SetPointSource.java | 1 + src/com/serotonin/mango/web/dwr/BaseDwr.java | 9 +- .../mango/web/dwr/DataPointDetailsDwr.java | 45 +---- .../serotonin/mango/web/dwr/EmportDwr.java | 1 + .../mango/web/dwr/beans/ImportTask.java | 2 - src/org/scada_lts/dao/GenericDaoCR.java | 1 - ...tValuesWithAdnotationAboutChangeOwner.java | 7 - .../dao/event/CompoundEventDetectorDAO.java | 5 - src/org/scada_lts/dao/event/EventDAO.java | 5 - src/org/scada_lts/dao/event/UserEventDAO.java | 6 - .../model/point/PointValueAdnnotation.java | 1 + .../dao/pointvalues/IPointValueDAO.java | 75 ++++++++ .../PointValueAdnnotationsDAO.java | 15 +- .../dao/pointvalues/PointValueDAO.java | 171 ++++++++--------- .../dao/pointvalues/PointValueDAO4REST.java | 36 ++-- .../scada_lts/dao/watchlist/WatchListDAO.java | 4 - src/org/scada_lts/login/ILoggedUsers.java | 3 + src/org/scada_lts/login/LoggedUsers.java | 20 ++ .../MangoPointValuesWithChangeOwner.java | 10 - .../mango/service/PointValueService.java | 50 +++-- .../dao/OnlyMigrationWatchListDAO.java | 4 - .../web/beans/GetApplicationBeans.java | 2 +- test/br/org/scadabr/db/utils/TestUtils.java | 17 ++ .../AnnotatedPointValueTimeTest.java | 18 +- .../rt/dataImage/PointValueCacheTest.java | 82 ++++++-- .../rt/dataImage/PointValueFacadeTest.java | 41 ---- .../rt/dataImage/PointValueTimeTest.java | 38 ++-- .../config/ConfigDataPointRtTest.java | 144 +++++++------- ...uteInactiveEventRtUnscheduleEventTest.java | 6 +- .../web/dwr/DataPointDetailsDwrTest.java | 62 ------ .../dao/PointValueAdnnotationDaoTest.java | 2 + test/org/scada_lts/dao/PointValueDAOTest.java | 44 +++-- .../MessagingChannelsMultiThreadTest.java | 6 +- .../channel/MessagingChannelsTest.java | 44 +++-- .../org/scada_lts/utils/ResultSetMock.java | 16 +- test/utils/PointValueDAOMemory.java | 179 ++++++++++++++++-- test/utils/UsersDAOMemory.java | 82 ++++++++ .../mock/ChangePointValueDataPointRtMock.java | 2 +- test/utils/mock/MockUtils.java | 27 ++- 46 files changed, 799 insertions(+), 640 deletions(-) delete mode 100644 src/org/scada_lts/dao/PointValuesWithAdnotationAboutChangeOwner.java create mode 100644 src/org/scada_lts/dao/pointvalues/IPointValueDAO.java delete mode 100644 src/org/scada_lts/mango/adapter/MangoPointValuesWithChangeOwner.java delete mode 100644 test/com/serotonin/mango/rt/dataImage/PointValueFacadeTest.java delete mode 100644 test/com/serotonin/mango/web/dwr/DataPointDetailsDwrTest.java rename src/org/scada_lts/dao/pointvalues/ResultSetImpl.java => test/org/scada_lts/utils/ResultSetMock.java (98%) create mode 100644 test/utils/UsersDAOMemory.java diff --git a/src/com/serotonin/mango/rt/RuntimeManager.java b/src/com/serotonin/mango/rt/RuntimeManager.java index 8eb4ef7945..f21d492a21 100644 --- a/src/com/serotonin/mango/rt/RuntimeManager.java +++ b/src/com/serotonin/mango/rt/RuntimeManager.java @@ -567,11 +567,6 @@ public DataPointListener getDataPointListeners(int dataPointId) { // Point values public void setDataPointValue(int dataPointId, MangoValue value, SetPointSource source) { - if(source instanceof User){ - setDataPointValue(dataPointId, - new PointValueTime(value, System.currentTimeMillis(),((User)source).getUsername()), source); - } - else setDataPointValue(dataPointId, new PointValueTime(value, System.currentTimeMillis()), source); } diff --git a/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java b/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java index 1c5dd2d14e..65bd4e3181 100644 --- a/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java +++ b/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java @@ -19,10 +19,12 @@ package com.serotonin.mango.rt.dataImage; import java.text.MessageFormat; +import java.util.Objects; import java.util.ResourceBundle; import com.serotonin.mango.rt.dataImage.types.MangoValue; import com.serotonin.web.i18n.I18NUtils; +import com.serotonin.web.taglib.DateFunctions; /** * This class provides a way of arbitrarily annotating a PointValue. Point value annotations should not be confused with @@ -56,24 +58,11 @@ public class AnnotatedPointValueTime extends PointValueTime { * @see SetPointSource */ private String sourceDescriptionArgument; - public AnnotatedPointValueTime(String valueChanger,MangoValue value, long time, int sourceType, int sourceId) { - super(value, time); - this.sourceType = sourceType; - this.sourceId = sourceId; - this.sourceDescriptionArgument = valueChanger; - } + public AnnotatedPointValueTime(MangoValue value, long time, int sourceType, int sourceId) { super(value, time); this.sourceType = sourceType; this.sourceId = sourceId; - this.sourceDescriptionArgument = getWhoChangedValue(); - } - public AnnotatedPointValueTime(MangoValue value, long time, int sourceType, int sourceId,String sourceDescription) { - super(value, time); - this.sourceType = sourceType; - this.sourceId = sourceId; - this.sourceDescriptionArgument = sourceDescription; - this.setWhoChangedValue(sourceDescription); } @Override @@ -105,9 +94,6 @@ public String getSourceDescriptionKey() { } public String getSourceDescriptionArgument() { - String EMPTY_STRING = ""; - if(sourceDescriptionArgument.equals( EMPTY_STRING ) ) - setSourceDescriptionArgument(getWhoChangedValue()); return sourceDescriptionArgument; } @@ -122,14 +108,22 @@ public String getAnnotation(ResourceBundle bundle) { return MessageFormat.format(pattern, sourceDescriptionArgument); } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof AnnotatedPointValueTime)) return false; + if (!super.equals(o)) return false; + AnnotatedPointValueTime that = (AnnotatedPointValueTime) o; + return getSourceType() == that.getSourceType() && getSourceId() == that.getSourceId() && Objects.equals(getSourceDescriptionArgument(), that.getSourceDescriptionArgument()); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), getSourceType(), getSourceId(), getSourceDescriptionArgument()); + } + @Override public String toString() { - return new StringBuilder() - .append("AnnotatedPointValueTime{") - .append(" sourceType= ").append(getSourceType()) - .append(" sourceId= ").append(getSourceId()) - .append(" whoChangedValue= ").append(getWhoChangedValue()) - .append(" sourceDescriptionArgument= ").append(getSourceDescriptionArgument()) - .append("}").toString(); + return "AnnotatedPointValueTime(" + sourceDescriptionArgument + " -- " + getValue() + "@" + DateFunctions.getTime(getTime()) + ")"; } } diff --git a/src/com/serotonin/mango/rt/dataImage/DataPointNonSyncRT.java b/src/com/serotonin/mango/rt/dataImage/DataPointNonSyncRT.java index d3e7a08c4b..40feef594c 100644 --- a/src/com/serotonin/mango/rt/dataImage/DataPointNonSyncRT.java +++ b/src/com/serotonin/mango/rt/dataImage/DataPointNonSyncRT.java @@ -64,13 +64,6 @@ public class DataPointNonSyncRT extends DataPointRT implements IDataPointRT { public DataPointNonSyncRT(DataPointVO vo, PointLocatorRT pointLocator) { super(vo, pointLocator); } - public DataPointNonSyncRT(DataPointVO vo, PointLocatorRT pointLocator, int cacheSize, int maxSize) { - super(vo, pointLocator, cacheSize, maxSize); - } - - public DataPointNonSyncRT(DataPointVO vo) { - super(vo); - } @Override protected void savePointValue(PointValueTime newValue, SetPointSource source, diff --git a/src/com/serotonin/mango/rt/dataImage/DataPointRT.java b/src/com/serotonin/mango/rt/dataImage/DataPointRT.java index 61971a2f4b..b74d0dc75e 100644 --- a/src/com/serotonin/mango/rt/dataImage/DataPointRT.java +++ b/src/com/serotonin/mango/rt/dataImage/DataPointRT.java @@ -89,22 +89,7 @@ public DataPointRT(DataPointVO vo, PointLocatorRT pointLocator) { pointValueService = new PointValueService(); dataPointServiceWebSocket = ApplicationBeans.getDataPointServiceWebSocketBean(); } - public DataPointRT(DataPointVO vo, PointLocatorRT pointLocator,int cacheSize,int maxSize) { - this.vo = vo; - this.pointLocator = pointLocator; - valueCache = new PointValueCache(cacheSize); - valueCache.setMaxSize(maxSize); - pointValueService = new PointValueService(); - dataPointServiceWebSocket = ApplicationBeans.getDataPointServiceWebSocketBean(); - } - public DataPointRT(DataPointVO vo) { - this.vo = vo; - this.pointLocator = null; - valueCache = new PointValueCache(); - pointValueService = new PointValueService(); - dataPointServiceWebSocket = ApplicationBeans.getDataPointServiceWebSocketBean(); - } public PointValueCache getPointValueCache(){ return this.valueCache; } diff --git a/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java b/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java index f5104bbb6c..1d10724ebd 100644 --- a/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java +++ b/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java @@ -47,16 +47,6 @@ public DataPointSynchronizedRT(DataPointVO vo, PointLocatorRT pointLocator) { this.pointValueState = PointValueState.empty(); } - public DataPointSynchronizedRT(DataPointVO vo, PointLocatorRT pointLocator, int cacheSize, int maxSize) { - super(vo, pointLocator, cacheSize, maxSize); - this.pointValueState = PointValueState.empty(); - } - - public DataPointSynchronizedRT(DataPointVO vo) { - super(vo); - this.pointValueState = PointValueState.empty(); - } - @Override protected void savePointValue(PointValueTime newValue, SetPointSource source, boolean async) { diff --git a/src/com/serotonin/mango/rt/dataImage/PointValueCache.java b/src/com/serotonin/mango/rt/dataImage/PointValueCache.java index 8a40a3e375..47e4241d20 100644 --- a/src/com/serotonin/mango/rt/dataImage/PointValueCache.java +++ b/src/com/serotonin/mango/rt/dataImage/PointValueCache.java @@ -22,7 +22,6 @@ import java.util.List; import com.serotonin.mango.db.dao.PointValueDao; -import com.serotonin.mango.rt.link.PointLinkRT; import com.serotonin.mango.vo.User; /** @@ -46,17 +45,6 @@ public class PointValueCache { * time, always use a local copy of the variable for read purposes. */ private List cache = new ArrayList(); - public PointValueCache(){ - this.dataPointId = -1; - this.defaultSize = -1; - this.dao=null; - } - - public PointValueCache(int defaultSize) { - this.defaultSize = defaultSize; - this.dataPointId = -1; - this.dao=null; - } public PointValueCache(int dataPointId, int defaultSize) { this.dataPointId = dataPointId; @@ -67,50 +55,25 @@ public PointValueCache(int dataPointId, int defaultSize) { refreshCache(defaultSize); } - /* - those method will proprably used to get information - annotations - from database but..... - */ - /*public String getValuesFromCacheForHistoryTable__(String givenpointValue){ - final String EMPTY_STRING=""; - for(PointValueTime pointValueTime:cache){ - if(((MangoValue)pointValueTime.getValue()).getStringValue().equals(givenpointValue) ) return pointValueTime.getWhoChangedValue(); - } - return EMPTY_STRING; - }*/ - /*public boolean getValuesFromCacheForHistoryTable(String time__,String givenPointValue){ - for(PointValueTime pointValueTime:cache){ - if( ((MangoValue)pointValueTime.getValue()).getStringValue().equals(givenPointValue) ) return true; - } - return false; - }*/ - - public void savePointValueIntoCache(PointValueTime pvt, SetPointSource source, boolean logValue) { - setChangeOwnerIfSourceIsNotEmpty(pvt,source); - } public void savePointValueIntoDaoAndCacheUpdate(PointValueTime pvt, SetPointSource source, boolean logValue, boolean async) { if (logValue) { if (async) dao.savePointValueAsync(dataPointId, pvt, source); else pvt = dao.savePointValueSync(dataPointId, pvt, source); + } + if(!pvt.isAnnotated() && (source instanceof User)) { + User user = (User) source; + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(pvt.getValue(), pvt.getTime(), SetPointSource.Types.USER, user.getId()); + annotatedPointValueTime.setSourceDescriptionArgument(user.getUsername()); + insertPointValueTimeIntoCache(annotatedPointValueTime); + return; } - setChangeOwnerIfSourceIsNotEmpty(pvt,source); insertPointValueTimeIntoCache(pvt); } - private void setChangeOwnerIfSourceIsNotEmpty(PointValueTime pvt, SetPointSource source) { - if(source!=null) - { - if(source instanceof User) - { - - pvt.setWhoChangedValue(((User)source).getUsername()); - } - } - - } private void insertPointValueTimeIntoCache(PointValueTime pvt){ List c = cache; List newCache = new ArrayList(c.size() + 1); diff --git a/src/com/serotonin/mango/rt/dataImage/PointValueTime.java b/src/com/serotonin/mango/rt/dataImage/PointValueTime.java index 79c7ccc179..b96917ea7d 100644 --- a/src/com/serotonin/mango/rt/dataImage/PointValueTime.java +++ b/src/com/serotonin/mango/rt/dataImage/PointValueTime.java @@ -46,7 +46,6 @@ public class PointValueTime implements Serializable, IValueTime, private static final long serialVersionUID = -1; private final MangoValue value; private final long time; - private String whoChangedValue; public static boolean equalValues(PointValueTime pvt1, PointValueTime pvt2) { if (pvt1 == null && pvt2 == null) @@ -67,22 +66,6 @@ public PointValueTime(MangoValue value, long time) { this.time = time; } - public PointValueTime(MangoValue value, long time, String whoChangedValue) { - this.value = value; - this.time = time; - this.whoChangedValue = whoChangedValue; - } - - public String getWhoChangedValue() { - String EMPTY_STRING = ""; - return (whoChangedValue==null)?EMPTY_STRING:whoChangedValue; - - } - - public void setWhoChangedValue(String whoChangedValue) { - this.whoChangedValue = whoChangedValue; - } - public PointValueTime(boolean value, long time) { this(new BinaryValue(value), time); } @@ -150,14 +133,7 @@ public int hashCode() { @Override public String toString() { - return new StringBuilder() - .append("PointValueTime(") - .append(getWhoChangedValue()) - .append(" -- ") - .append(getValue()) - .append("@") - .append(DateFunctions.getTime(time)) - .append(")").toString(); + return "PointValueTime(" + value + "@" + DateFunctions.getTime(time) + ")"; } @Override diff --git a/src/com/serotonin/mango/rt/dataImage/SetPointSource.java b/src/com/serotonin/mango/rt/dataImage/SetPointSource.java index 0f0083a6b9..c24c8df575 100644 --- a/src/com/serotonin/mango/rt/dataImage/SetPointSource.java +++ b/src/com/serotonin/mango/rt/dataImage/SetPointSource.java @@ -34,6 +34,7 @@ public interface Types { int ANONYMOUS = 3; int POINT_LINK = 4; int UNKNOWN = 5; + int API = 6; } public int getSetPointSourceType(); diff --git a/src/com/serotonin/mango/web/dwr/BaseDwr.java b/src/com/serotonin/mango/web/dwr/BaseDwr.java index 4d8e003388..40c6856c53 100644 --- a/src/com/serotonin/mango/web/dwr/BaseDwr.java +++ b/src/com/serotonin/mango/web/dwr/BaseDwr.java @@ -249,14 +249,7 @@ else if (typeId == UserComment.TYPE_POINT) return c; } - protected String getOwnerNameOfChangePointValue(String pointvalue){ - PointValueAdnnotationsDAO p = new PointValueAdnnotationsDAO(); - //PointValueCache pvc = new PointValueCache(); - //point - UserDao userDao = new UserDao(); - User a =userDao.getUser(1); - return a.getUsername(); - } + protected List getReadablePoints() { User user = Common.getUser(); diff --git a/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java b/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java index d8e481e67d..1f09f51820 100644 --- a/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java @@ -80,56 +80,20 @@ public WatchListState getPointData() { return state; } - public boolean doThisAnnotationExist(String annotation,PointValueFacade facade,int limit){ - boolean result=false; - List pointValueTimes = facade.getLatestPointValues(limit); - List renderedData = new ArrayList(pointValueTimes.size()); - for (PointValueTime pvt : pointValueTimes) { - RenderedPointValueTime rpvt = new RenderedPointValueTime(); - rpvt.setTime(Functions.getTime(pvt)); - AnnotatedPointValueTime apvt = new AnnotatedPointValueTime(pvt.getWhoChangedValue(),pvt.getValue(),pvt.getTime(), 2,2); - apvt.getSourceDescriptionArgument(); - result = apvt.getSourceDescriptionArgument().equals(annotation); - - if (result ) - return result; - } - return result; - } - private List renderData(List rawData, DataPointVO pointVO){ - - List renderedData = new ArrayList(rawData.size()); - - for (PointValueTime pvt : rawData) { - RenderedPointValueTime rpvt = new RenderedPointValueTime(); - rpvt.setValue(Functions.getHtmlText(pointVO, pvt)); - rpvt.setTime(Functions.getTime(pvt)); - - if (pvt.isAnnotated()) { - AnnotatedPointValueTime apvt = (AnnotatedPointValueTime) pvt; - rpvt.setAnnotation((apvt.getSourceDescriptionArgument() == null) - ?apvt.getSourceDescriptionArgument() - :apvt.getAnnotation(getResourceBundle())); - } - renderedData.add(rpvt); - } - - return renderedData; - } public DwrResponseI18n getHistoryTableData(int limit) { DataPointVO pointVO = Common.getUser().getEditPoint(); PointValueFacade facade = new PointValueFacade(pointVO.getId()); List rawData = facade.getLatestPointValues(limit); - List renderedData = renderData(rawData,pointVO); - /* + List renderedData = new ArrayList<>(); + for (PointValueTime pvt : rawData) { RenderedPointValueTime rpvt = new RenderedPointValueTime(); rpvt.setValue(Functions.getHtmlText(pointVO, pvt)); rpvt.setTime(formatDateTime(pvt)); - if (pvt.isAnnotated()) { + if (pvt != null && pvt.isAnnotated()) { AnnotatedPointValueTime apvt = (AnnotatedPointValueTime) pvt; if (apvt.getSourceDescriptionArgument() == null) { rpvt.setAnnotation(apvt.getSourceDescriptionArgument()); @@ -139,9 +103,6 @@ public DwrResponseI18n getHistoryTableData(int limit) { } renderedData.add(rpvt); } - - */ - DwrResponseI18n response = new DwrResponseI18n(); response.addData("history", renderedData); addAsof(response); diff --git a/src/com/serotonin/mango/web/dwr/EmportDwr.java b/src/com/serotonin/mango/web/dwr/EmportDwr.java index 635a882653..18f2e44356 100644 --- a/src/com/serotonin/mango/web/dwr/EmportDwr.java +++ b/src/com/serotonin/mango/web/dwr/EmportDwr.java @@ -230,6 +230,7 @@ public static DwrResponseI18n importDataImpl(String data, JsonObject root = value.toJsonObject(); ImportTask importTask = new ImportTask(reader, root, bundle, user); + Common.ctx.getBackgroundProcessing().addWorkItem(importTask); user.setImportTask(importTask); response.addData("importStarted", true); } else { diff --git a/src/com/serotonin/mango/web/dwr/beans/ImportTask.java b/src/com/serotonin/mango/web/dwr/beans/ImportTask.java index 66211afaab..c7648c0788 100644 --- a/src/com/serotonin/mango/web/dwr/beans/ImportTask.java +++ b/src/com/serotonin/mango/web/dwr/beans/ImportTask.java @@ -173,8 +173,6 @@ public ImportTask(JsonReader reader, JsonObject root, systemSettings = nonNullList(root, EmportDwr.SYSTEM_SETTINGS); usersProfiles = nonNullList(root, EmportDwr.USERS_PROFILES); reports = nonNullList(root, EmportDwr.REPORTS); - - Common.ctx.getBackgroundProcessing().addWorkItem(this); } private void preloadDataPoints() { diff --git a/src/org/scada_lts/dao/GenericDaoCR.java b/src/org/scada_lts/dao/GenericDaoCR.java index b3fe826414..c11e62963d 100644 --- a/src/org/scada_lts/dao/GenericDaoCR.java +++ b/src/org/scada_lts/dao/GenericDaoCR.java @@ -32,7 +32,6 @@ public interface GenericDaoCR { static final String LIMIT = " LIMIT "; static final int NO_LIMIT = 0; - List findAllWithUserName(); List findAll(); /** diff --git a/src/org/scada_lts/dao/PointValuesWithAdnotationAboutChangeOwner.java b/src/org/scada_lts/dao/PointValuesWithAdnotationAboutChangeOwner.java deleted file mode 100644 index 67960fee3a..0000000000 --- a/src/org/scada_lts/dao/PointValuesWithAdnotationAboutChangeOwner.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.scada_lts.dao; - -import java.util.List; - -public interface PointValuesWithAdnotationAboutChangeOwner { - List findAllWithAdnotationsAboutChangeOwner(); -} diff --git a/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java b/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java index 99ced43b0a..48a7bcfdf1 100644 --- a/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java +++ b/src/org/scada_lts/dao/event/CompoundEventDetectorDAO.java @@ -133,11 +133,6 @@ public CompoundEventDetectorVO mapRow(ResultSet rs, int rowNum) throws SQLExcept } } - @Override - public List findAllWithUserName() { - return null; - } - @Override public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(COMPOUND_EVENT_DETECTOR_SELECT+" order by name", new Object[]{}, new CompoundEventDetectorRowMapper()); diff --git a/src/org/scada_lts/dao/event/EventDAO.java b/src/org/scada_lts/dao/event/EventDAO.java index 9e84998093..49f34a3707 100644 --- a/src/org/scada_lts/dao/event/EventDAO.java +++ b/src/org/scada_lts/dao/event/EventDAO.java @@ -876,11 +876,6 @@ public SQLPageWithTotal findEvents( return new SQLPageWithTotal<>(page, total); } - @Override - public List findAllWithUserName() { - return null; - } - @Override public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(BASIC_EVENT_SELECT, new Object[]{ }, new EventRowMapper()); diff --git a/src/org/scada_lts/dao/event/UserEventDAO.java b/src/org/scada_lts/dao/event/UserEventDAO.java index ba79c422ed..9af44795cb 100644 --- a/src/org/scada_lts/dao/event/UserEventDAO.java +++ b/src/org/scada_lts/dao/event/UserEventDAO.java @@ -137,12 +137,6 @@ public UserEvent mapRow(ResultSet rs, int rowNum) throws SQLException { } } - - @Override - public List findAllWithUserName() { - return null; - } - @Override public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(USER_EVENT_SELECT, new Object[]{ }, new UserEventRowMapper()); diff --git a/src/org/scada_lts/dao/model/point/PointValueAdnnotation.java b/src/org/scada_lts/dao/model/point/PointValueAdnnotation.java index 205aaaeb18..3b599c83b8 100644 --- a/src/org/scada_lts/dao/model/point/PointValueAdnnotation.java +++ b/src/org/scada_lts/dao/model/point/PointValueAdnnotation.java @@ -23,6 +23,7 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ +@Deprecated public class PointValueAdnnotation { diff --git a/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java b/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java new file mode 100644 index 0000000000..8bd8801deb --- /dev/null +++ b/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java @@ -0,0 +1,75 @@ +package org.scada_lts.dao.pointvalues; + +import com.serotonin.mango.rt.dataImage.PointValueTime; +import com.serotonin.mango.vo.bean.LongPair; +import com.serotonin.mango.vo.bean.PointHistoryCount; +import org.scada_lts.dao.model.point.PointValue; +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 IPointValueDAO { + List findAll(); + + PointValue findById(Object[] pk); + + List findByIdAndTs(long id, long ts); + + List filtered(String filter, Object[] argsFilter, long limit); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + Object[] create(PointValue entity); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + Object[] create(int pointId, int dataType, double dvalue, long time); + + Object[] createNoTransaction(int pointId, int dataType, double dvalue, long time); + + @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, rollbackFor = SQLException.class) + void executeBatchUpdateInsert(List params); + + Long getInceptionDate(int dataPointId); + + long dateRangeCount(int dataPointId, long from, long to); + + LongPair getStartAndEndTime(List dataPointIds); + + long getStartTime(List dataPointIds); + + long getEndTime(List dataPointIds); + + List getFiledataIds(); + + Long getLatestPointValue(int dataPointId); + + // Apply database specific bounds on double values. + double applyBounds(double value); + + @Deprecated + long deletePointValuesBeforeWithOutLast(int dataPointId, long time); + + long deletePointValuesBeforeWithOutLastTwo(int dataPointId, long time); + + long deletePointValue(int dataPointId); + + long deleteAllPointData(); + + long deletePointValuesWithMismatchedType(int dataPointId, int dataType); + + long deletePointValuesWithValueLimit(int dataPointId, int limit); + + PointValueTime getPointValue(long id); + + long getMinTs(int dataPointId); + + long getMaxTs(int dataPointId); + + List getTopPointHistoryCounts(); + + int createAnnotation(long pointValueId, String textPointValueShort, String textPointValueLong, int sourceType, int sourceId); + + void updateAnnotation(int userId); +} diff --git a/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java b/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java index 462c46fc36..aa7272c3cb 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueAdnnotationsDAO.java @@ -29,7 +29,6 @@ import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.DAO; import org.scada_lts.dao.GenericDaoCR; -import org.scada_lts.dao.PointValuesWithAdnotationAboutChangeOwner; import org.scada_lts.dao.model.point.PointValue; import org.scada_lts.dao.model.point.PointValueAdnnotation; import org.springframework.jdbc.core.RowMapper; @@ -45,7 +44,9 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ -public class PointValueAdnnotationsDAO implements GenericDaoCR, PointValuesWithAdnotationAboutChangeOwner { + +@Deprecated +public class PointValueAdnnotationsDAO implements GenericDaoCR { private static final Log LOG = LogFactory.getLog(PointValueAdnnotationsDAO.class); @@ -139,16 +140,6 @@ public static PointValueAdnnotationsDAO getInstance() { return instance; } - @Override - public List findAllWithAdnotationsAboutChangeOwner() { - return (List) DAO.getInstance().getJdbcTemp().query(POINT_VALUE_ADNNOTATIONS_SELECT_WITH_OWNER_OF_CHANGE, new Object[]{ }, new PointValueAdnnotationRowMapperWithAdnnotationAboutChangeOwner()); - } - - @Override - public List findAllWithUserName() { - return null; - } - @Override public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(POINT_VALUE_ADNNOTATIONS_SELECT_WITH_OWNER_OF_CHANGE/*POINT_VALUE_ADNNOTATIONS_SELECT*/, new Object[]{ }, new PointValueAdnnotationRowMapper()); diff --git a/src/org/scada_lts/dao/pointvalues/PointValueDAO.java b/src/org/scada_lts/dao/pointvalues/PointValueDAO.java index 16fc28528a..e337607942 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueDAO.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueDAO.java @@ -25,6 +25,7 @@ import java.sql.Statement; import java.util.List; +import com.serotonin.mango.rt.dataImage.SetPointSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scada_lts.dao.DAO; @@ -61,7 +62,7 @@ * */ @Repository -public class PointValueDAO implements GenericDaoCR { +public class PointValueDAO implements GenericDaoCR, IPointValueDAO { private static final Log LOG = LogFactory.getLog(PointValueDAO.class); @@ -301,7 +302,8 @@ public class PointValueDAO implements GenericDaoCR { // @formatter:on //RowMappers - private class PointValueRowMapper implements RowMapper { + public static class PointValueRowMapper implements RowMapper { + public PointValue mapRow(ResultSet rs, int rowNum) throws SQLException { //TODO rewrite MangoValue MangoValue value = createMangoValue(rs); @@ -310,74 +312,17 @@ public PointValue mapRow(ResultSet rs, int rowNum) throws SQLException { PointValue pv = new PointValue(); pv.setId(rs.getLong(COLUMN_NAME_ID)); pv.setDataPointId(rs.getInt(COLUMN_NAME_DATA_POINT_ID)); - int sourceId = rs.getInt(COLUMN_NAME_SOURCE_ID); - int sourceType = rs.getInt(COLUMN_NAME_SOURCE_TYPE); if (rs.wasNull()) { pv.setPointValue(new PointValueTime(value, time)); } else { + int sourceId = rs.getInt(COLUMN_NAME_SOURCE_ID); pv.setPointValue(new AnnotatedPointValueTime(value, time, sourceType, sourceId)); } return pv; } } - public PointValue getPointValueRow(ResultSet rs, int rowNum){ - try { - return new PointValueRowMapperWithUserName().mapRow(rs, rowNum); - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - private class PointValueRowMapperWithUserName implements RowMapper { - - public PointValue mapRow(ResultSet rs, int rowNum) throws SQLException { - //TODO rewrite MangoValue - MangoValue value = createMangoValue(rs); - long time = rs.getLong(COLUMN_NAME_TIME_STAMP); - - PointValue pv = new PointValue(); - pv.setId(rs.getLong(COLUMN_NAME_ID)); - pv.setDataPointId(rs.getInt(COLUMN_NAME_DATA_POINT_ID)); - int sourceId = rs.getInt(COLUMN_NAME_SOURCE_ID); - - int sourceType = rs.getInt(COLUMN_NAME_SOURCE_TYPE); - int username = -1; - String userName = null; - try{ - username = rs.getInt(COLUMN_NAME_USERNAME_IN_TABLE_USERS); - } - catch (Exception e){ - - userName = rs.getString(COLUMN_NAME_USERNAME_IN_TABLE_USERS); - } - - pv.setPointValue( rs.wasNull() - ? createPointValueTime( userName, value, time, username ) - : createAnnotatedPointValueTime( value,time, sourceType, sourceId, userName )); - - return pv; - } - private AnnotatedPointValueTime createAnnotatedPointValueTime(MangoValue value, long time, int sourceType, int sourceId, String userName){ - return ( userName!= null ) - ?new AnnotatedPointValueTime(value, time, sourceType, sourceId, userName) - :new AnnotatedPointValueTime(value, time, sourceType, sourceId); - } - private PointValueTime createPointValueTime(String userName, MangoValue value, long time, int username ){ - - if(userName!= null){ - return new PointValueTime(value, time,userName); - } - else if( username!=0 ){ - return new PointValueTime(value, time,String.valueOf(username)); - } - else { - return new PointValueTime(value, time); - } - - } - } private class LongPairRowMapper implements RowMapper { public LongPair mapRow(ResultSet rs, int index) throws SQLException { @@ -395,7 +340,7 @@ public Long mapRow(ResultSet rs, int index) throws SQLException { } //TODO rewrite for new types - MangoValue createMangoValue(ResultSet rs) + static MangoValue createMangoValue(ResultSet rs) throws SQLException { int dataType = rs.getInt(COLUMN_NAME_DATA_TYPE); @@ -438,10 +383,7 @@ public static PointValueDAO getInstance() { } return instance; } - @Override - public List findAllWithUserName(){ - return (List) DAO.getInstance().getJdbcTemp().query(POINT_VALUE_SELECT_WITH_USERNAME, new Object[]{ }, new PointValueRowMapper()); - } + @Override public List findAll() { @@ -453,6 +395,7 @@ public PointValue findById(Object[] pk) { return (PointValue) DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_SELECT_ON_BASE_ID, pk, new PointValueRowMapper()); } + @Override public List findByIdAndTs(long id, long ts) { return DAO.getInstance().getJdbcTemp().query(POINT_VALUE_SELECT_ON_BASE_ID_TS, new Object[] { id,ts }, new PointValueRowMapper()); } @@ -464,24 +407,7 @@ public List filtered(String filter, Object[] argsFilter, long limit) //TODO rewrite limit adding in argsFilter myLimit = LIMIT+limit; } - List res = - (List) DAO.getInstance().getJdbcTemp().query( - "select " - + "pv."+COLUMN_NAME_ID + "," - + "pv."+COLUMN_NAME_DATA_POINT_ID + ", " - + "pv."+COLUMN_NAME_DATA_TYPE + ", " - + "pv."+COLUMN_NAME_POINT_VALUE + ", " - + "pv."+COLUMN_NAME_TIME_STAMP + ", " - + "pva."+COLUMN_NAME_TEXT_POINT_VALUE_SHORT + ", " - + "pva."+COLUMN_NAME_TEXT_POINT_VALUE_LONG + ", " - + "pva."+COLUMN_NAME_SOURCE_TYPE + ", " - + "pva."+COLUMN_NAME_SOURCE_ID + ", " - + "us." +COLUMN_NAME_USERNAME_IN_TABLE_USERS - + " from " - + "pointValues pv " - + "left join pointValueAnnotations pva on pv.id=pva.pointValueId " - + "left join users us on pva.sourceId = us.id " +" where "+ filter + myLimit, argsFilter, new PointValueRowMapperWithUserName()); - return res; + return (List) DAO.getInstance().getJdbcTemp().query(POINT_VALUE_SELECT+" where "+ filter + myLimit, argsFilter, new PointValueRowMapper()); } @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) @@ -512,15 +438,17 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S } + @Override @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) - public Object[] create(final int pointId,final int dataType,final double dvalue,final long time) { + public Object[] create(final int pointId, final int dataType, final double dvalue, final long time) { return createNoTransaction(pointId, dataType, dvalue, time); } - public Object[] createNoTransaction(final int pointId,final int dataType,final double dvalue,final long time) { + @Override + public Object[] createNoTransaction(final int pointId, final int dataType, final double dvalue, final long time) { if (LOG.isTraceEnabled()) { LOG.trace("pointId:"+pointId+" dataType:"+dataType+" dvalue:"+time); @@ -547,8 +475,9 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S + @Override @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) - public void executeBatchUpdateInsert( List params) { + public void executeBatchUpdateInsert(List params) { if (LOG.isTraceEnabled()) { for (Object[] param : params) { for (Object arg :param) { @@ -561,14 +490,17 @@ public void executeBatchUpdateInsert( List params) { } + @Override public Long getInceptionDate(int dataPointId) { return DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_INCEPTION_DATA, new Object[] {dataPointId}, Long.class); } + @Override public long dateRangeCount(int dataPointId, long from, long to) { return DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_DATA_RANGE_COUNT, new Object[] {dataPointId, from, to}, Long.class); } + @Override public LongPair getStartAndEndTime(List dataPointIds) { if (dataPointIds.isEmpty()) return null; @@ -580,6 +512,7 @@ public LongPair getStartAndEndTime(List dataPointIds) { return longPair; } + @Override public long getStartTime(List dataPointIds) { if (dataPointIds.isEmpty()) return -1; @@ -591,6 +524,7 @@ public long getStartTime(List dataPointIds) { return minTs; } + @Override public long getEndTime(List dataPointIds) { if (dataPointIds.isEmpty()) return -1; MapSqlParameterSource parameters = new MapSqlParameterSource(); @@ -602,6 +536,7 @@ public long getEndTime(List dataPointIds) { } + @Override public List getFiledataIds() { //TODO rewrite return DAO.getInstance().getJdbcTemp().queryForList( @@ -616,6 +551,7 @@ public List getFiledataIds() { + ") a order by 1", new Object[] {}, Long.class); } + @Override public Long getLatestPointValue(int dataPointId) { try { return DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_SELECT_MAX_BASE_ON_DATA_POINT_ID, new Object[] {dataPointId}, Long.class); @@ -641,7 +577,8 @@ private double getValueBaseOnType(int dataType, PointValueTime value) { } // Apply database specific bounds on double values. - public double applyBounds(double value) { + @Override + public double applyBounds(double value) { if (Double.isNaN(value)) return 0; if (value == Double.POSITIVE_INFINITY) @@ -652,44 +589,54 @@ public double applyBounds(double value) { return value; } + @Override @Deprecated public long deletePointValuesBeforeWithOutLast(int dataPointId, long time) { Long lastId = DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_ID_OF_LAST_VALUE, new Object[] { dataPointId }, Long.class ); return DAO.getInstance().getJdbcTemp().update(POINT_VALUE_DELETE_BEFORE, new Object[] {dataPointId, time, lastId}); } + @Override public long deletePointValuesBeforeWithOutLastTwo(int dataPointId, long time) { return DAO.getInstance().getJdbcTemp().update(POINT_VALUE_DELETE_BEFORE_WITHOUT_LAST_TWO, new Object[] {dataPointId, dataPointId, time}); } - public long deletePointValue(int dataPointId) { + @Override + public long deletePointValue(int dataPointId) { return DAO.getInstance().getJdbcTemp().update(POINT_VALUE_DELETE_BASE_ON_POINT_ID, new Object[] {dataPointId}); } - public long deleteAllPointData() { + @Override + public long deleteAllPointData() { return DAO.getInstance().getJdbcTemp().update(POINT_VALUE_DELETE, new Object[] {}); } - public long deletePointValuesWithMismatchedType(int dataPointId, int dataType) { + @Override + public long deletePointValuesWithMismatchedType(int dataPointId, int dataType) { return DAO.getInstance().getJdbcTemp().update(DELETE_POINT_VALUE_WITH_MISMATCHED_TYPE, new Object[] {dataPointId, dataType}); } + @Override public long deletePointValuesWithValueLimit(int dataPointId, int limit){ return DAO.getInstance().getJdbcTemp().update(DELETE_POINT_VALUE_BASED_ON_DATAPOINT_WITH_VALUE_LIMIT, new Object[] {dataPointId, dataPointId, limit}); } - public PointValueTime getPointValue(long id) { + @Override + public PointValueTime getPointValue(long id) { return ((PointValue) DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_SELECT + " where " + POINT_VALUE_FILTER_BASE_ON_ID, new Object[] {id}, new PointValueRowMapper())).getPointValue(); } + @Override public long getMinTs(int dataPointId) { return DAO.getInstance().getJdbcTemp().queryForObject(SELECT_MIN_TIME_WHERE_DATA_POINT_ID, new Object[] {dataPointId}, Long.TYPE); } + @Override public long getMaxTs(int dataPointId) { return DAO.getInstance().getJdbcTemp().queryForObject(SELECT_MAX_TIME_WHERE_DATA_POINT_ID, new Object[] {dataPointId}, Long.TYPE); } + @Override public List getTopPointHistoryCounts() { return DAO.getInstance().getJdbcTemp().query(SELECT_DP_ID_AND_COUNT, new RowMapper() { @Override @@ -701,4 +648,46 @@ public PointHistoryCount mapRow(ResultSet rs, int rowNum) throws SQLException { } }); } + + private static final String POINT_VALUE_ADNNOTATIONS_INSERT = "" + + "insert pointValueAnnotations (" + + COLUMN_NAME_POINT_VALUE_ID + "," + + COLUMN_NAME_TEXT_POINT_VALUE_SHORT + "," + + COLUMN_NAME_TEXT_POINT_VALUE_LONG + "," + + COLUMN_NAME_SOURCE_TYPE + "," + + COLUMN_NAME_SOURCE_ID + +") " + + "values (?,?,?,?,?)"; + + @Override + public int createAnnotation(long pointValueId, String textPointValueShort, String textPointValueLong, + int sourceType, int sourceId) { + return DAO.getInstance().getJdbcTemp().update(POINT_VALUE_ADNNOTATIONS_INSERT, new Object[] { + pointValueId, + textPointValueShort, + textPointValueLong, + sourceType, + sourceId + }); + } + + private static final String POINT_VALUE_ANNOTATIONS_UPDATE = "" + + "update pointValueAnnotations set " + + COLUMN_NAME_SOURCE_ID + "=null " + + "where " + + COLUMN_NAME_SOURCE_ID + "=? " + + "and " + + COLUMN_NAME_SOURCE_TYPE + "=" + + SetPointSource.Types.USER; + + @Override + @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) + public void updateAnnotation(int userId) { + + if (LOG.isTraceEnabled()) { + LOG.trace("update(int userId) userId:" + userId); + } + + DAO.getInstance().getJdbcTemp().update(POINT_VALUE_ANNOTATIONS_UPDATE, new Object[]{userId}); + } } \ No newline at end of file diff --git a/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java b/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java index db7db5044b..35112e6717 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java @@ -20,17 +20,18 @@ import java.sql.SQLException; import java.util.Date; +import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; +import com.serotonin.mango.rt.dataImage.SetPointSource; +import com.serotonin.mango.rt.dataImage.types.MangoValue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.DAO; -import org.scada_lts.dao.model.point.PointValueAdnnotation; import org.scada_lts.dao.model.point.PointValueTypeOfREST; +import org.scada_lts.mango.service.PointValueService; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import com.serotonin.mango.DataTypes; import com.serotonin.mango.rt.dataImage.PointValueTime; /** @@ -77,30 +78,15 @@ public PointValueTime save(String value, int typePointValueOfREST, int dpid) { new RuntimeException("Value not compatible with type (double)"); } } else if (typePointValueOfREST==PointValueTypeOfREST.TYPE_STRING) { - - pvt = new PointValueTime(value, new Date().getTime() ); - Object[] resultPointValue = new PointValueDAO().createNoTransaction(dpid, DataTypes.ALPHANUMERIC, 0, new Date().getTime()); - PointValueAdnnotation pva = new PointValueAdnnotation(); - Long pointValueId = (Long) resultPointValue[0]; - pva.setPointValueId(pointValueId); - pva.setSourceType(DataTypes.ALPHANUMERIC); - - int lengthShortValue = 128; - if (value.length()<=lengthShortValue) { - pva.setTextPointValueShort(value); - } else { - pva.setTextPointValueLong(value); - } - - new PointValueAdnnotationsDAO().create(pva); - - if (LOG.isTraceEnabled()) { - LOG.trace("save data string:" + dpid); - } - + pvt = new AnnotatedPointValueTime(MangoValue.objectToValue(value), new Date().getTime(), SetPointSource.Types.API, 0); } else { new RuntimeException("Unknown value type"); - } + } + + if(pvt != null) { + PointValueService pointValueService = new PointValueService(); + pointValueService.savePointValue(dpid, pvt); + } return pvt; } diff --git a/src/org/scada_lts/dao/watchlist/WatchListDAO.java b/src/org/scada_lts/dao/watchlist/WatchListDAO.java index 287b0900f3..9f2fb3cbab 100644 --- a/src/org/scada_lts/dao/watchlist/WatchListDAO.java +++ b/src/org/scada_lts/dao/watchlist/WatchListDAO.java @@ -311,10 +311,6 @@ public ShareUser mapRow(ResultSet rs, int rowNum) throws SQLException { } } @Override - public List findAllWithUserName(){ - return null; - } - @Override public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(WATCH_LIST_SELECT_ORDER_BY_NAME, new Object[] {}, new WatchListRowMapper()); } diff --git a/src/org/scada_lts/login/ILoggedUsers.java b/src/org/scada_lts/login/ILoggedUsers.java index 90b32a2970..1c548e63f3 100644 --- a/src/org/scada_lts/login/ILoggedUsers.java +++ b/src/org/scada_lts/login/ILoggedUsers.java @@ -4,6 +4,7 @@ import com.serotonin.mango.vo.User; import javax.servlet.http.HttpSession; +import java.util.Collection; import java.util.Set; public interface ILoggedUsers { @@ -12,4 +13,6 @@ public interface ILoggedUsers { void updateUsers(UsersProfileVO profile); User removeUser(User user, HttpSession session); Set getUserIds(); + Collection getUsers(); + User getUser(int id); } diff --git a/src/org/scada_lts/login/LoggedUsers.java b/src/org/scada_lts/login/LoggedUsers.java index 18eb58153e..6f67fe10c8 100644 --- a/src/org/scada_lts/login/LoggedUsers.java +++ b/src/org/scada_lts/login/LoggedUsers.java @@ -100,6 +100,26 @@ public Set getUserIds() { } } + @Override + public Collection getUsers() { + lock.readLock().lock(); + try { + return loggedUsers.values(); + } finally { + lock.readLock().unlock(); + } + } + + @Override + public User getUser(int id) { + lock.readLock().lock(); + try { + return loggedUsers.get(id); + } finally { + lock.readLock().unlock(); + } + } + private static void update(User user, Map loggedUsers, Map> loggedSessions, ThreadLocal blocked) { diff --git a/src/org/scada_lts/mango/adapter/MangoPointValuesWithChangeOwner.java b/src/org/scada_lts/mango/adapter/MangoPointValuesWithChangeOwner.java deleted file mode 100644 index 6d49b1aa3c..0000000000 --- a/src/org/scada_lts/mango/adapter/MangoPointValuesWithChangeOwner.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.scada_lts.mango.adapter; - -import org.scada_lts.dao.model.point.PointValueAdnnotation; - -import java.util.List; - -public interface MangoPointValuesWithChangeOwner { - - List findAllWithAdnotationsAboutChangeOwner(); -} diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index 276854d2d7..8b28502864 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -44,11 +44,9 @@ 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.model.point.PointValueAdnnotation; -import org.scada_lts.dao.pointvalues.PointValueAdnnotationsDAO; import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.mango.adapter.MangoPointValues; -import org.scada_lts.mango.adapter.MangoPointValuesWithChangeOwner; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; @@ -73,12 +71,12 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu */ @Service -public class PointValueService implements MangoPointValues, MangoPointValuesWithChangeOwner { +public class PointValueService implements MangoPointValues { private static List UNSAVED_POINT_VALUES = new ArrayList(); private static final int POINT_VALUE_INSERT_VALUES_COUNT = 4; - private static PointValueAdnnotationsDAO pointValueAnnotationsDAO = new PointValueAdnnotationsDAO(); + private PointValueDAO pointValueDAO = new PointValueDAO(); private DataPointService dataPointService = new DataPointService(); private DataSourceService dataSourceService = new DataSourceService(); @@ -88,10 +86,6 @@ public PointValueService() { } - @Override - public List findAllWithAdnotationsAboutChangeOwner(){ - return pointValueAnnotationsDAO.findAllWithAdnotationsAboutChangeOwner(); - } /** * Only the PointValueCache should call this method during runtime. Do not * use. @@ -307,8 +301,7 @@ private long savePointValueImpl(int pointId, int dataType, double dvalue, long t else shortString = svalue; } - PointValueAdnnotation pointValueAdnnotation = new PointValueAdnnotation(id, shortString, longString, sourceType, sourceId); - PointValueAdnnotationsDAO.getInstance().create(pointValueAdnnotation); + PointValueDAO.getInstance().createAnnotation(id, shortString, longString, sourceType, sourceId); } @@ -321,6 +314,9 @@ private List getLstPointValueTime(List lstIn) { for (PointValue pv : lstIn) { lst.add(pv.getPointValue()); + if(pv.getPointValue() instanceof AnnotatedPointValueTime) { + updateAnnotation((AnnotatedPointValueTime) pv.getPointValue()); + } } return lst; } @@ -363,9 +359,13 @@ public PointValueTime getLatestPointValue(int dataPointId) { List lstValues = PointValueDAO.getInstance().findByIdAndTs(dataPointId, maxTs); - PointValueAdnnotationsDAO.getInstance().updateAnnotations(lstValues); if (lstValues.size() == 0) return null; + + PointValueTime pointValue = lstValues.get(0).getPointValue(); + if(pointValue instanceof AnnotatedPointValueTime) { + updateAnnotation((AnnotatedPointValueTime) pointValue); + } return lstValues.get(0).getPointValue(); } @@ -634,14 +634,15 @@ public String getDetails() { } public PointValueTime getPointValue(long id) { - return PointValueDAO.getInstance().getPointValue(id); - } - public List getAllPointValueAnnotations(){ - return pointValueAnnotationsDAO.findAll(); + PointValueTime pointValueTime = PointValueDAO.getInstance().getPointValue(id); + if(pointValueTime instanceof AnnotatedPointValueTime) { + updateAnnotation((AnnotatedPointValueTime) pointValueTime); + } + return pointValueTime; } public void updatePointValueAnnotations(int userId) { - pointValueAnnotationsDAO.update(userId); + pointValueDAO.updateAnnotation(userId); } @Override @@ -752,5 +753,20 @@ public void updateAllMetaDataPointsByScript(User user) { .forEach(dp -> updateMetaDataPointByScript(user, dp.getXid())); } + + private void updateAnnotation(AnnotatedPointValueTime annotatedPointValueTime) { + int sourceType = annotatedPointValueTime.getSourceType(); + int sourceId = annotatedPointValueTime.getSourceId(); + if (sourceType == SetPointSource.Types.USER && sourceId > 0) { + User user = ApplicationBeans.getLoggedUsersBean().getUser(sourceId); + if (user == null) { + user = ApplicationBeans.getUserDaoBean().getUser(sourceId); + } + if (user != null) { + String username = user.getUsername(); + annotatedPointValueTime.setSourceDescriptionArgument(username); + } + } + } } diff --git a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationWatchListDAO.java b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationWatchListDAO.java index ce8875dd06..6dc5dca856 100644 --- a/src/org/scada_lts/permissions/migration/dao/OnlyMigrationWatchListDAO.java +++ b/src/org/scada_lts/permissions/migration/dao/OnlyMigrationWatchListDAO.java @@ -280,10 +280,6 @@ public ShareUser mapRow(ResultSet rs, int rowNum) throws SQLException { } } @Override - public List findAllWithUserName(){ - return null; - } - @Override public List findAll() { return (List) DAO.getInstance().getJdbcTemp().query(WATCH_LIST_SELECT_ORDER_BY_NAME, new Object[] {}, new WatchListRowMapper()); } diff --git a/src/org/scada_lts/web/beans/GetApplicationBeans.java b/src/org/scada_lts/web/beans/GetApplicationBeans.java index 1150c82518..992c5dc6aa 100644 --- a/src/org/scada_lts/web/beans/GetApplicationBeans.java +++ b/src/org/scada_lts/web/beans/GetApplicationBeans.java @@ -4,7 +4,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -class GetApplicationBeans implements ApplicationContextAware { +public class GetApplicationBeans implements ApplicationContextAware { private static ApplicationContext applicationContext; diff --git a/test/br/org/scadabr/db/utils/TestUtils.java b/test/br/org/scadabr/db/utils/TestUtils.java index 35aaf64ebd..5a2c1f0294 100644 --- a/test/br/org/scadabr/db/utils/TestUtils.java +++ b/test/br/org/scadabr/db/utils/TestUtils.java @@ -106,4 +106,21 @@ public static DataSourceVO newDataSource(int id) { dataSource.setXid("DS_" + id); return dataSource; } + + public static User newUser(int id, String username) { + User user = new User(); + user.setId(id); + user.setUsername(username); + user.setPassword("password"); + user.setEmail("An email"); + user.setPhone("phone"); + user.setAdmin(true); + user.setDisabled(false); + user.setHomeUrl("url"); + user.setReceiveAlarmEmails(1); + user.setReceiveOwnAuditEvents(true); + user.setDataSourcePermissions(new ArrayList()); + user.setDataPointPermissions(new ArrayList()); + return user; + } } diff --git a/test/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTimeTest.java b/test/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTimeTest.java index d4d9b9a755..1938e4ebf9 100644 --- a/test/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTimeTest.java +++ b/test/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTimeTest.java @@ -9,28 +9,24 @@ public class AnnotatedPointValueTimeTest { public void annotaionPartShouldExistInAnnotationPointValueTime_Test(){ // that AnnotaionPartWhichShouldBeVisibleOnGui will be visible on GUI after text "User:" - String AnnotaionPartWhichShouldBeVisibleOnGui = "admin"; + String username = "admin"; - AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime( - AnnotaionPartWhichShouldBeVisibleOnGui, - new PointValueTimeTest().getMangoValueWithBinaryDataType(), + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(null, 0, SetPointSource.Types.USER, - SetPointSource.Types.USER); + -1); + annotatedPointValueTime.setSourceDescriptionArgument(username); - Assert.assertEquals(AnnotaionPartWhichShouldBeVisibleOnGui, annotatedPointValueTime.getSourceDescriptionArgument()); + Assert.assertEquals(username, annotatedPointValueTime.getSourceDescriptionArgument()); } @Test public void annotaionPartShouldBeAnEmptyInPointValueTime_Test(){ - - String EMPTY_STRING = ""; - AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime( new PointValueTimeTest().getMangoValueWithBinaryDataType(), 0, SetPointSource.Types.USER, - SetPointSource.Types.USER); + -1); - Assert.assertEquals(EMPTY_STRING, annotatedPointValueTime.getSourceDescriptionArgument()); + Assert.assertEquals("", annotatedPointValueTime.getSourceDescriptionArgument()); } } diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java index 6ab1b3f784..2e38a3d7e2 100644 --- a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java +++ b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java @@ -1,36 +1,88 @@ package com.serotonin.mango.rt.dataImage; +import com.serotonin.mango.Common; +import com.serotonin.mango.db.dao.DataPointDao; +import com.serotonin.mango.db.dao.DataSourceDao; +import com.serotonin.mango.db.dao.PointValueDao; +import com.serotonin.mango.rt.RuntimeManager; import com.serotonin.mango.rt.dataImage.types.MangoValue; +import com.serotonin.mango.rt.dataSource.virtual.VirtualDataSourceRT; import com.serotonin.mango.rt.link.PointLinkRT; import com.serotonin.mango.vo.User; import com.serotonin.mango.vo.link.PointLinkVO; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.scada_lts.dao.DAO; +import org.scada_lts.dao.SystemSettingsDAO; +import org.scada_lts.dao.pointvalues.PointValueDAO; +import org.scada_lts.login.ILoggedUsers; +import org.scada_lts.login.LoggedUsers; +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; +import utils.mock.MockUtils; +import javax.sql.DataSource; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.*; +import static org.powermock.api.mockito.PowerMockito.whenNew; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DAO.class, PointValueDAO.class, PointValueService.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 PointValueCacheTest { + private PointValueCache pointValueCache; + private PointValueTime pvt = new PointValueTime(MangoValue.stringToValue("1",1), 1); + + @Before + public void config() throws Exception { + MockUtils.configDaoMock(); + pointValueCache = new PointValueCache(-1, 1); + } + @Test - public void sourceIsNotEmptyFillNeededPropertyInPointValueTime_Test(){ + public void sourceIsNotEmptyFillNeededPropertyInPointValueTime_Test() { + + //given: User source = new User(); - source.setUsername("testName"); - PointValueTime pvt = savePropertiesAboutOwnerOfPointValueChange(source); - Assert.assertEquals("testName",pvt.getWhoChangedValue()); + source.setId(12); + String username = "testName"; + source.setUsername(username); + + //when: + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt,source,Boolean.FALSE,Boolean.FALSE); + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertTrue(pvt.isAnnotated()); + AnnotatedPointValueTime annotatedPointValueTime = (AnnotatedPointValueTime) pvt; + Assert.assertEquals(username, annotatedPointValueTime.getSourceDescriptionArgument()); } @Test - public void sourceIsEmptyNotFillNeededPropertyInPointValueTime_Test(){ + public void sourceIsEmptyNotFillNeededPropertyInPointValueTime_Test() { + //given: PointLinkRT source = new PointLinkRT(new PointLinkVO()); - PointValueTime pvt = savePropertiesAboutOwnerOfPointValueChange(source); - Assert.assertNotSame("testName",pvt.getWhoChangedValue()); - } - public PointValueTime getSavedPointValueTimeInCache (SetPointSource source ){ - return savePropertiesAboutOwnerOfPointValueChange( source ); - } - private PointValueTime savePropertiesAboutOwnerOfPointValueChange (SetPointSource source ){ - PointValueTime pvt = new PointValueTime(MangoValue.stringToValue("1",1), new Long(1)); - PointValueCache pointValueCache = new PointValueCache(); + + + //when: pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt,source,Boolean.FALSE,Boolean.FALSE); - return pvt; + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertFalse(pvt.isAnnotated()); } } diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueFacadeTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueFacadeTest.java deleted file mode 100644 index c5909b9f02..0000000000 --- a/test/com/serotonin/mango/rt/dataImage/PointValueFacadeTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.serotonin.mango.rt.dataImage; - -import com.serotonin.mango.vo.DataPointVO; -import com.serotonin.mango.vo.DataPointVO.LoggingTypes; -import com.serotonin.mango.vo.User; -import org.junit.Assert; -import org.junit.Test; - -public class PointValueFacadeTest { - - private DataPointRT dataPointRT; - private PointValueCache pointValueCache; - - @Test - public void fillCacheWithPointValueWhichContainsOneNotEmptySource_Test(){ - final String GIVEN_USERNAME="testName"; - final String DO_THIS_USERNAME_EXIST="testName"; - DataPointVO dataPointVO = new DataPointVO(LoggingTypes.ON_CHANGE); - dataPointVO.setId(2); - dataPointVO.setDefaultCacheSize(10); - - dataPointRT = new DataPointRT(dataPointVO); - pointValueCache = dataPointRT.getPointValueCache(); - pointValueCache.addPointValueTimeIntoCacheForTest(new PointValueTime(true,new Long(3))); - - User source = new User(); - source.setUsername(GIVEN_USERNAME); - PointValueTime pvt = new PointValueTime(true, new Long(5)); - pointValueCache.setMaxSize(10); - pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt,source,Boolean.FALSE,Boolean.FALSE); - boolean sourceIsNotEmpty=Boolean.FALSE; - for(PointValueTime pointValueTime:pointValueCache.getLatestPointValuesUsedForTest(2)) - { - if(pointValueTime.getWhoChangedValue().equals(DO_THIS_USERNAME_EXIST)) sourceIsNotEmpty=Boolean.TRUE; - } - Assert.assertEquals(Boolean.TRUE,sourceIsNotEmpty); - - } - - -} diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueTimeTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueTimeTest.java index 8526623c78..863173b11b 100644 --- a/test/com/serotonin/mango/rt/dataImage/PointValueTimeTest.java +++ b/test/com/serotonin/mango/rt/dataImage/PointValueTimeTest.java @@ -7,42 +7,46 @@ public class PointValueTimeTest { private final String WHO_CHANGED_VALUE = "test"; - private boolean createInstanceWithVWhoValuedValue; @Test public void thisPointValueTimeInstanceShouldNotHavePropertyWhoChangedValue_Test(){ - createInstanceWithVWhoValuedValue=false; - Assert.assertTrue( createPointValueTime( createInstanceWithVWhoValuedValue ).getWhoChangedValue() != null); + //given: + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(MangoValue.objectToValue(1), -1, SetPointSource.Types.USER, 1); + annotatedPointValueTime.setSourceDescriptionArgument(WHO_CHANGED_VALUE); + + //when: + String username = annotatedPointValueTime.getSourceDescriptionArgument(); + + //then: + Assert.assertTrue( username != null); } @Test public void thisPointValueTimeInstanceShouldHavePropertyWhoChangedValueAsAnEmptyString_Test(){ - createInstanceWithVWhoValuedValue=false; - PointValueTime pointValueTime = createPointValueTime( createInstanceWithVWhoValuedValue ); + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(MangoValue.objectToValue(1), -1, SetPointSource.Types.USER, 1); + annotatedPointValueTime.setSourceDescriptionArgument(""); - String EMPTY_STRING = ""; + String username = annotatedPointValueTime.getSourceDescriptionArgument(); - Assert.assertTrue( - pointValueTime.getWhoChangedValue() != null && - pointValueTime.getWhoChangedValue().equals(EMPTY_STRING) - ); + Assert.assertTrue(username != null && username.equals("")); } @Test public void thisPointValueTimeInstanceShouldHaveCertainPropertyWhoChangedValue_Test(){ - createInstanceWithVWhoValuedValue=true; - Assert.assertEquals(WHO_CHANGED_VALUE, createPointValueTime( createInstanceWithVWhoValuedValue ).getWhoChangedValue() ); - } + //given: + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(MangoValue.objectToValue(1), -1, SetPointSource.Types.USER, 1); + annotatedPointValueTime.setSourceDescriptionArgument(WHO_CHANGED_VALUE); - private PointValueTime createPointValueTime(boolean createInstanceWithVWhoValuedValue){ + //when: + String username = annotatedPointValueTime.getSourceDescriptionArgument(); - return createInstanceWithVWhoValuedValue - ?new PointValueTime( createMangoValue(), 0, WHO_CHANGED_VALUE) - :new PointValueTime( createMangoValue(), 0); + //then: + Assert.assertEquals(WHO_CHANGED_VALUE, username); } + public MangoValue getMangoValueWithBinaryDataType(){ return createMangoValue(); } 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 d52279b5c1..4ae30c73e0 100644 --- a/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java +++ b/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java @@ -5,6 +5,7 @@ import com.serotonin.mango.DataTypes; import com.serotonin.mango.db.dao.DataPointDao; import com.serotonin.mango.db.dao.DataSourceDao; +import com.serotonin.mango.db.dao.PointValueDao; import com.serotonin.mango.rt.EventManager; import com.serotonin.mango.rt.RuntimeManager; import com.serotonin.mango.rt.dataImage.*; @@ -29,18 +30,27 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.model.point.PointValueAdnnotation; -import org.scada_lts.dao.pointvalues.PointValueAdnnotationsDAO; +import org.scada_lts.dao.IUserDAO; +import org.scada_lts.dao.SystemSettingsDAO; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import org.scada_lts.dao.pointvalues.PointValueDAO; +import org.scada_lts.login.ILoggedUsers; +import org.scada_lts.login.LoggedUsers; import org.scada_lts.mango.service.DataPointService; import org.scada_lts.mango.service.DataSourceService; import org.scada_lts.mango.service.PointValueService; import org.scada_lts.mango.service.SystemSettingsService; import org.scada_lts.web.beans.ApplicationBeans; +import org.scada_lts.web.beans.GetApplicationBeans; import org.scada_lts.web.ws.services.DataPointServiceWebSocket; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import utils.PointValueDAOMemory; +import org.springframework.context.ApplicationContext; +import utils.UsersDAOMemory; +import utils.mock.MockUtils; +import javax.sql.DataSource; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -51,16 +61,25 @@ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) -@PrepareForTest({DAO.class, Common.class, PointValueDAO.class, PointValueAdnnotationsDAO.class, - DataPointDao.class, DataSourceDao.class, VirtualDataSourceRT.class, RuntimeManager.class, - PointValueService.class, PointValueDAO.class, ApplicationBeans.class}) +@PrepareForTest({DAO.class, Common.class, PointValueDAO.class, DataPointDao.class, DataSourceDao.class, + VirtualDataSourceRT.class, RuntimeManager.class, PointValueService.class, PointValueDAO.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.*"}) public class ConfigDataPointRtTest { private static final Log LOG = LogFactory.getLog(ConfigDataPointRtTest.class); - private static final PointValueDAOMemory pointValueDAOMemory = new PointValueDAOMemory(); + private static final IPointValueDAO pointValueDAOMemory; + private static final IUserDAO usersDAOMemory = new UsersDAOMemory(); + private static final User user; + + static { + User testUser = TestUtils.newUser(123); + usersDAOMemory.insert(testUser); + user = testUser; + pointValueDAOMemory = new PointValueDAOMemory(usersDAOMemory); + } private static final int NUMBER_OF_TESTS = 20; private PointValueTime oldValue; @@ -77,7 +96,7 @@ public class ConfigDataPointRtTest { private final int defaultCacheSize = 30; private final int numberOfLaunches = 10; - private final User user; + private final DataPointSyncMode sync; private RuntimeManager runtimeManagerMock; @@ -87,66 +106,46 @@ public class ConfigDataPointRtTest { public ConfigDataPointRtTest(DataPointSyncMode sync, Object oldValue, Object newValue, Object newValue2, int dataTypeId, String dataType, String startValue) { - setPointValueTime(oldValue, newValue, newValue2, dataTypeId); + setPointValueTime(oldValue, newValue, newValue2); this.dataTypeId = dataTypeId; this.dataType = dataType; this.startValue = startValue; this.tolerance = 0.0; - this.user = TestUtils.newUser(123); - setPointValueTimeWithUser(oldValue, newValue, newValue2, dataTypeId); + setPointValueTime(this.oldValue, this.newValue, this.newValue2, user); this.sync = sync; init(); } public ConfigDataPointRtTest(DataPointSyncMode sync, Object oldValue, Object newValue, Object newValue2, int dataTypeId, String dataType, String startValue, double tolerance) { - setPointValueTime(oldValue, newValue, newValue2, dataTypeId); + setPointValueTime(oldValue, newValue, newValue2); this.dataTypeId = dataTypeId; this.dataType = dataType; this.startValue = startValue; this.tolerance = tolerance; - this.user = TestUtils.newUser(123); - setPointValueTimeWithUser(oldValue, newValue, newValue2, dataTypeId); + setPointValueTime(this.oldValue, this.newValue, this.newValue2, user); this.sync = sync; init(); } - private void setPointValueTime(Object oldValue, Object newValue, Object newValue2, int dataTypeId) { - if(dataTypeId == DataTypes.ALPHANUMERIC) { - this.oldValue = new AnnotatedPointValueTime(MangoValue.objectToValue(oldValue), System.currentTimeMillis(), 1, 123); - this.newValue = new AnnotatedPointValueTime(MangoValue.objectToValue(newValue), System.currentTimeMillis() + 10, 1, 123); - this.newValue2 = new AnnotatedPointValueTime(MangoValue.objectToValue(newValue2), System.currentTimeMillis() + 15, 1, 123); - - } else { - this.oldValue = new PointValueTime(MangoValue.objectToValue(oldValue), System.currentTimeMillis()); - this.newValue = new PointValueTime(MangoValue.objectToValue(newValue), System.currentTimeMillis() + 10); - this.newValue2 = new PointValueTime(MangoValue.objectToValue(newValue2), System.currentTimeMillis() + 15); - - } + private void setPointValueTime(Object oldValue, Object newValue, Object newValue2) { + this.oldValue = new PointValueTime(MangoValue.objectToValue(oldValue), System.currentTimeMillis()); + this.newValue = new PointValueTime(MangoValue.objectToValue(newValue), System.currentTimeMillis() + 10); + this.newValue2 = new PointValueTime(MangoValue.objectToValue(newValue2), System.currentTimeMillis() + 15); } - private void setPointValueTimeWithUser(Object oldValue, Object newValue, Object newValue2, int dataTypeId) { - if(dataTypeId == DataTypes.ALPHANUMERIC) { - this.oldValueWithUser = new AnnotatedPointValueTime(MangoValue.objectToValue(oldValue), this.oldValue.getTime(), 1, 123); - this.oldValueWithUser.setWhoChangedValue(user.getUsername()); - - this.newValueWithUser = new AnnotatedPointValueTime(MangoValue.objectToValue(newValue), this.newValue.getTime(), 1, 123); - this.newValueWithUser.setWhoChangedValue(user.getUsername()); - - this.newValueWithUser2 = new AnnotatedPointValueTime(MangoValue.objectToValue(newValue2), this.newValue2.getTime(), 1, 123); - this.newValueWithUser2.setWhoChangedValue(user.getUsername()); + private void setPointValueTime(PointValueTime oldValue, PointValueTime newValue, PointValueTime newValue2, User user) { + AnnotatedPointValueTime oldValueWithUser = new AnnotatedPointValueTime(oldValue.getValue(), oldValue.getTime(), SetPointSource.Types.USER, user.getId()); + oldValueWithUser.setSourceDescriptionArgument(user.getUsername()); + this.oldValueWithUser = oldValueWithUser; - } else { - this.oldValueWithUser = new PointValueTime(MangoValue.objectToValue(oldValue), this.oldValue.getTime()); - this.oldValueWithUser.setWhoChangedValue(user.getUsername()); + AnnotatedPointValueTime newValueWithUser = new AnnotatedPointValueTime(newValue.getValue(), newValue.getTime(), SetPointSource.Types.USER, user.getId()); + newValueWithUser.setSourceDescriptionArgument(user.getUsername()); + this.newValueWithUser = newValueWithUser; - this.newValueWithUser = new PointValueTime(MangoValue.objectToValue(newValue), this.newValue.getTime()); - this.newValueWithUser.setWhoChangedValue(user.getUsername()); - - this.newValueWithUser2 = new PointValueTime(MangoValue.objectToValue(newValue2), this.newValue2.getTime()); - this.newValueWithUser2.setWhoChangedValue(user.getUsername()); - - } + AnnotatedPointValueTime newValueWithUser2 = new AnnotatedPointValueTime(newValue2.getValue(), newValue2.getTime(), SetPointSource.Types.USER, user.getId()); + newValueWithUser2.setSourceDescriptionArgument(user.getUsername()); + this.newValueWithUser2 = newValueWithUser2; } private void init() { @@ -159,31 +158,44 @@ private void init() { } private void preconfig() throws Exception { - DAO dao = mock(DAO.class); - JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class); - when(dao.getJdbcTemp()).thenReturn(jdbcTemplate); - whenNew(DAO.class) - .withAnyArguments() - .thenReturn(dao); + ApplicationContext applicationContext = mock(ApplicationContext.class); + GetApplicationBeans getApplicationBeans = new GetApplicationBeans(); + getApplicationBeans.setApplicationContext(applicationContext); + + MockUtils.configDaoMock(); + + ILoggedUsers loggedUsers = new LoggedUsers(); + when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); dataSourceVO = createDataSource(); dataPointVO = createDataPoint(defaultCacheSize, tolerance, startValue, dataTypeId, dataSourceVO); - PointValueAdnnotationsDAO pointValueAdnnotationsDAOMock = mock(PointValueAdnnotationsDAO.class); - when(pointValueAdnnotationsDAOMock.create(any(PointValueAdnnotation.class))).thenAnswer(a -> { + pointValueDAOMock = mock(PointValueDAO.class); + + when(pointValueDAOMock.createAnnotation(anyLong(), anyString(), anyString(), anyInt(), anyInt())).thenAnswer(a -> { Object[] args = a.getArguments(); - return pointValueDAOMemory.create((PointValueAdnnotation)args[0]); + return pointValueDAOMemory.createAnnotation((long)args[0], (String)args[1], (String)args[2], (int)args[3], (int)args[4]); }); - whenNew(PointValueAdnnotationsDAO.class) - .withNoArguments() - .thenReturn(pointValueAdnnotationsDAOMock); - pointValueDAOMock = mock(PointValueDAO.class); - 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]); - }); + 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(), 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.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.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]); + }); when(pointValueDAOMock.getPointValue(anyLong())).thenAnswer(a -> { Object[] args = a.getArguments(); @@ -245,9 +257,11 @@ private void preconfig() throws Exception { .withNoArguments() .thenReturn(systemSettingsServiceMock); - mockStatic(ApplicationBeans.class); DataPointServiceWebSocket dataPointServiceWebSocket = mock(DataPointServiceWebSocket.class); when(ApplicationBeans.getDataPointServiceWebSocketBean()).thenReturn(dataPointServiceWebSocket); + + IUserDAO userDAO = mock(IUserDAO.class); + when(ApplicationBeans.getUserDaoBean()).thenReturn(userDAO); } protected DataPointVO createDataPoint(int defaultCacheSize, @@ -283,7 +297,7 @@ protected DataSourceVO createDataSource() { } public void clear() { - pointValueDAOMemory.clear(); + ((PointValueDAOMemory)pointValueDAOMemory).clear(); } protected static int getNumberOfTests() { diff --git a/test/com/serotonin/mango/rt/event/ScheduledExecuteInactiveEventRtUnscheduleEventTest.java b/test/com/serotonin/mango/rt/event/ScheduledExecuteInactiveEventRtUnscheduleEventTest.java index eeef9f7841..363da9a60f 100644 --- a/test/com/serotonin/mango/rt/event/ScheduledExecuteInactiveEventRtUnscheduleEventTest.java +++ b/test/com/serotonin/mango/rt/event/ScheduledExecuteInactiveEventRtUnscheduleEventTest.java @@ -18,6 +18,8 @@ import org.scada_lts.mango.service.DataSourceService; import org.scada_lts.mango.service.SystemSettingsService; import org.scada_lts.service.*; +import org.scada_lts.web.beans.GetApplicationBeans; +import org.springframework.context.ApplicationContext; import utils.EventTestUtils; import utils.MailingListTestUtils; import utils.ScheduledInactiveEventTestUtils; @@ -81,7 +83,9 @@ public ScheduledExecuteInactiveEventRtUnscheduleEventTest(int dailyLimitSentEmai boolean dailyLimitSentEmails, CommunicationChannelType type, int invokeUnscheduleEventTimes) { - + GetApplicationBeans getApplicationBeans = new GetApplicationBeans(); + ApplicationContext applicationContext = mock(ApplicationContext.class); + getApplicationBeans.setApplicationContext(applicationContext); this.invokeUnscheduleEventTimes = invokeUnscheduleEventTimes; this.channelType = type; this.dailyLimitSentEmails = dailyLimitSentEmails; diff --git a/test/com/serotonin/mango/web/dwr/DataPointDetailsDwrTest.java b/test/com/serotonin/mango/web/dwr/DataPointDetailsDwrTest.java deleted file mode 100644 index 37e5b3ed67..0000000000 --- a/test/com/serotonin/mango/web/dwr/DataPointDetailsDwrTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.serotonin.mango.web.dwr; - -import com.serotonin.mango.rt.dataImage.DataPointRT; -import com.serotonin.mango.rt.dataImage.PointValueCacheTest; -import com.serotonin.mango.rt.dataImage.PointValueFacade; -import com.serotonin.mango.rt.dataImage.PointValueTime; -import com.serotonin.mango.rt.dataSource.PointLocatorRT; -import com.serotonin.mango.rt.link.PointLinkRT; -import com.serotonin.mango.vo.DataPointVO; -import com.serotonin.mango.vo.DataPointVO.LoggingTypes; -import com.serotonin.mango.vo.User; -import com.serotonin.mango.vo.link.PointLinkVO; -import org.junit.Assert; -import org.junit.Test; - -public class DataPointDetailsDwrTest { - - - @Test - public void AnnotatedPointValueWithAnnotations_Test(){ - PointValueCacheTest pointValueCacheTest =new PointValueCacheTest(); - String FIRST_ANNOTATION = "testName"; - String SECOND_ANNOTATION = "another user"; - - User source = new User(); - source.setUsername(FIRST_ANNOTATION); - PointValueTime pointValueTime = pointValueCacheTest.getSavedPointValueTimeInCache(source); - - DataPointVO dataPointVO = new DataPointVO(LoggingTypes.ON_CHANGE); - dataPointVO.setId(2); - dataPointVO.setDefaultCacheSize(10); - - DataPointRT dataPointRT = new DataPointRT(dataPointVO, new PointLocatorRT() { - @Override - public boolean isSettable() { - return true; - } - },4,5); - dataPointRT.addCollectionIntoCache(pointValueTime); - - - PointValueFacade pointValueFacade = new PointValueFacade(dataPointVO.getId(),dataPointRT); - source.setUsername(SECOND_ANNOTATION); - dataPointRT.addCollectionIntoCache( pointValueCacheTest.getSavedPointValueTimeInCache(source) ); - - PointLinkVO pointLinkVO = new PointLinkVO(); - pointLinkVO.setSourcePointId(2); - pointLinkVO.setTargetPointId(3); - pointLinkVO.setId(1); - pointLinkVO.setXid("X_POINT_LINK"); - - PointLinkRT pointLinkRT = new PointLinkRT( pointLinkVO); - dataPointRT.addCollectionIntoCache( pointValueCacheTest.getSavedPointValueTimeInCache(pointLinkRT) ); - - - DataPointDetailsDwr dataPointDetailsDwr = new DataPointDetailsDwr(); - boolean doThisAnnotationExist; - doThisAnnotationExist = dataPointDetailsDwr.doThisAnnotationExist(FIRST_ANNOTATION,pointValueFacade,2); - doThisAnnotationExist = dataPointDetailsDwr.doThisAnnotationExist(SECOND_ANNOTATION,pointValueFacade,2); - Assert.assertTrue(doThisAnnotationExist); - } -} diff --git a/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java b/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java index 8236a3abd8..11c351e22f 100644 --- a/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java +++ b/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java @@ -39,6 +39,8 @@ * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu * */ + +@Deprecated public class PointValueAdnnotationDaoTest extends TestDAO{ private final long POINT_ID_1 = 1; diff --git a/test/org/scada_lts/dao/PointValueDAOTest.java b/test/org/scada_lts/dao/PointValueDAOTest.java index 4d441ee71a..d3b5221bf2 100644 --- a/test/org/scada_lts/dao/PointValueDAOTest.java +++ b/test/org/scada_lts/dao/PointValueDAOTest.java @@ -1,39 +1,55 @@ package org.scada_lts.dao; +import br.org.scadabr.db.utils.TestUtils; +import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.scada_lts.dao.model.point.PointValue; import org.scada_lts.dao.pointvalues.PointValueDAO; -import org.scada_lts.dao.pointvalues.ResultSetImpl; +import org.scada_lts.utils.ResultSetMock; +import org.scada_lts.web.beans.GetApplicationBeans; +import org.springframework.context.ApplicationContext; import java.sql.ResultSet; +import java.sql.SQLException; import java.util.HashMap; import java.util.Map; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class PointValueDAOTest extends TestDAO { - private Map rowExample; + private Map rowExample; private ResultSet resultSet; - private final String USERNAME = "admin"; + private final String username = "admin"; + private final int sourceId = 111111; @Before public void setUp(){ - rowExample = new HashMap(); - rowExample.put("dataType","33333"); - rowExample.put("dataPointId","333332"); - rowExample.put("sourceId","11111"); - rowExample.put("sourceType","1"); - rowExample.put("username",USERNAME); - - resultSet = new ResultSetImpl(rowExample); + ApplicationContext applicationContextMock = mock(ApplicationContext.class); + IUserDAO userDaoMock = mock(IUserDAO.class); + when(userDaoMock.getUser(11111)).thenReturn(TestUtils.newUser(11111, "admin")); + when(applicationContextMock.getBean(eq("userDaoWithCache"))).thenReturn(userDaoMock); + new GetApplicationBeans().setApplicationContext(applicationContextMock); + rowExample = new HashMap<>(); + rowExample.put("dataType",33333); + rowExample.put("dataPointId",333332); + rowExample.put("sourceId",sourceId); + rowExample.put("sourceType",1); + rowExample.put("username", username); + + resultSet = new ResultSetMock(rowExample); } @Test - public void doPointValueContainsGivenUserNameFromResultSetTest(){ - PointValue pointValue = new PointValueDAO().getPointValueRow(resultSet,1); - Assert.assertEquals(USERNAME, pointValue.getPointValue().getWhoChangedValue()); + public void doPointValueContainsGivenUserNameFromResultSetTest() throws SQLException { + PointValue pointValue = new PointValueDAO.PointValueRowMapper().mapRow(resultSet,1); + AnnotatedPointValueTime annotatedPointValueTime = (AnnotatedPointValueTime) pointValue.getPointValue(); + Assert.assertEquals(sourceId, annotatedPointValueTime.getSourceId()); } @After diff --git a/test/org/scada_lts/ds/messaging/channel/MessagingChannelsMultiThreadTest.java b/test/org/scada_lts/ds/messaging/channel/MessagingChannelsMultiThreadTest.java index e5bd0842d9..77e3e1f700 100644 --- a/test/org/scada_lts/ds/messaging/channel/MessagingChannelsMultiThreadTest.java +++ b/test/org/scada_lts/ds/messaging/channel/MessagingChannelsMultiThreadTest.java @@ -99,11 +99,11 @@ public void publish(String message) {} }; DataPointVO dataPoint1 = TestUtils.newPointSettable(1, -1); - dataPointRT1 = new DataPointRT(dataPoint1); + dataPointRT1 = new DataPointRT(dataPoint1, null); DataPointVO dataPoint2 = TestUtils.newPointSettable(2, -1); - dataPointRT2 = new DataPointRT(dataPoint2); + dataPointRT2 = new DataPointRT(dataPoint2, null); DataPointVO dataPoint3 = TestUtils.newPointSettable(3, -1); - dataPointRT3 = new DataPointRT(dataPoint3); + dataPointRT3 = new DataPointRT(dataPoint3, null); } diff --git a/test/org/scada_lts/ds/messaging/channel/MessagingChannelsTest.java b/test/org/scada_lts/ds/messaging/channel/MessagingChannelsTest.java index a283f8f227..d3a52b680c 100644 --- a/test/org/scada_lts/ds/messaging/channel/MessagingChannelsTest.java +++ b/test/org/scada_lts/ds/messaging/channel/MessagingChannelsTest.java @@ -8,10 +8,14 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import utils.mock.MockUtils; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + @RunWith(Parameterized.class) public class MessagingChannelsTest { @@ -94,13 +98,17 @@ public void close(int timeout) {} public void publish(String message) {} }; - DataPointVO dataPoint1 = TestUtils.newPointSettable(1, -1); - dataPointRT1 = new DataPointRT(dataPoint1); - DataPointVO dataPoint2 = TestUtils.newPointSettable(2, -1); - dataPointRT2 = new DataPointRT(dataPoint2); - DataPointVO dataPoint3 = TestUtils.newPointSettable(3, -1); - dataPointRT3 = new DataPointRT(dataPoint3); + DataPointRT dataPointRT1 = mock(DataPointRT.class); + when(dataPointRT1.getId()).thenReturn(1); + this.dataPointRT1 = dataPointRT1; + + DataPointRT dataPointRT2 = mock(DataPointRT.class); + when(dataPointRT2.getId()).thenReturn(2); + this.dataPointRT2 = dataPointRT2; + DataPointRT dataPointRT3 = mock(DataPointRT.class); + when(dataPointRT3.getId()).thenReturn(3); + this.dataPointRT3 = dataPointRT3; } @Before @@ -109,7 +117,7 @@ public void reset() throws Exception { } @Test - public void when_removeChannel_then_channels_size_zero() throws Exception { + public void when_removeChannel_then_channels_size_zero() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -123,7 +131,7 @@ public void when_removeChannel_then_channels_size_zero() throws Exception { } @Test - public void when_removeChannel_then_isOpenChannel_false() throws Exception { + public void when_removeChannel_then_isOpenChannel_false() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -137,7 +145,7 @@ public void when_removeChannel_then_isOpenChannel_false() throws Exception { } @Test - public void when_removeChannel_one_form_two_then_one_isOpenChannel_true() throws Exception { + public void when_removeChannel_one_form_two_then_one_isOpenChannel_true() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -151,7 +159,7 @@ public void when_removeChannel_one_form_two_then_one_isOpenChannel_true() throws } @Test - public void when_removeChannel_one_form_two_then_isOpenChannel_false() throws Exception { + public void when_removeChannel_one_form_two_then_isOpenChannel_false() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -165,7 +173,7 @@ public void when_removeChannel_one_form_two_then_isOpenChannel_false() throws Ex } @Test - public void when_removeChannel_one_form_two_then_one_size() throws Exception { + public void when_removeChannel_one_form_two_then_one_size() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -179,7 +187,7 @@ public void when_removeChannel_one_form_two_then_one_size() throws Exception { } @Test - public void when_removeChannel_and_initChannel_on_other_dataPoints_then_one_size() throws Exception { + public void when_removeChannel_and_initChannel_on_other_dataPoints_then_one_size() { //given: messagingChannels.initChannel(dataPointRT2, () -> messagingChannelOpenned2); @@ -194,7 +202,7 @@ public void when_removeChannel_and_initChannel_on_other_dataPoints_then_one_size } @Test - public void when_removeChannel_and_initChannel_on_other_dataPoints_then_one_isOpenChannel_true() throws Exception { + public void when_removeChannel_and_initChannel_on_other_dataPoints_then_one_isOpenChannel_true() { //given: messagingChannels.initChannel(dataPointRT2, () -> messagingChannelOpenned2); @@ -209,7 +217,7 @@ public void when_removeChannel_and_initChannel_on_other_dataPoints_then_one_isOp } @Test - public void when_isOpenChannel_after_initChannel_then_true() throws Exception { + public void when_isOpenChannel_after_initChannel_then_true() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -231,7 +239,7 @@ public void when_isOpenChannel_without_initChannel_then_false() { } @Test - public void when_initChannel_with_three_dataPoints_then_size_three() throws Exception { + public void when_initChannel_with_three_dataPoints_then_size_three() { //when: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -243,7 +251,7 @@ public void when_initChannel_with_three_dataPoints_then_size_three() throws Exce } @Test - public void when_initChannel_same_dataPoint_then_size_one() throws Exception { + public void when_initChannel_same_dataPoint_then_size_one() { //when: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -253,7 +261,7 @@ public void when_initChannel_same_dataPoint_then_size_one() throws Exception { } @Test - public void when_isOpen_after_initChannel_then_true() throws Exception { + public void when_isOpen_after_initChannel_then_true() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); @@ -265,7 +273,7 @@ public void when_isOpen_after_initChannel_then_true() throws Exception { } @Test - public void when_closeChannels_then_size_zero() throws Exception { + public void when_closeChannels_then_size_zero() { //given: messagingChannels.initChannel(dataPointRT1, () -> messagingChannelOpenned1); messagingChannels.initChannel(dataPointRT2, () -> messagingChannelOpenned2); diff --git a/src/org/scada_lts/dao/pointvalues/ResultSetImpl.java b/test/org/scada_lts/utils/ResultSetMock.java similarity index 98% rename from src/org/scada_lts/dao/pointvalues/ResultSetImpl.java rename to test/org/scada_lts/utils/ResultSetMock.java index 46c9fcc944..c9bb7007d4 100644 --- a/src/org/scada_lts/dao/pointvalues/ResultSetImpl.java +++ b/test/org/scada_lts/utils/ResultSetMock.java @@ -1,4 +1,4 @@ -package org.scada_lts.dao.pointvalues; +package org.scada_lts.utils; import java.io.InputStream; import java.io.Reader; @@ -9,11 +9,11 @@ import java.util.HashMap; import java.util.Map; -public class ResultSetImpl implements ResultSet { +public class ResultSetMock implements ResultSet { - private Map rowExample = new HashMap(); + private Map rowExample = new HashMap<>(); - public ResultSetImpl(Map rowExample){ + public ResultSetMock(Map rowExample){ this.rowExample = rowExample; } @Override @@ -33,7 +33,7 @@ public boolean wasNull() throws SQLException { @Override public String getString(int i) throws SQLException { - return rowExample.get(i); + return (String) rowExample.get(i); } @Override @@ -53,7 +53,7 @@ public short getShort(int i) throws SQLException { @Override public int getInt(int i) throws SQLException { - return 0; + return (int) rowExample.get(i); } @Override @@ -113,7 +113,7 @@ public InputStream getBinaryStream(int i) throws SQLException { @Override public String getString(String s) throws SQLException { - return rowExample.get(s); + return (String) rowExample.get(s); } @Override @@ -133,7 +133,7 @@ public short getShort(String s) throws SQLException { @Override public int getInt(String s) throws SQLException { - return Integer.parseInt(rowExample.get(s)); + return (int) rowExample.get(s); } @Override diff --git a/test/utils/PointValueDAOMemory.java b/test/utils/PointValueDAOMemory.java index dfec4873a8..b8f7a262e1 100644 --- a/test/utils/PointValueDAOMemory.java +++ b/test/utils/PointValueDAOMemory.java @@ -3,19 +3,35 @@ import com.serotonin.mango.DataTypes; import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; import com.serotonin.mango.rt.dataImage.PointValueTime; +import com.serotonin.mango.rt.dataImage.SetPointSource; import com.serotonin.mango.rt.dataImage.types.AlphanumericValue; import com.serotonin.mango.rt.dataImage.types.MangoValue; +import com.serotonin.mango.vo.User; +import com.serotonin.mango.vo.bean.LongPair; +import com.serotonin.mango.vo.bean.PointHistoryCount; +import org.scada_lts.dao.IUserDAO; +import org.scada_lts.dao.model.point.PointValue; import org.scada_lts.dao.model.point.PointValueAdnnotation; +import org.scada_lts.dao.pointvalues.IPointValueDAO; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; -public class PointValueDAOMemory { +public class PointValueDAOMemory implements IPointValueDAO { - private final Map pointValues = new HashMap<>(); - private final Map pointValuesAnno = new HashMap<>(); + private final Map pointValues; + private final Map pointValuesAnno; private static final AtomicLong serial = new AtomicLong(222); + private final IUserDAO usersDAO; + + + public PointValueDAOMemory(IUserDAO usersDAO) { + this.pointValues = new HashMap<>(); + this.pointValuesAnno = new HashMap<>(); + this.usersDAO = usersDAO; + } public synchronized Object[] create(final int pointId, final int dataType, final double dvalue, final long time) { Object value = convert(dataType, dvalue); @@ -25,20 +41,34 @@ public synchronized Object[] create(final int pointId, final int dataType, final return new Object[] {id}; } - public synchronized Object[] create(PointValueAdnnotation pointValueAdnnotation) { - pointValuesAnno.put(pointValueAdnnotation.getPointValueId(), pointValueAdnnotation); - return new Object[] {0}; + + @Override + public int createAnnotation(long pointValueId, String textPointValueShort, String textPointValueLong, int sourceType, int sourceId) { + PointValueTime pointValueTime = pointValues.get(pointValueId); + long time = pointValueTime.getTime(); + MangoValue mangoValue = pointValueTime.getValue(); + if(textPointValueShort != null) { + mangoValue = MangoValue.objectToValue(textPointValueShort); + } else if(textPointValueLong != null) { + mangoValue = MangoValue.objectToValue(textPointValueLong); + } + pointValuesAnno.put(pointValueId, new AnnotatedPointValueTime(mangoValue, time, sourceType, sourceId)); + return 0; } + @Override public synchronized PointValueTime getPointValue(long id) { if(pointValuesAnno.containsKey(id)) { + AnnotatedPointValueTime annotatedPointValueTime = pointValuesAnno.get(id); PointValueTime pointValueTime = pointValues.get(id); - if(pointValueTime.getValue().getDataType() == DataTypes.ALPHANUMERIC) { - PointValueAdnnotation pointValueAdnnotation = pointValuesAnno.get(id); - return new AnnotatedPointValueTime( - new AlphanumericValue(pointValueAdnnotation.getTextPointValueShort() == null ? - pointValueAdnnotation.getTextPointValueLong() : pointValueAdnnotation.getTextPointValueShort()), - pointValueTime.getTime(), pointValueAdnnotation.getSourceType(), (int) pointValueAdnnotation.getSourceId()); + User user = usersDAO.getUser(annotatedPointValueTime.getSourceId()); + annotatedPointValueTime.setSourceDescriptionArgument(user.getUsername()); + if(pointValueTime.getValue() instanceof AlphanumericValue) { + return annotatedPointValueTime; + } else { + AnnotatedPointValueTime annotatedPointValueTime1 = new AnnotatedPointValueTime(pointValueTime.getValue(), pointValueTime.getTime(), SetPointSource.Types.USER, user.getId()); + annotatedPointValueTime1.setSourceDescriptionArgument(user.getUsername()); + return annotatedPointValueTime1; } } return pointValues.get(id); @@ -58,4 +88,129 @@ public synchronized void clear() { pointValuesAnno.clear(); pointValues.clear(); } + + @Override + public List findAll() { + return null; + } + + @Override + public PointValue findById(Object[] pk) { + return null; + } + + @Override + public List findByIdAndTs(long id, long ts) { + return null; + } + + @Override + public List filtered(String filter, Object[] argsFilter, long limit) { + return null; + } + + @Override + public Object[] create(PointValue entity) { + return new Object[0]; + } + + @Override + public Object[] createNoTransaction(int pointId, int dataType, double dvalue, long time) { + return new Object[0]; + } + + @Override + public void executeBatchUpdateInsert(List params) { + + } + + @Override + public Long getInceptionDate(int dataPointId) { + return null; + } + + @Override + public long dateRangeCount(int dataPointId, long from, long to) { + return 0; + } + + @Override + public LongPair getStartAndEndTime(List dataPointIds) { + return null; + } + + @Override + public long getStartTime(List dataPointIds) { + return 0; + } + + @Override + public long getEndTime(List dataPointIds) { + return 0; + } + + @Override + public List getFiledataIds() { + return null; + } + + @Override + public Long getLatestPointValue(int dataPointId) { + return null; + } + + @Override + public double applyBounds(double value) { + return 0; + } + + @Override + public long deletePointValuesBeforeWithOutLast(int dataPointId, long time) { + return 0; + } + + @Override + public long deletePointValuesBeforeWithOutLastTwo(int dataPointId, long time) { + return 0; + } + + @Override + public long deletePointValue(int dataPointId) { + return 0; + } + + @Override + public long deleteAllPointData() { + return 0; + } + + @Override + public long deletePointValuesWithMismatchedType(int dataPointId, int dataType) { + return 0; + } + + @Override + public long deletePointValuesWithValueLimit(int dataPointId, int limit) { + return 0; + } + + @Override + public long getMinTs(int dataPointId) { + return 0; + } + + @Override + public long getMaxTs(int dataPointId) { + return 0; + } + + @Override + public List getTopPointHistoryCounts() { + return null; + } + + @Override + public void updateAnnotation(int userId) { + + } } diff --git a/test/utils/UsersDAOMemory.java b/test/utils/UsersDAOMemory.java new file mode 100644 index 0000000000..3dacab809d --- /dev/null +++ b/test/utils/UsersDAOMemory.java @@ -0,0 +1,82 @@ +package utils; + +import com.serotonin.mango.Common; +import com.serotonin.mango.vo.User; +import org.scada_lts.dao.IUserDAO; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +public class UsersDAOMemory implements IUserDAO { + + private final Map users = new HashMap<>(); + private final static AtomicInteger id = new AtomicInteger(); + + + @Override + public List getAll() { + return new ArrayList<>(users.keySet()); + } + + @Override + public List getUsers() { + return new ArrayList<>(users.values()); + } + + @Override + public List getActiveUsers() { + return users.values().stream().filter(a -> !a.isDisabled()).collect(Collectors.toList()); + } + + @Override + public User getUser(String username) { + return users.values().stream().filter(a -> a.getUsername().equals(username)).findAny().orElse(null); + } + + @Override + public User getUser(int id) { + return users.values().stream().filter(a -> a.getId() == id).findAny().orElse(null); + } + + @Override + public void update(User user) { + users.put(user.getId(), user); + } + + @Override + public void updateHomeUrl(int userId, String homeUrl) { + users.values().stream().filter(a -> a.getId() == userId).peek(a -> a.setHomeUrl(homeUrl)).close(); + } + + @Override + public void updateUserPassword(int userId, String newPassword) { + users.values().stream().filter(a -> a.getId() == userId).peek(a -> a.setPassword(newPassword)).close(); + } + + @Override + public void updateLogin(int userId) { + users.values().stream().filter(a -> a.getId() == userId).peek(a -> a.setLastLogin(System.currentTimeMillis())).close(); + } + + @Override + public void delete(int userId) { + users.remove(userId); + } + + @Override + public int insert(User user) { + if(users.containsKey(user.getId())) { + throw new IllegalStateException(); + } + int userId = id.incrementAndGet(); + user.setId(userId); + users.put(userId, user); + return userId; + } + + @Override + public void updateUserLang(int userId, String lang) { + users.values().stream().filter(a -> a.getId() == userId).peek(a -> a.setLang(lang)).close(); + } +} diff --git a/test/utils/mock/ChangePointValueDataPointRtMock.java b/test/utils/mock/ChangePointValueDataPointRtMock.java index 92b12c5a00..dc6330002b 100644 --- a/test/utils/mock/ChangePointValueDataPointRtMock.java +++ b/test/utils/mock/ChangePointValueDataPointRtMock.java @@ -14,7 +14,7 @@ public class ChangePointValueDataPointRtMock extends DataPointRT implements IDat private Iterator pointValueTimes; public ChangePointValueDataPointRtMock(List pointValueTimes) { - super(null); + super(new DataPointVO(DataPointVO.LoggingTypes.ON_CHANGE), null); this.pointValueTimes = pointValueTimes.iterator(); } diff --git a/test/utils/mock/MockUtils.java b/test/utils/mock/MockUtils.java index 6341ab1d21..f0a3212051 100644 --- a/test/utils/mock/MockUtils.java +++ b/test/utils/mock/MockUtils.java @@ -8,14 +8,17 @@ import com.serotonin.mango.web.ContextWrapper; import com.serotonin.util.PropertiesUtils; import org.scada_lts.dao.DAO; +import org.scada_lts.web.beans.ApplicationBeans; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import utils.ServletContextMock; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; +import javax.sql.DataSource; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.*; import static org.powermock.api.mockito.PowerMockito.when; @@ -58,4 +61,24 @@ public static void configMock(RuntimeManager runtimeManager, User user) throws E PropertiesUtils propertiesUtils = new PropertiesUtils("WEB-INF/classes/env"); when(Common.getEnvironmentProfile()).thenReturn(propertiesUtils); } + + public static void configDaoMock() throws Exception { + mockStatic(ApplicationBeans.class); + + DataSource dataSource = mock(DataSource.class); + when(ApplicationBeans.getBean(eq("databaseSource"), eq(DataSource.class))).thenReturn(dataSource); + + JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class); + NamedParameterJdbcTemplate namedParameterJdbcTemplate = mock(NamedParameterJdbcTemplate.class); + + whenNew(JdbcTemplate.class) + .withParameterTypes(DataSource.class) + .withArguments(eq(dataSource)) + .thenReturn(jdbcTemplate); + + whenNew(NamedParameterJdbcTemplate.class) + .withParameterTypes(DataSource.class) + .withArguments(eq(dataSource)) + .thenReturn(namedParameterJdbcTemplate); + } } From 3d2ede0ae487734870b7138a64d2d3c9ac4bc7f9 Mon Sep 17 00:00:00 2001 From: Kamil Jarmusik Date: Thu, 25 Jan 2024 12:38:20 +0100 Subject: [PATCH 2/6] #2798 Corrected History Annotation Change Point Value By User - include tests: DataPointSyncRtMultiTest, DataPointSyncRtBinaryMultiTest, DataPointSyncRtNumericMultiTest, DataPointSyncRtAlphanumericMultiTest, DataPointSyncRtMultistateMultiTest, DataPointSyncRtToleranceMultiTest, DataPointSyncRtNumericSameMultiTest --- .../datapointrt/DataPointRtMultiThreadTestsSuite.java | 8 ++++---- .../rt/dataImage/datapointrt/DataPointRtTestsSuite.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtMultiThreadTestsSuite.java b/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtMultiThreadTestsSuite.java index cd58ae3a4a..33027af4e0 100644 --- a/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtMultiThreadTestsSuite.java +++ b/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtMultiThreadTestsSuite.java @@ -8,13 +8,13 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ - DataPointRtMultiTest.class, + /*DataPointRtMultiTest.class, DataPointRtBinaryMultiTest.class, DataPointRtNumericMultiTest.class, DataPointRtAlphanumericMultiTest.class, DataPointRtMultistateMultiTest.class, DataPointRtToleranceMultiTest.class, - DataPointRtNumericSameMultiTest.class, + DataPointRtNumericSameMultiTest.class,*/ DataPointSyncRtMultiTest.class, DataPointSyncRtBinaryMultiTest.class, @@ -24,12 +24,12 @@ DataPointSyncRtToleranceMultiTest.class, DataPointSyncRtNumericSameMultiTest.class, - DataPointNonSyncRtMultiTest.class, + /*DataPointNonSyncRtMultiTest.class, DataPointNonSyncRtBinaryMultiTest.class, DataPointNonSyncRtNumericMultiTest.class, DataPointNonSyncRtAlphanumericMultiTest.class, DataPointNonSyncRtMultistateMultiTest.class, DataPointNonSyncRtToleranceMultiTest.class, - DataPointNonSyncRtNumericSameMultiTest.class, + DataPointNonSyncRtNumericSameMultiTest.class,*/ }) public class DataPointRtMultiThreadTestsSuite {} diff --git a/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtTestsSuite.java b/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtTestsSuite.java index a3dc16e075..a718b37d8b 100644 --- a/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtTestsSuite.java +++ b/test/com/serotonin/mango/rt/dataImage/datapointrt/DataPointRtTestsSuite.java @@ -7,6 +7,6 @@ @Suite.SuiteClasses({ PointValueStateTest.class, DataPointRtOneThreadTestsSuite.class, - //DataPointRtMultiThreadTestsSuite.class + DataPointRtMultiThreadTestsSuite.class }) public class DataPointRtTestsSuite {} From d125139800480fddaa649c5f3e00ba2ebd98c61b Mon Sep 17 00:00:00 2001 From: Kamil Date: Thu, 15 Feb 2024 17:08:35 +0100 Subject: [PATCH 3/6] #2798 Corrected History Annotation Change Point Value By User - sorted point values by id desc if ts is same; --- .../scada_lts/mango/service/PointValueService.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index 931b363d95..849b84f7dc 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -22,9 +22,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.RejectedExecutionException; @@ -311,7 +309,7 @@ private long savePointValueImpl(int pointId, int dataType, double dvalue, long t //TODO rewrite private List getLstPointValueTime(List lstIn) { List lst = new ArrayList(); - + lstIn.sort(Comparator.comparing(PointValue::getId).reversed()); for (PointValue pv : lstIn) { lst.add(pv.getPointValue()); if(pv.getPointValue() instanceof AnnotatedPointValueTime) { @@ -359,14 +357,16 @@ public PointValueTime getLatestPointValue(int dataPointId) { List lstValues = PointValueDAO.getInstance().findByIdAndTs(dataPointId, maxTs); - if (lstValues.size() == 0) + if (lstValues.isEmpty()) return null; + lstValues.sort(Comparator.comparing(PointValue::getId).reversed()); + PointValueTime pointValue = lstValues.get(0).getPointValue(); if(pointValue instanceof AnnotatedPointValueTime) { updateAnnotation((AnnotatedPointValueTime) pointValue); } - return lstValues.get(0).getPointValue(); + return pointValue; } public PointValueTime getPointValueBefore(int dataPointId, long time) { From cc358fcda1bd4dbbd8aa235616bb928e689a684c Mon Sep 17 00:00:00 2001 From: Kamil Jarmusik Date: Fri, 16 Feb 2024 20:14:57 +0100 Subject: [PATCH 4/6] #2798 Corrected History Annotation Change Point Value By User: - removed MangoPointValuesWithChangeOwner from imports in PointValueService; (this import appeared in conflict resolution) --- src/org/scada_lts/mango/service/PointValueService.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index 3acc30182c..8eb2d568bc 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -45,7 +45,6 @@ import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.mango.adapter.MangoPointValues; import org.scada_lts.web.beans.ApplicationBeans; -import org.scada_lts.mango.adapter.MangoPointValuesWithChangeOwner; import org.scada_lts.monitor.type.IntegerMonitor; import org.springframework.dao.ConcurrencyFailureException; From 2acb03d0137a4f1138ddf105ebf17495043ce21a Mon Sep 17 00:00:00 2001 From: Kamil Date: Mon, 19 Feb 2024 11:08:54 +0100 Subject: [PATCH 5/6] #2798 Corrected History Annotation Change Point Value By User - corrected annotation for other source user --- .../rt/dataImage/AnnotatedPointValueTime.java | 24 +- .../mango/rt/dataImage/PointValueCache.java | 27 +- .../mango/rt/dataImage/PointValueFacade.java | 23 +- .../mango/rt/dataImage/SetPointSource.java | 2 +- .../mango/util/AnnotatedPointValueUtils.java | 56 ++++ src/com/serotonin/mango/vo/RestApiSource.java | 25 ++ .../mango/web/dwr/DataPointDetailsDwr.java | 11 +- .../dao/model/point/PointValueTypeOfREST.java | 1 + .../dao/pointvalues/IPointValueDAO.java | 4 + .../dao/pointvalues/PointValueDAO.java | 167 ++++++---- .../dao/pointvalues/PointValueDAO4REST.java | 3 +- .../mango/adapter/MangoPointValues.java | 6 + .../mango/service/DataPointService.java | 24 ++ .../mango/service/PointValueService.java | 61 +--- .../scada_lts/web/mvc/api/PointValueAPI.java | 11 +- .../mvc/api/components/cmp/ChangeDataAPI.java | 6 +- .../rt/dataImage/PointValueCacheTest.java | 299 ++++++++++++++++-- .../config/ConfigDataPointRtTest.java | 3 +- test/messages_de.properties | 3 +- test/messages_en.properties | 3 +- test/messages_es.properties | 3 +- test/messages_fi.properties | 3 +- test/messages_fr.properties | 3 +- test/messages_lu.properties | 3 +- test/messages_nl.properties | 3 +- test/messages_pl.properties | 1 + test/messages_pt.properties | 3 +- test/messages_ru.properties | 3 +- test/messages_zh.properties | 3 +- .../dao/PointValueAdnnotationDaoTest.java | 181 ----------- test/org/scada_lts/dao/PointValueDAOTest.java | 69 ++-- test/utils/PointValueDAOMemory.java | 91 +++--- test/utils/mock/MockUtils.java | 3 + webapp-resources/messages_de.properties | 3 +- webapp-resources/messages_en.properties | 3 +- webapp-resources/messages_es.properties | 3 +- webapp-resources/messages_fi.properties | 3 +- webapp-resources/messages_fr.properties | 3 +- webapp-resources/messages_lu.properties | 3 +- webapp-resources/messages_nl.properties | 3 +- webapp-resources/messages_pl.properties | 1 + webapp-resources/messages_pt.properties | 3 +- webapp-resources/messages_ru.properties | 3 +- webapp-resources/messages_zh.properties | 3 +- 44 files changed, 691 insertions(+), 468 deletions(-) create mode 100644 src/com/serotonin/mango/util/AnnotatedPointValueUtils.java create mode 100644 src/com/serotonin/mango/vo/RestApiSource.java delete mode 100644 test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java diff --git a/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java b/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java index 65bd4e3181..a8ee5a3bf9 100644 --- a/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java +++ b/src/com/serotonin/mango/rt/dataImage/AnnotatedPointValueTime.java @@ -18,12 +18,12 @@ */ package com.serotonin.mango.rt.dataImage; -import java.text.MessageFormat; import java.util.Objects; import java.util.ResourceBundle; +import com.serotonin.mango.Common; import com.serotonin.mango.rt.dataImage.types.MangoValue; -import com.serotonin.web.i18n.I18NUtils; +import com.serotonin.mango.util.AnnotatedPointValueUtils; import com.serotonin.web.taglib.DateFunctions; /** @@ -79,18 +79,7 @@ public int getSourceType() { } public String getSourceDescriptionKey() { - switch (sourceType) { - case SetPointSource.Types.ANONYMOUS: - return "annotation.anonymous"; - case SetPointSource.Types.EVENT_HANDLER: - return "annotation.eventHandler"; - case SetPointSource.Types.USER: - return "annotation.user"; - case SetPointSource.Types.POINT_LINK: - return "annotation.pointLink"; - default: - return "annotation.unknown"; - } + return AnnotatedPointValueUtils.getSourceDescriptionKey(sourceType); } public String getSourceDescriptionArgument() { @@ -102,10 +91,7 @@ public void setSourceDescriptionArgument(String sourceDescriptionArgument) { } public String getAnnotation(ResourceBundle bundle) { - String pattern = I18NUtils.getMessage(bundle, getSourceDescriptionKey()); - if (sourceDescriptionArgument == null) - return MessageFormat.format(pattern, I18NUtils.getMessage(bundle, "common.deleted")); - return MessageFormat.format(pattern, sourceDescriptionArgument); + return AnnotatedPointValueUtils.getAnnotation(bundle, sourceType, sourceDescriptionArgument); } @Override @@ -124,6 +110,6 @@ public int hashCode() { @Override public String toString() { - return "AnnotatedPointValueTime(" + sourceDescriptionArgument + " -- " + getValue() + "@" + DateFunctions.getTime(getTime()) + ")"; + return "AnnotatedPointValueTime(" + (sourceDescriptionArgument == null ? getAnnotation(Common.getBundle()) : sourceDescriptionArgument) + " -- " + getValue() + "@" + DateFunctions.getTime(getTime()) + ")"; } } diff --git a/src/com/serotonin/mango/rt/dataImage/PointValueCache.java b/src/com/serotonin/mango/rt/dataImage/PointValueCache.java index 47e4241d20..a6151528d9 100644 --- a/src/com/serotonin/mango/rt/dataImage/PointValueCache.java +++ b/src/com/serotonin/mango/rt/dataImage/PointValueCache.java @@ -21,8 +21,8 @@ import java.util.ArrayList; import java.util.List; -import com.serotonin.mango.db.dao.PointValueDao; import com.serotonin.mango.vo.User; +import org.scada_lts.mango.service.PointValueService; /** * This class maintains an ordered list of the most recent values for a data point. It will mirror values in the @@ -36,7 +36,7 @@ public class PointValueCache { private final int dataPointId; private final int defaultSize; - private final PointValueDao dao; + private final PointValueService service; private int maxSize = 0; /** @@ -49,7 +49,7 @@ public class PointValueCache { public PointValueCache(int dataPointId, int defaultSize) { this.dataPointId = dataPointId; this.defaultSize = defaultSize; - dao = new PointValueDao(); + service = new PointValueService(); if (defaultSize > 0) refreshCache(defaultSize); @@ -58,15 +58,18 @@ public PointValueCache(int dataPointId, int defaultSize) { public void savePointValueIntoDaoAndCacheUpdate(PointValueTime pvt, SetPointSource source, boolean logValue, boolean async) { if (logValue) { if (async) - dao.savePointValueAsync(dataPointId, pvt, source); + service.savePointValueAsync(dataPointId, pvt, source); else - pvt = dao.savePointValueSync(dataPointId, pvt, source); + pvt = service.savePointValueSync(dataPointId, pvt, source); } - if(!pvt.isAnnotated() && (source instanceof User)) { - User user = (User) source; - AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(pvt.getValue(), pvt.getTime(), SetPointSource.Types.USER, user.getId()); - annotatedPointValueTime.setSourceDescriptionArgument(user.getUsername()); + if((!logValue || async) && !pvt.isAnnotated() && source != null) { + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(pvt.getValue(), pvt.getTime(), + source.getSetPointSourceType(), source.getSetPointSourceId()); + if(source instanceof User) { + User user = (User) source; + annotatedPointValueTime.setSourceDescriptionArgument(user.getUsername()); + } insertPointValueTimeIntoCache(annotatedPointValueTime); return; } @@ -104,7 +107,7 @@ private void insertPointValueTimeIntoCache(PointValueTime pvt){ */ void logPointValueAsync(PointValueTime pointValue, SetPointSource source) { // Save the new value and get a point value time back that has the id and annotations set, as appropriate. - dao.savePointValueAsync(dataPointId, pointValue, source); + service.savePointValueAsync(dataPointId, pointValue, source); } public PointValueTime getLatestPointValue() { @@ -141,7 +144,7 @@ private void refreshCache(int size) { maxSize = size; if (size == 1) { // Performance thingy - PointValueTime pvt = dao.getLatestPointValue(dataPointId); + PointValueTime pvt = service.getLatestPointValue(dataPointId); if (pvt != null) { List c = new ArrayList(); c.add(pvt); @@ -149,7 +152,7 @@ private void refreshCache(int size) { } } else - cache = dao.getLatestPointValues(dataPointId, size); + cache = service.getLatestPointValues(dataPointId, size); } } diff --git a/src/com/serotonin/mango/rt/dataImage/PointValueFacade.java b/src/com/serotonin/mango/rt/dataImage/PointValueFacade.java index 5491f7031f..b3626b9295 100644 --- a/src/com/serotonin/mango/rt/dataImage/PointValueFacade.java +++ b/src/com/serotonin/mango/rt/dataImage/PointValueFacade.java @@ -21,7 +21,7 @@ import java.util.List; import com.serotonin.mango.Common; -import com.serotonin.mango.db.dao.PointValueDao; +import org.scada_lts.mango.service.PointValueService; /** * @author Matthew Lohbihler @@ -29,52 +29,47 @@ public class PointValueFacade { private final int dataPointId; private final DataPointRT point; - private final PointValueDao pointValueDao; + private final PointValueService pointValueService; - public PointValueFacade(int dataPointId,DataPointRT point) { - this.dataPointId = dataPointId; - pointValueDao = null; - this.point = point; - } public PointValueFacade(int dataPointId) { this.dataPointId = dataPointId; point = Common.ctx.getRuntimeManager().getDataPoint(dataPointId); - pointValueDao = new PointValueDao(); + pointValueService = new PointValueService(); } public List getPointValues(long since) { if (point != null) return point.getPointValues(since); - return pointValueDao.getPointValues(dataPointId, since); + return pointValueService.getPointValues(dataPointId, since); } public PointValueTime getPointValueBefore(long time) { if (point != null) return point.getPointValueBefore(time); - return pointValueDao.getPointValueBefore(dataPointId, time); + return pointValueService.getPointValueBefore(dataPointId, time); } public PointValueTime getPointValueAt(long time) { if (point != null) return point.getPointValueAt(time); - return pointValueDao.getPointValueAt(dataPointId, time); + return pointValueService.getPointValueAt(dataPointId, time); } public PointValueTime getPointValue() { if (point != null) return point.getPointValue(); - return pointValueDao.getLatestPointValue(dataPointId); + return pointValueService.getLatestPointValue(dataPointId); } public List getPointValuesBetween(long from, long to) { if (point != null) return point.getPointValuesBetween(from, to); - return pointValueDao.getPointValuesBetween(dataPointId, from, to); + return pointValueService.getPointValuesBetween(dataPointId, from, to); } public List getLatestPointValues(int limit) { if (point != null) return point.getLatestPointValues(limit); - return pointValueDao.getLatestPointValues(dataPointId, limit); + return pointValueService.getLatestPointValues(dataPointId, limit); } } diff --git a/src/com/serotonin/mango/rt/dataImage/SetPointSource.java b/src/com/serotonin/mango/rt/dataImage/SetPointSource.java index c24c8df575..339dc43936 100644 --- a/src/com/serotonin/mango/rt/dataImage/SetPointSource.java +++ b/src/com/serotonin/mango/rt/dataImage/SetPointSource.java @@ -34,7 +34,7 @@ public interface Types { int ANONYMOUS = 3; int POINT_LINK = 4; int UNKNOWN = 5; - int API = 6; + int REST_API = 6; } public int getSetPointSourceType(); diff --git a/src/com/serotonin/mango/util/AnnotatedPointValueUtils.java b/src/com/serotonin/mango/util/AnnotatedPointValueUtils.java new file mode 100644 index 0000000000..95fec1b207 --- /dev/null +++ b/src/com/serotonin/mango/util/AnnotatedPointValueUtils.java @@ -0,0 +1,56 @@ +package com.serotonin.mango.util; + +import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; +import com.serotonin.mango.rt.dataImage.PointValueTime; +import com.serotonin.mango.rt.dataImage.SetPointSource; +import com.serotonin.mango.vo.User; +import com.serotonin.web.i18n.I18NUtils; + +import java.text.MessageFormat; +import java.util.ResourceBundle; + +public final class AnnotatedPointValueUtils { + + private AnnotatedPointValueUtils(){} + + public static AnnotatedPointValueTime createAnnotatedPointValueTime(PointValueTime pvt, SetPointSource source) { + String sourceDescriptionArgument = getSourceDescriptionArgument(source); + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(pvt.getValue(), pvt.getTime(), + source.getSetPointSourceType(), source.getSetPointSourceId()); + annotatedPointValueTime.setSourceDescriptionArgument(sourceDescriptionArgument); + return annotatedPointValueTime; + } + + public static String getSourceDescriptionArgument(SetPointSource source) { + if(source instanceof User) { + User user = (User) source; + return user.getUsername(); + } else { + return source.getClass().getSimpleName(); + } + } + + public static String getSourceDescriptionKey(int sourceType) { + switch (sourceType) { + case SetPointSource.Types.ANONYMOUS: + return "annotation.anonymous"; + case SetPointSource.Types.EVENT_HANDLER: + return "annotation.eventHandler"; + case SetPointSource.Types.USER: + return "annotation.user"; + case SetPointSource.Types.POINT_LINK: + return "annotation.pointLink"; + case SetPointSource.Types.REST_API: + return "annotation.api"; + default: + return "annotation.unknown"; + } + } + + public static String getAnnotation(ResourceBundle bundle, int sourceType, String sourceDescriptionArgument) { + String pattern = I18NUtils.getMessage(bundle, getSourceDescriptionKey(sourceType)); + if (sourceDescriptionArgument == null) + return MessageFormat.format(pattern, I18NUtils.getMessage(bundle, "common.deleted")); + return MessageFormat.format(pattern, sourceDescriptionArgument); + } +} diff --git a/src/com/serotonin/mango/vo/RestApiSource.java b/src/com/serotonin/mango/vo/RestApiSource.java new file mode 100644 index 0000000000..fbfa60fbf8 --- /dev/null +++ b/src/com/serotonin/mango/vo/RestApiSource.java @@ -0,0 +1,25 @@ +package com.serotonin.mango.vo; + +import com.serotonin.mango.rt.dataImage.SetPointSource; + +public class RestApiSource implements SetPointSource { + @Override + public int getSetPointSourceType() { + return Types.REST_API; + } + + @Override + public int getSetPointSourceId() { + return -1; + } + + @Override + public void raiseRecursionFailureEvent() { + + } + + @Override + public void pointSetComplete() { + + } +} diff --git a/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java b/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java index 1f09f51820..648266eccc 100644 --- a/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java +++ b/src/com/serotonin/mango/web/dwr/DataPointDetailsDwr.java @@ -26,6 +26,7 @@ import javax.servlet.http.HttpServletRequest; +import com.serotonin.mango.util.AnnotatedPointValueUtils; import org.directwebremoting.WebContextFactory; import org.joda.time.DateTime; @@ -93,12 +94,12 @@ public DwrResponseI18n getHistoryTableData(int limit) { rpvt.setValue(Functions.getHtmlText(pointVO, pvt)); rpvt.setTime(formatDateTime(pvt)); - if (pvt != null && pvt.isAnnotated()) { - AnnotatedPointValueTime apvt = (AnnotatedPointValueTime) pvt; - if (apvt.getSourceDescriptionArgument() == null) { - rpvt.setAnnotation(apvt.getSourceDescriptionArgument()); - } else { + if (pvt != null) { + if(pvt.isAnnotated()) { + AnnotatedPointValueTime apvt = (AnnotatedPointValueTime) pvt; rpvt.setAnnotation(apvt.getAnnotation(getResourceBundle())); + } else { + rpvt.setAnnotation("System"); } } renderedData.add(rpvt); diff --git a/src/org/scada_lts/dao/model/point/PointValueTypeOfREST.java b/src/org/scada_lts/dao/model/point/PointValueTypeOfREST.java index 3c01011462..9731c2f857 100644 --- a/src/org/scada_lts/dao/model/point/PointValueTypeOfREST.java +++ b/src/org/scada_lts/dao/model/point/PointValueTypeOfREST.java @@ -1,5 +1,6 @@ package org.scada_lts.dao.model.point; +@Deprecated public class PointValueTypeOfREST { public final static int TYPE_UNKNOWN = 0; diff --git a/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java b/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java index 8bd8801deb..f64856996b 100644 --- a/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java +++ b/src/org/scada_lts/dao/pointvalues/IPointValueDAO.java @@ -72,4 +72,8 @@ public interface IPointValueDAO { int createAnnotation(long pointValueId, String textPointValueShort, String textPointValueLong, int sourceType, int sourceId); void updateAnnotation(int userId); + + PointValueTime getPointValueBefore(int dataPointId, long time); + + PointValueTime getPointValueAt(int dataPointId, long time); } diff --git a/src/org/scada_lts/dao/pointvalues/PointValueDAO.java b/src/org/scada_lts/dao/pointvalues/PointValueDAO.java index 1716cb51d1..703eb09015 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueDAO.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueDAO.java @@ -26,11 +26,13 @@ import java.util.List; import com.serotonin.mango.rt.dataImage.SetPointSource; +import com.serotonin.mango.vo.User; 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.web.beans.ApplicationBeans; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; import org.springframework.jdbc.core.PreparedStatementCreator; @@ -65,9 +67,9 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { private static final Log LOG = LogFactory.getLog(PointValueDAO.class); - + private static PointValueDAO instance; - + private final static String COLUMN_NAME_ID = "id"; private final static String COLUMN_NAME_DATA_TYPE = "dataType"; private final static String COLUMN_NAME_POINT_VALUE = "pointValue"; @@ -81,8 +83,8 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { private final static String COLUMN_NAME_MIN_TIME_STAMP = "minTs"; private final static String COLUMN_NAME_MAX_TIME_STAMP = "maxTs"; private final static String COLUMN_NAME_USERNAME_IN_TABLE_USERS = "username"; - - + + // @formatter:off private static final String POINT_VALUE_SELECT = "" + "select " @@ -118,15 +120,15 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { private static final String POINT_VALUE_FILTER_BASE_ON_ID = "" + "pv."+COLUMN_NAME_ID+"=?"; - - private static final String POINT_VALUE_SELECT_MIN_MAX_TS_BASE_ON_LIST_DATA_POINT = "" + + private static final String POINT_VALUE_SELECT_MIN_MAX_TS_BASE_ON_LIST_DATA_POINT = "" +"select " +"min(ts) as "+COLUMN_NAME_MIN_TIME_STAMP+", " +"max(ts) as "+COLUMN_NAME_MAX_TIME_STAMP+" " +"from " + "pointValues " + "where " + COLUMN_NAME_DATA_POINT_ID + " in (:ids)"; - + private static final String POINT_VALUE_SELECT_MIN_TS_BASE_ON_LIST_DATA_POINT = "" +"select " +"min(ts) as "+ COLUMN_NAME_MIN_TIME_STAMP + " " @@ -134,7 +136,7 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { + "pointValues " + "where " + COLUMN_NAME_DATA_POINT_ID + " in (:ids)"; - + private static final String POINT_VALUE_SELECT_MAX_TS_BASE_ON_LIST_DATA_POINT = "" +"select " + "max(ts) as "+ COLUMN_NAME_MAX_TIME_STAMP+" " @@ -142,7 +144,7 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { + "pointValues " + "where " + COLUMN_NAME_DATA_POINT_ID + " in (:ids)"; - + private static final String POINT_VALUE_SELECT_MAX_BASE_ON_DATA_POINT_ID = "" +"select " +"max(ts) as " + COLUMN_NAME_MAX_TIME_STAMP + " " @@ -150,30 +152,30 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { + "pointValues " +"where " + COLUMN_NAME_DATA_POINT_ID + "=?"; - - - private static final String POINT_VALUE_SELECT_ON_BASE_ID = "" - + POINT_VALUE_SELECT - + " where " + + + private static final String POINT_VALUE_SELECT_ON_BASE_ID = "" + + POINT_VALUE_SELECT + + " where " + COLUMN_NAME_ID + "=?"; - - private static final String POINT_VALUE_SELECT_ON_BASE_ID_TS = "" - + POINT_VALUE_SELECT - + " where " + + private static final String POINT_VALUE_SELECT_ON_BASE_ID_TS = "" + + POINT_VALUE_SELECT + + " where " + COLUMN_NAME_DATA_POINT_ID + "=? and " + COLUMN_NAME_TIME_STAMP +"=?"; - - + + private static final String POINT_VALUE_INSERT = "" + "insert pointValues (" - + COLUMN_NAME_DATA_POINT_ID + "," - + COLUMN_NAME_DATA_TYPE + "," - + COLUMN_NAME_POINT_VALUE + "," - + COLUMN_NAME_TIME_STAMP + + COLUMN_NAME_DATA_POINT_ID + "," + + COLUMN_NAME_DATA_TYPE + "," + + COLUMN_NAME_POINT_VALUE + "," + + COLUMN_NAME_TIME_STAMP +") " + "values (?,?,?,?)"; - - + + private static final String POINT_VALUE_INCEPTION_DATA = " " +"select " + "min(ts) " @@ -181,7 +183,7 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { + "pointValues " + "where " + COLUMN_NAME_DATA_POINT_ID+"=?"; - + private static final String POINT_VALUE_DATA_RANGE_COUNT = " " +"select " + "count(*) " @@ -189,29 +191,29 @@ public class PointValueDAO implements GenericDaoCR, IPointValueDAO { + "pointValues " + "where " + COLUMN_NAME_DATA_POINT_ID+"=? and "+COLUMN_NAME_TIME_STAMP+">=? and "+COLUMN_NAME_TIME_STAMP+"<=?"; - + public static final String POINT_VALUE_FILTER_BASE_ON_DATA_POINT_ID_AND_TIME_STAMP = " " + "pv."+COLUMN_NAME_DATA_POINT_ID+"=? and " + "pv."+COLUMN_NAME_TIME_STAMP+" >= ? order by "+COLUMN_NAME_TIME_STAMP; - + public static final String POINT_VALUE_FILTER_BASE_ON_DATA_POINT_ID_AND_TIME_STAMP_FROM_TO = " " + "pv."+COLUMN_NAME_DATA_POINT_ID+"=? and " + "pv."+COLUMN_NAME_TIME_STAMP+">=? and pv."+COLUMN_NAME_TIME_STAMP+", IPointValueDAO { + "order by id DESC " + "limit 2 " + ") lastId ) and " + COLUMN_NAME_TIME_STAMP + ", IPointValueDAO { + "order by 2 desc "; // @formatter:on - + //RowMappers public static class PointValueRowMapper implements RowMapper { @@ -308,7 +310,7 @@ public PointValue mapRow(ResultSet rs, int rowNum) throws SQLException { //TODO rewrite MangoValue MangoValue value = createMangoValue(rs); long time = rs.getLong(COLUMN_NAME_TIME_STAMP); - + PointValue pv = new PointValue(); pv.setId(rs.getLong(COLUMN_NAME_ID)); pv.setDataPointId(rs.getInt(COLUMN_NAME_DATA_POINT_ID)); @@ -318,9 +320,21 @@ public PointValue mapRow(ResultSet rs, int rowNum) throws SQLException { pv.setPointValue(new PointValueTime(value, time)); } else { int sourceId = rs.getInt(COLUMN_NAME_SOURCE_ID); - pv.setPointValue(new AnnotatedPointValueTime(value, time, sourceType, sourceId)); + + AnnotatedPointValueTime annotatedPointValueTime = new AnnotatedPointValueTime(value, time, sourceType, sourceId); + if (sourceType == SetPointSource.Types.USER && sourceId > 0) { + User user = ApplicationBeans.getLoggedUsersBean().getUser(sourceId); + if (user == null) { + user = ApplicationBeans.getUserDaoBean().getUser(sourceId); + } + if (user != null) { + String username = user.getUsername(); + annotatedPointValueTime.setSourceDescriptionArgument(username); + } + } + pv.setPointValue(annotatedPointValueTime); } - return pv; + return pv; } } @@ -332,17 +346,17 @@ public LongPair mapRow(ResultSet rs, int index) throws SQLException { return new LongPair(myLongValue, rs.getLong(COLUMN_NAME_MAX_TIME_STAMP)); } } - + private class LongRowMapper implements RowMapper { public Long mapRow(ResultSet rs, int index) throws SQLException { return rs.getLong(COLUMN_NAME_MIN_TIME_STAMP); } } - + //TODO rewrite for new types static MangoValue createMangoValue(ResultSet rs) throws SQLException { - + int dataType = rs.getInt(COLUMN_NAME_DATA_TYPE); MangoValue value = null; switch (dataType) { @@ -362,7 +376,7 @@ static MangoValue createMangoValue(ResultSet rs) value = new AlphanumericValue(s); break; case (DataTypes.IMAGE): { - try { + try { value = new ImageValue(Integer.parseInt(rs .getString(COLUMN_NAME_TEXT_POINT_VALUE_SHORT)), rs.getInt(COLUMN_NAME_TEXT_POINT_VALUE_LONG)); @@ -376,8 +390,8 @@ static MangoValue createMangoValue(ResultSet rs) } return value; } - - public static PointValueDAO getInstance() { + + public static IPointValueDAO getInstance() { if (instance == null) { instance = new PointValueDAO(); } @@ -394,12 +408,12 @@ public List findAll() { public PointValue findById(Object[] pk) { return (PointValue) DAO.getInstance().getJdbcTemp().queryForObject(POINT_VALUE_SELECT_ON_BASE_ID, pk, new PointValueRowMapper()); } - + @Override public List findByIdAndTs(long id, long ts) { return DAO.getInstance().getJdbcTemp().query(POINT_VALUE_SELECT_ON_BASE_ID_TS, new Object[] { id,ts }, new PointValueRowMapper()); } - + @Override public List filtered(String filter, Object[] argsFilter, long limit) { String myLimit=""; @@ -423,7 +437,7 @@ public Object[] create(final PointValue entity) { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(POINT_VALUE_INSERT, Statement.RETURN_GENERATED_KEYS); - new ArgumentPreparedStatementSetter( new Object[] { + new ArgumentPreparedStatementSetter( new Object[] { entity.getDataPointId(), entity.getPointValue().getValue().getDataType(), getValueBaseOnType( entity.getPointValue().getValue().getDataType(), entity.getPointValue()), @@ -432,34 +446,35 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return ps; } }, keyHolder); - - return new Object[] {keyHolder.getKey().longValue()}; - + + long id = getId(keyHolder); + return new Object[] {id}; + } - - + + @Override @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) public Object[] create(final int pointId, final int dataType, final double dvalue, final long time) { - + return createNoTransaction(pointId, dataType, dvalue, time); - + } - - + + @Override public Object[] createNoTransaction(final int pointId, final int dataType, final double dvalue, final long time) { - + if (LOG.isTraceEnabled()) { LOG.trace("pointId:"+pointId+" dataType:"+dataType+" dvalue:"+time); } - + KeyHolder keyHolder = new GeneratedKeyHolder(); DAO.getInstance().getJdbcTemp().update(new PreparedStatementCreator() { @Override - public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(POINT_VALUE_INSERT, Statement.RETURN_GENERATED_KEYS); - new ArgumentPreparedStatementSetter( new Object[] { + new ArgumentPreparedStatementSetter( new Object[] { pointId, dataType, dvalue, @@ -468,13 +483,14 @@ public PreparedStatement createPreparedStatement(Connection connection) throws S return ps; } }, keyHolder); - - return new Object[] {keyHolder.getKey().longValue()}; - + + long id = getId(keyHolder); + return new Object[]{id}; + } - - - + + + @Override @Transactional(readOnly = false,propagation= Propagation.REQUIRES_NEW,isolation= Isolation.READ_COMMITTED,rollbackFor=SQLException.class) public void executeBatchUpdateInsert(List params) { @@ -690,8 +706,9 @@ public void updateAnnotation(int userId) { DAO.getInstance().getJdbcTemp().update(POINT_VALUE_ANNOTATIONS_UPDATE, new Object[]{userId}); } - - public PointValueTime getPointValueBefore(int dataPointId, long time) { + + @Override + public PointValueTime getPointValueBefore(int dataPointId, long time) { try { Long valueTime = DAO.getInstance().getJdbcTemp().queryForObject("select max(ts) from pointValues where dataPointId=? and ts pointValues = DAO.getInstance().getJdbcTemp().query(POINT_VALUE_SELECT + " where pv.dataPointId=? and pv.ts=?", new Object[]{dataPointId, time}, new PointValueRowMapper()); @@ -714,4 +732,13 @@ public PointValueTime getPointValueAt(int dataPointId, long time) { return null; return pointValue.getPointValue(); } + + private static long getId(KeyHolder keyHolder) { + long id = -1; + Number key = keyHolder.getKey(); + if(key != null) { + id = key.longValue(); + } + return id; + } } \ No newline at end of file diff --git a/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java b/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java index 35112e6717..f59225b706 100644 --- a/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java +++ b/src/org/scada_lts/dao/pointvalues/PointValueDAO4REST.java @@ -40,6 +40,7 @@ * */ @Repository +@Deprecated public class PointValueDAO4REST { private static final Log LOG = LogFactory.getLog(PointValueDAO4REST.class); @@ -78,7 +79,7 @@ public PointValueTime save(String value, int typePointValueOfREST, int dpid) { new RuntimeException("Value not compatible with type (double)"); } } else if (typePointValueOfREST==PointValueTypeOfREST.TYPE_STRING) { - pvt = new AnnotatedPointValueTime(MangoValue.objectToValue(value), new Date().getTime(), SetPointSource.Types.API, 0); + pvt = new AnnotatedPointValueTime(MangoValue.objectToValue(value), new Date().getTime(), SetPointSource.Types.REST_API, 0); } else { new RuntimeException("Unknown value type"); } diff --git a/src/org/scada_lts/mango/adapter/MangoPointValues.java b/src/org/scada_lts/mango/adapter/MangoPointValues.java index d61cbd283a..fbb7369695 100644 --- a/src/org/scada_lts/mango/adapter/MangoPointValues.java +++ b/src/org/scada_lts/mango/adapter/MangoPointValues.java @@ -77,5 +77,11 @@ public interface MangoPointValues { long getEndTime(List dataPointIds); List getFiledataIds(); + + PointValueTime savePointValueSync(int pointId, + PointValueTime pointValue, SetPointSource source); + + void savePointValueAsync(int pointId, PointValueTime pointValue, + SetPointSource source); } diff --git a/src/org/scada_lts/mango/service/DataPointService.java b/src/org/scada_lts/mango/service/DataPointService.java index 51eb9980d8..ba428095cd 100644 --- a/src/org/scada_lts/mango/service/DataPointService.java +++ b/src/org/scada_lts/mango/service/DataPointService.java @@ -255,24 +255,43 @@ public List valuesPointBooleanBaseOnNameFilter2DTO(Map searchDataPointsBy(String searchText) { } return getDataPoints(Comparator.comparing(DataPointVO::getName), false); } + + private void save(User user, String value, DataPointVO point, SetPointSource source) { + Permissions.ensureDataPointSetPermission(user, point); + setPointImpl(point, value, source); + } } diff --git a/src/org/scada_lts/mango/service/PointValueService.java b/src/org/scada_lts/mango/service/PointValueService.java index 8eb2d568bc..deb730fbf1 100644 --- a/src/org/scada_lts/mango/service/PointValueService.java +++ b/src/org/scada_lts/mango/service/PointValueService.java @@ -44,7 +44,6 @@ import org.scada_lts.dao.model.point.PointValue; import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.mango.adapter.MangoPointValues; -import org.scada_lts.web.beans.ApplicationBeans; import org.scada_lts.monitor.type.IntegerMonitor; import org.springframework.dao.ConcurrencyFailureException; @@ -89,6 +88,7 @@ public PointValueService() { * Only the PointValueCache should call this method during runtime. Do not * use. */ + @Override public PointValueTime savePointValueSync(int pointId, PointValueTime pointValue, SetPointSource source) { long id = savePointValueImpl(pointId, pointValue, source, false); @@ -97,7 +97,7 @@ public PointValueTime savePointValueSync(int pointId, int retries = 5; while (true) { try { - savedPointValue = PointValueDAO.getInstance().findById(new Object[]{id}).getPointValue(); + savedPointValue = getPointValue(id); break; } catch (ConcurrencyFailureException e) { if (retries <= 0) @@ -113,6 +113,7 @@ public PointValueTime savePointValueSync(int pointId, * Only the PointValueCache should call this method during runtime. Do not * use. */ + @Override public void savePointValueAsync(int pointId, PointValueTime pointValue, SetPointSource source) { long id = savePointValueImpl(pointId, pointValue, source, true); @@ -238,7 +239,7 @@ long savePointValueInTrasaction(final int pointId, final int dataType, double dv } catch (RuntimeException e) { throw new RuntimeException( "Error saving point value: dataType=" + dataType - + ", dvalue=" + dvalue, e); + + ", dvalue=" + dvalue + ", message: " + e.getMessage(), e); } } } @@ -313,9 +314,6 @@ private List getLstPointValueTime(List lstIn) { lstIn.sort(Comparator.comparing(PointValue::getId).reversed()); for (PointValue pv : lstIn) { lst.add(pv.getPointValue()); - if(pv.getPointValue() instanceof AnnotatedPointValueTime) { - updateAnnotation((AnnotatedPointValueTime) pv.getPointValue()); - } } return lst; } @@ -364,9 +362,9 @@ public PointValueTime getLatestPointValue(int dataPointId) { lstValues.sort(Comparator.comparing(PointValue::getId).reversed()); PointValueTime pointValue = lstValues.get(0).getPointValue(); - if(pointValue instanceof AnnotatedPointValueTime) { + /*if(pointValue instanceof AnnotatedPointValueTime) { updateAnnotation((AnnotatedPointValueTime) pointValue); - } + }*/ return pointValue; } @@ -626,9 +624,9 @@ public String getDetails() { public PointValueTime getPointValue(long id) { PointValueTime pointValueTime = PointValueDAO.getInstance().getPointValue(id); - if(pointValueTime instanceof AnnotatedPointValueTime) { + /*if(pointValueTime instanceof AnnotatedPointValueTime) { updateAnnotation((AnnotatedPointValueTime) pointValueTime); - } + }*/ return pointValueTime; } @@ -674,8 +672,6 @@ public void updateMetaDataPointByScript(User user, String xid) { metaPointLocatorRT.initialize(Common.timer, metaDataSourceRT, dataPointRT); - String value = ""; - try { ScriptExecutor scriptExecutor = new ScriptExecutor(); @@ -683,35 +679,13 @@ public void updateMetaDataPointByScript(User user, String xid) { Map context = scriptExecutor.convertContext(metaPointLocatorVO.getContext()); PointValueTime pointValueTime = scriptExecutor.execute(metaPointLocatorVO.getScript(), context, System.currentTimeMillis(), metaPointLocatorVO.getDataTypeId(), System.currentTimeMillis()); - - switch (metaPointLocatorVO.getDataTypeId()) { - case DataTypes.BINARY: - BinaryValue binaryValue = (BinaryValue) pointValueTime.getValue(); - if (binaryValue.getBooleanValue()) { - value = "" + 1; - } else { - value = "" + 0; - } - break; - case DataTypes.MULTISTATE: - MultistateValue multistateValue = (MultistateValue) pointValueTime.getValue(); - value = "" + multistateValue.getIntegerValue(); - break; - case DataTypes.NUMERIC: - NumericValue numericValue = (NumericValue) pointValueTime.getValue(); - value = "" + numericValue.getDoubleValue(); - break; - case DataTypes.ALPHANUMERIC: - AlphanumericValue alphanumericValue = (AlphanumericValue) pointValueTime.getValue(); - value = alphanumericValue.getStringValue(); - break; - } + Common.ctx.getRuntimeManager().setDataPointValue(dataPoint.getId(), pointValueTime, user); } catch (Exception ex) { LOG.error(infoErrorExecutionScript(ex, dataPointRT, metaDataSourceRT)); throw ex; } - dataPointService.save(user, value, dataPoint.getXid(), metaPointLocatorVO.getDataTypeId()); + } catch (Exception e) { LOG.error(e.getMessage()); } @@ -744,20 +718,5 @@ public void updateAllMetaDataPointsByScript(User user) { .forEach(dp -> updateMetaDataPointByScript(user, dp.getXid())); } - - private void updateAnnotation(AnnotatedPointValueTime annotatedPointValueTime) { - int sourceType = annotatedPointValueTime.getSourceType(); - int sourceId = annotatedPointValueTime.getSourceId(); - if (sourceType == SetPointSource.Types.USER && sourceId > 0) { - User user = ApplicationBeans.getLoggedUsersBean().getUser(sourceId); - if (user == null) { - user = ApplicationBeans.getUserDaoBean().getUser(sourceId); - } - if (user != null) { - String username = user.getUsername(); - annotatedPointValueTime.setSourceDescriptionArgument(username); - } - } - } } diff --git a/src/org/scada_lts/web/mvc/api/PointValueAPI.java b/src/org/scada_lts/web/mvc/api/PointValueAPI.java index 19ad13908e..ad35df22a8 100644 --- a/src/org/scada_lts/web/mvc/api/PointValueAPI.java +++ b/src/org/scada_lts/web/mvc/api/PointValueAPI.java @@ -7,10 +7,11 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; +import com.serotonin.mango.DataTypes; +import com.serotonin.mango.vo.RestApiSource; import com.serotonin.mango.vo.dataSource.DataSourceVO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scada_lts.dao.model.point.PointValueTypeOfREST; import org.scada_lts.mango.service.DataPointService; import org.scada_lts.mango.service.DataSourceService; import org.scada_lts.mango.service.PointValueService; @@ -445,7 +446,7 @@ public ResponseEntity setValue( User user = Common.getUser(request); if (user != null) { - dataPointService.save(user, value, xid, type); + dataPointService.save(user, value, xid, type, new RestApiSource()); return new ResponseEntity(value, HttpStatus.OK); } @@ -480,8 +481,8 @@ public ResponseEntity setValueV2( if (!error.isEmpty()) { return ResponseEntity.badRequest().body(formatErrorsJson(error)); } - if(type != PointValueTypeOfREST.TYPE_STRING) { value = convertInputValue(value); } - dataPointService.save(user, value, xid, type); + if(type != DataTypes.ALPHANUMERIC) { value = convertInputValue(value); } + dataPointService.save(user, value, xid, type, new RestApiSource()); return new ResponseEntity<>(value, HttpStatus.OK); } return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); @@ -512,7 +513,7 @@ public ResponseEntity setValueGet( User user = Common.getUser(request); if (user != null) { - dataPointService.save(user, value, xid, type); + dataPointService.save(user, value, xid, type, new RestApiSource()); return new ResponseEntity(value, HttpStatus.OK); } diff --git a/src/org/scada_lts/web/mvc/api/components/cmp/ChangeDataAPI.java b/src/org/scada_lts/web/mvc/api/components/cmp/ChangeDataAPI.java index 7215ebcf0b..1724b2956d 100644 --- a/src/org/scada_lts/web/mvc/api/components/cmp/ChangeDataAPI.java +++ b/src/org/scada_lts/web/mvc/api/components/cmp/ChangeDataAPI.java @@ -1,6 +1,7 @@ package org.scada_lts.web.mvc.api.components.cmp; import com.serotonin.mango.Common; +import com.serotonin.mango.vo.RestApiSource; import com.serotonin.mango.vo.User; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -13,7 +14,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -53,7 +53,7 @@ public ResponseEntity set( if (user != null) { for (SetValuePointDTO sv : xIDsValues) { try { - dataPointService.saveAPI(user, sv.getValue(), sv.getXid()); + dataPointService.save(user, sv.getValue(), sv.getXid(), new RestApiSource()); } catch (Exception e) { sv.setError(e.getMessage()); } @@ -95,7 +95,7 @@ public ResponseEntity setNoAdit( if (user != null) { for (SetValuePointDTO sv : xIDsValues) { try { - dataPointService.saveAPI(user, sv.getValue(), sv.getXid()); + dataPointService.save(user, sv.getValue(), sv.getXid(), new RestApiSource()); } catch (Exception e) { sv.setError(e.getMessage()); } diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java index 2e38a3d7e2..076199411c 100644 --- a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java +++ b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java @@ -1,88 +1,329 @@ package com.serotonin.mango.rt.dataImage; import com.serotonin.mango.Common; -import com.serotonin.mango.db.dao.DataPointDao; -import com.serotonin.mango.db.dao.DataSourceDao; -import com.serotonin.mango.db.dao.PointValueDao; -import com.serotonin.mango.rt.RuntimeManager; +import com.serotonin.mango.DataTypes; +import com.serotonin.mango.MangoContextListener; import com.serotonin.mango.rt.dataImage.types.MangoValue; -import com.serotonin.mango.rt.dataSource.virtual.VirtualDataSourceRT; +import com.serotonin.mango.rt.event.handlers.SetPointHandlerRT; import com.serotonin.mango.rt.link.PointLinkRT; +import com.serotonin.mango.rt.maint.BackgroundProcessing; +import com.serotonin.mango.rt.maint.work.AbstractBeforeAfterWorkItem; import com.serotonin.mango.vo.User; +import com.serotonin.mango.vo.event.EventHandlerVO; import com.serotonin.mango.vo.link.PointLinkVO; +import com.serotonin.mango.web.ContextWrapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.scada_lts.dao.DAO; -import org.scada_lts.dao.SystemSettingsDAO; +import org.scada_lts.dao.IUserDAO; import org.scada_lts.dao.pointvalues.PointValueDAO; import org.scada_lts.login.ILoggedUsers; -import org.scada_lts.login.LoggedUsers; import org.scada_lts.mango.service.PointValueService; +import org.scada_lts.mango.service.SystemSettingsService; import org.scada_lts.web.beans.ApplicationBeans; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import utils.mock.MockUtils; +import utils.PointValueDAOMemory; -import javax.sql.DataSource; +import java.util.ResourceBundle; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.*; -import static org.powermock.api.mockito.PowerMockito.whenNew; @RunWith(PowerMockRunner.class) -@PrepareForTest({DAO.class, PointValueDAO.class, PointValueService.class, ApplicationBeans.class}) +@PrepareForTest({DAO.class, PointValueDAO.class, PointValueService.class, ApplicationBeans.class, + AbstractBeforeAfterWorkItem.class, MangoContextListener.class, Common.class}) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*", "javax.activation.*", "javax.management.*"}) public class PointValueCacheTest { private PointValueCache pointValueCache; - private PointValueTime pvt = new PointValueTime(MangoValue.stringToValue("1",1), 1); + private PointValueTime pvt; + private User sourceUser; @Before public void config() throws Exception { - MockUtils.configDaoMock(); + sourceUser = new User(); + sourceUser.setId(12); + sourceUser.setLang("pl"); + String username = "testName"; + sourceUser.setUsername(username); + + 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); + when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); + + SystemSettingsService systemSettingsService = mock(SystemSettingsService.class); + whenNew(SystemSettingsService.class).withAnyArguments().thenReturn(systemSettingsService); + + BackgroundProcessing backgroundProcessing = mock(BackgroundProcessing.class); + ContextWrapper contextWrapper = mock(ContextWrapper.class); + when(contextWrapper.getBackgroundProcessing()).thenReturn(backgroundProcessing); + Common.ctx = contextWrapper; + + mockStatic(Common.class); + when(Common.getUser()).thenReturn(sourceUser); + when(Common.getBundle()).thenReturn(ResourceBundle.getBundle("messages")); + + pvt = new PointValueTime(MangoValue.stringToValue("1", DataTypes.BINARY), 1708165754243L); pointValueCache = new PointValueCache(-1, 1); } @Test - public void sourceIsNotEmptyFillNeededPropertyInPointValueTime_Test() { + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_for_User_then_annotated_true() { //given: - User source = new User(); - source.setId(12); - String username = "testName"; - source.setUsername(username); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, false, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_for_User_then_toString() { + + //given: + String expected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@Feb 17 11:29)"; + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, false, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(expected, pvt.toString()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_for_PointLinkRT_then_annotated_true() { + + //given: + PointLinkRT source = new PointLinkRT(new PointLinkVO()); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, source, false, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_for_SetPointHandlerRT_then_annotated_true() { + + //given: + SetPointHandlerRT source = new SetPointHandlerRT(new EventHandlerVO()); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, source, false, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_for_User_then_annotated_true() { + + //given: + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, true, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_for_User_then_toString() { + + //given: + String expected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@Feb 17 11:29)"; + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, true, false); //when: - pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt,source,Boolean.FALSE,Boolean.FALSE); PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertTrue(pvt.isAnnotated()); - AnnotatedPointValueTime annotatedPointValueTime = (AnnotatedPointValueTime) pvt; - Assert.assertEquals(username, annotatedPointValueTime.getSourceDescriptionArgument()); + Assert.assertEquals(expected, pvt.toString()); } @Test - public void sourceIsEmptyNotFillNeededPropertyInPointValueTime_Test() { + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_for_PointLinkRT_then_annotated_true() { + //given: PointLinkRT source = new PointLinkRT(new PointLinkVO()); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, source, true, false); + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_for_SetPointHandlerRT_then_annotated_true() { + + //given: + SetPointHandlerRT source = new SetPointHandlerRT(new EventHandlerVO()); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, source, true, false); //when: - pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt,source,Boolean.FALSE,Boolean.FALSE); PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertFalse(pvt.isAnnotated()); + Assert.assertEquals(true, pvt.isAnnotated()); } + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_for_User_then_annotated_true() { + + //given: + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, true, true); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_for_User_then_toString() { + + //given: + String expected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@Feb 17 11:29)"; + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, true, true); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(expected, pvt.toString()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_for_PointLinkRT_then_annotated_true() { + + //given: + PointLinkRT source = new PointLinkRT(new PointLinkVO()); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, source, true, true); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_for_SetPointHandlerRT_then_annotated_true() { + + //given: + SetPointHandlerRT source = new SetPointHandlerRT(new EventHandlerVO()); + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, source, true, true); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(true, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_source_null_then_annotated_false() { + + //given: + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, false, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(false, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_source_null_then_toString() { + + //given: + String expected = "PointValueTime(true@Feb 17 11:29)"; + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, false, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(expected, pvt.toString()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_source_null_then_annotated_false() { + + //given: + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, true, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(false, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_source_null_then_toString() { + + //given: + String expected = "PointValueTime(true@Feb 17 11:29)"; + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, true, false); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(expected, pvt.toString()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_source_null_then_annotated_false() { + + //given: + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, true, true); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(false, pvt.isAnnotated()); + } + + @Test + public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_source_null_then_toString() { + + //given: + String expected = "PointValueTime(true@Feb 17 11:29)"; + pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, true, true); + + //when: + PointValueTime pvt = pointValueCache.getLatestPointValue(); + + //then: + Assert.assertEquals(expected, pvt.toString()); + } } 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 4ae30c73e0..3defb08d4d 100644 --- a/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java +++ b/test/com/serotonin/mango/rt/dataImage/datapointrt/config/ConfigDataPointRtTest.java @@ -164,8 +164,9 @@ private void preconfig() throws Exception { MockUtils.configDaoMock(); - ILoggedUsers loggedUsers = new LoggedUsers(); + ILoggedUsers loggedUsers = mock(ILoggedUsers.class); when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); + when(loggedUsers.getUser(eq(user.getId()))).thenReturn(user); dataSourceVO = createDataSource(); dataPointVO = createDataPoint(defaultCacheSize, tolerance, startValue, dataTypeId, dataSourceVO); diff --git a/test/messages_de.properties b/test/messages_de.properties index 2b5b9e6739..a3ee01559b 100644 --- a/test/messages_de.properties +++ b/test/messages_de.properties @@ -3334,4 +3334,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_en.properties b/test/messages_en.properties index 2c75526a76..b30109299b 100644 --- a/test/messages_en.properties +++ b/test/messages_en.properties @@ -3337,4 +3337,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_es.properties b/test/messages_es.properties index 4039c70224..d34a747fdd 100644 --- a/test/messages_es.properties +++ b/test/messages_es.properties @@ -3377,4 +3377,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_fi.properties b/test/messages_fi.properties index f3d9c7b23a..812f1fe756 100644 --- a/test/messages_fi.properties +++ b/test/messages_fi.properties @@ -3463,4 +3463,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_fr.properties b/test/messages_fr.properties index b37b69350f..4a1d179507 100644 --- a/test/messages_fr.properties +++ b/test/messages_fr.properties @@ -3331,4 +3331,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_lu.properties b/test/messages_lu.properties index fcffdadd8d..56025f852b 100644 --- a/test/messages_lu.properties +++ b/test/messages_lu.properties @@ -3350,4 +3350,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_nl.properties b/test/messages_nl.properties index dc9ff02d3b..cc838b5d15 100644 --- a/test/messages_nl.properties +++ b/test/messages_nl.properties @@ -3453,4 +3453,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_pl.properties b/test/messages_pl.properties index d41ffc1c60..aef65b4b72 100644 --- a/test/messages_pl.properties +++ b/test/messages_pl.properties @@ -3476,3 +3476,4 @@ systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API diff --git a/test/messages_pt.properties b/test/messages_pt.properties index eb16fbfd9a..94316ea501 100644 --- a/test/messages_pt.properties +++ b/test/messages_pt.properties @@ -3489,4 +3489,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_ru.properties b/test/messages_ru.properties index b99c28e26f..4aba684182 100644 --- a/test/messages_ru.properties +++ b/test/messages_ru.properties @@ -3485,4 +3485,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/messages_zh.properties b/test/messages_zh.properties index 25c80922a9..7d451f2719 100644 --- a/test/messages_zh.properties +++ b/test/messages_zh.properties @@ -3438,4 +3438,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java b/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java deleted file mode 100644 index 11c351e22f..0000000000 --- a/test/org/scada_lts/dao/PointValueAdnnotationDaoTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * (c) 2016 Abil'I.T. http://abilit.eu/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package org.scada_lts.dao; - -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Test; -import org.scada_lts.dao.model.point.PointValue; -import org.scada_lts.dao.model.point.PointValueAdnnotation; -import org.scada_lts.dao.pointvalues.PointValueAdnnotationsDAO; -import org.scada_lts.dao.pointvalues.PointValueDAO; - -import com.serotonin.mango.rt.dataImage.PointValueTime; -import com.serotonin.mango.rt.dataImage.types.AlphanumericValue; -import com.serotonin.mango.rt.dataImage.types.ImageValue; -import com.serotonin.mango.rt.dataImage.types.MangoValue; - -/** - * Test PointValueDAO - * - * @author grzegorz bylica Abil'I.T. development team, sdt@abilit.eu - * - */ - -@Deprecated -public class PointValueAdnnotationDaoTest extends TestDAO{ - - private final long POINT_ID_1 = 1; - private final long POINT_ID_2 = 2; - - @Test - public void test() { - - //populate data - // @formatter:off - // Adding datasource - DAO.getInstance().getJdbcTemp().update("INSERT INTO datasources (`xid`,`name`,`dataSourceType`,`data`) VALUES ('DS_01','DS_TEST', 1,'');"); - - // create point - // ALPHANUMERIC dataPointId 1 - DAO.getInstance().getJdbcTemp().update("INSERT INTO datapoints (`xid`,`dataSourceId`,`data`) VALUES ('T_04',1,'')"); - // IMAGE dataPointId 2 - DAO.getInstance().getJdbcTemp().update("INSERT INTO datapoints (`xid`,`dataSourceId`,`data`) VALUES ('T_05',1,'')"); - - //create values for point ALPHANUMERIC 150 char - // aadfadfasdfadfadfasdfasdfasdfasdf12ddddddddddd133333333aadfadfasdfadfadfasdfasdfasdfasdf12ddddddddddd133333333aadfadfasdfadfadfasdfasdfasdfasdf12ddddddddddd133333333 - MangoValue valueAlphanumeric1 = new AlphanumericValue("aadfadfasdfadfadfasdfasdfasdfasdf12ddddddddddd133333333aadfadfasdfadfadfasdfasdfasdfasdf12ddddddddddd133333333aadfadfasdfadfadfasdfasdfasdfasdf12ddddddddddd133333333"); - PointValueTime pvtForAlphanumeric1 = new PointValueTime(valueAlphanumeric1, 0); - PointValue pointValueAlphanumeric1 = new PointValue(); - pointValueAlphanumeric1.setDataPointId(POINT_ID_1); - pointValueAlphanumeric1.setPointValue(pvtForAlphanumeric1); - - // 12abc - MangoValue valueAlphanumeric2 = new AlphanumericValue("12abc"); - PointValueTime pvtForAlphanumeric2 = new PointValueTime(valueAlphanumeric2, 0); - PointValue pointValueAlphanumeric2 = new PointValue(); - pointValueAlphanumeric2.setDataPointId(POINT_ID_1); - pointValueAlphanumeric2.setPointValue(pvtForAlphanumeric2); - //save data in pointValueAdnnotation - - //create values for point IMAGE - // ? - MangoValue valueImage1 = new ImageValue(Integer.parseInt("1"),1); - PointValueTime pvtForImage1 = new PointValueTime(valueImage1, 0); - PointValue pointValueImage1 = new PointValue(); - pointValueImage1.setDataPointId(POINT_ID_2); - pointValueImage1.setPointValue(pvtForImage1); - - // ? - MangoValue valueImage2 = new ImageValue(Integer.parseInt("2"),1); - PointValueTime pvtForImage2 = new PointValueTime(valueImage2, 0); - PointValue pointValueImage2 = new PointValue(); - pointValueImage2.setDataPointId(POINT_ID_2); - pointValueImage2.setPointValue(pvtForImage2); - //save data in pointValueAdnnotation - - //insert (values for every type point) - PointValueDAO pointValuesDAO = new PointValueDAO(); - - pointValuesDAO.create(pointValueAlphanumeric1); - pointValuesDAO.create(pointValueAlphanumeric2); - pointValuesDAO.create(pointValueImage1); - pointValuesDAO.create(pointValueImage2); - - //insert (adnnotations for every value) - //alphanumeric - PointValueAdnnotation pointValueAdnnotationAlphanumericLongText = new PointValueAdnnotation(); - pointValueAdnnotationAlphanumericLongText.setPointValueId(1); - pointValueAdnnotationAlphanumericLongText.setTextPointValueLong(pointValueAlphanumeric1.getPointValue().getStringValue()); - - PointValueAdnnotation pointValueAdnnotationAlphanumericShortText = new PointValueAdnnotation(); - pointValueAdnnotationAlphanumericShortText.setPointValueId(2); - pointValueAdnnotationAlphanumericShortText.setTextPointValueShort(pointValueAlphanumeric2.getPointValue().getStringValue()); - - //image - PointValueAdnnotation pointValueAdnnotationImage1= new PointValueAdnnotation(); - pointValueAdnnotationImage1.setPointValueId(3); - pointValueAdnnotationImage1.setTextPointValueShort(pointValueAlphanumeric2.getPointValue().getStringValue()); - - PointValueAdnnotation pointValueAdnnotationImage2= new PointValueAdnnotation(); - pointValueAdnnotationImage2.setPointValueId(4); - pointValueAdnnotationImage2.setTextPointValueShort(pointValueAlphanumeric2.getPointValue().getStringValue()); - - // changed value by USER; - // sourceType = 1 - //TODO - // changed value by EVENT_HANDLER - // soruceType = 2; - //TODO - // changed value by ANONYMOUS - // sourceType = 3 - //TODO - //changed value by POINT_LINK - // sourceType = 4 - - - // - // @formatter:on - // end populate data - - PointValueAdnnotationsDAO pointValuesAdnnotationsDAO = new PointValueAdnnotationsDAO(); - //CR - - // create - pointValuesAdnnotationsDAO.create(pointValueAdnnotationAlphanumericLongText); - pointValuesAdnnotationsDAO.create(pointValueAdnnotationAlphanumericShortText); - pointValuesAdnnotationsDAO.create(pointValueAdnnotationImage1); - pointValuesAdnnotationsDAO.create(pointValueAdnnotationImage2); - - // - - // read - // TODO because valueAdnnotations don't have pk error when adnnotation more then one - //find (adnnotations for every pointValues in test) - PointValueAdnnotation pointValueAdnnotationNewLongText = pointValuesAdnnotationsDAO.findById(new Object[] {1}); - boolean test1 = pointValueAdnnotationNewLongText.equals(pointValueAdnnotationAlphanumericLongText); - assertTrue(test1); - - PointValueAdnnotation pointValueAdnnotationNewShortText = pointValuesAdnnotationsDAO.findById(new Object[] {2}); - boolean test2 = pointValueAdnnotationNewShortText.equals(pointValueAdnnotationAlphanumericShortText); - assertTrue(test2); - - PointValueAdnnotation pointValueAdnnotationNewImage1 = pointValuesAdnnotationsDAO.findById(new Object[] {3}); - boolean test3 = pointValueAdnnotationNewImage1.equals(pointValueAdnnotationImage1); - assertTrue(test3); - - PointValueAdnnotation pointValueAdnnotationNewImage2 = pointValuesAdnnotationsDAO.findById(new Object[] {4}); - boolean test4 = pointValueAdnnotationNewImage2.equals(pointValueAdnnotationImage2); - assertTrue(test4); - - //filtered (values for every type point) - List valuesAdnnotationsFiltered = pointValuesAdnnotationsDAO.filtered( - PointValueAdnnotationsDAO.POINT_VALUE_ADNNOTATIONS_FILTER_BASE_ON_POINT_VALUES_ID, - new Object[]{1}, 10); - boolean testFiltered = (valuesAdnnotationsFiltered.size() == 1); - - assertTrue(testFiltered); - - //end CR - - } - -} diff --git a/test/org/scada_lts/dao/PointValueDAOTest.java b/test/org/scada_lts/dao/PointValueDAOTest.java index d3b5221bf2..92474d024b 100644 --- a/test/org/scada_lts/dao/PointValueDAOTest.java +++ b/test/org/scada_lts/dao/PointValueDAOTest.java @@ -2,15 +2,20 @@ import br.org.scadabr.db.utils.TestUtils; import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; +import com.serotonin.mango.vo.User; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import org.scada_lts.dao.model.point.PointValue; import org.scada_lts.dao.pointvalues.PointValueDAO; +import org.scada_lts.login.ILoggedUsers; import org.scada_lts.utils.ResultSetMock; -import org.scada_lts.web.beans.GetApplicationBeans; -import org.springframework.context.ApplicationContext; +import org.scada_lts.web.beans.ApplicationBeans; import java.sql.ResultSet; import java.sql.SQLException; @@ -18,10 +23,15 @@ import java.util.Map; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.when; -public class PointValueDAOTest extends TestDAO { +@RunWith(PowerMockRunner.class) +@PrepareForTest({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 PointValueDAOTest { private Map rowExample; private ResultSet resultSet; @@ -29,15 +39,21 @@ public class PointValueDAOTest extends TestDAO { private final int sourceId = 111111; @Before - public void setUp(){ - ApplicationContext applicationContextMock = mock(ApplicationContext.class); + public void setup() { + IUserDAO userDaoMock = mock(IUserDAO.class); - when(userDaoMock.getUser(11111)).thenReturn(TestUtils.newUser(11111, "admin")); - when(applicationContextMock.getBean(eq("userDaoWithCache"))).thenReturn(userDaoMock); - new GetApplicationBeans().setApplicationContext(applicationContextMock); + when(userDaoMock.getUser(sourceId)).thenReturn(TestUtils.newUser(sourceId, "admin")); + + User user = TestUtils.newUser(sourceId, "admin"); + ILoggedUsers loggedUsers = mock(ILoggedUsers.class); + when(loggedUsers.getUser(eq(sourceId))).thenReturn(user); + + mockStatic(ApplicationBeans.class); + when(ApplicationBeans.getLoggedUsersBean()).thenReturn(loggedUsers); + rowExample = new HashMap<>(); - rowExample.put("dataType",33333); - rowExample.put("dataPointId",333332); + rowExample.put("dataType",1); + rowExample.put("dataPointId",123); rowExample.put("sourceId",sourceId); rowExample.put("sourceType",1); rowExample.put("username", username); @@ -46,17 +62,30 @@ public void setUp(){ } @Test - public void doPointValueContainsGivenUserNameFromResultSetTest() throws SQLException { - PointValue pointValue = new PointValueDAO.PointValueRowMapper().mapRow(resultSet,1); + public void when_mapRow_to_PointValue_then_sourceId() throws SQLException { + + //given: + PointValueDAO.PointValueRowMapper mapper = new PointValueDAO.PointValueRowMapper(); + + //when: + PointValue pointValue = mapper.mapRow(resultSet,1); AnnotatedPointValueTime annotatedPointValueTime = (AnnotatedPointValueTime) pointValue.getPointValue(); + + //then: Assert.assertEquals(sourceId, annotatedPointValueTime.getSourceId()); } - @After - public void tearDown() { - // drop database; - resultSet = null; - rowExample = null; - LOG.info("End test "); + @Test + public void when_mapRow_to_PointValue_then_sourceDescriptionArgument_same_username() throws SQLException { + + //given: + PointValueDAO.PointValueRowMapper mapper = new PointValueDAO.PointValueRowMapper(); + + //when: + PointValue pointValue = mapper.mapRow(resultSet,1); + AnnotatedPointValueTime annotatedPointValueTime = (AnnotatedPointValueTime) pointValue.getPointValue(); + + //then: + Assert.assertEquals(username, annotatedPointValueTime.getSourceDescriptionArgument()); } } diff --git a/test/utils/PointValueDAOMemory.java b/test/utils/PointValueDAOMemory.java index b8f7a262e1..fb43931920 100644 --- a/test/utils/PointValueDAOMemory.java +++ b/test/utils/PointValueDAOMemory.java @@ -4,14 +4,16 @@ import com.serotonin.mango.rt.dataImage.AnnotatedPointValueTime; import com.serotonin.mango.rt.dataImage.PointValueTime; import com.serotonin.mango.rt.dataImage.SetPointSource; -import com.serotonin.mango.rt.dataImage.types.AlphanumericValue; import com.serotonin.mango.rt.dataImage.types.MangoValue; -import com.serotonin.mango.vo.User; +import com.serotonin.mango.rt.event.handlers.SetPointHandlerRT; +import com.serotonin.mango.rt.link.PointLinkRT; +import com.serotonin.mango.vo.AnonymousUser; import com.serotonin.mango.vo.bean.LongPair; import com.serotonin.mango.vo.bean.PointHistoryCount; +import com.serotonin.mango.vo.event.EventHandlerVO; +import com.serotonin.mango.vo.link.PointLinkVO; import org.scada_lts.dao.IUserDAO; import org.scada_lts.dao.model.point.PointValue; -import org.scada_lts.dao.model.point.PointValueAdnnotation; import org.scada_lts.dao.pointvalues.IPointValueDAO; import java.util.HashMap; @@ -19,11 +21,14 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicLong; +import static com.serotonin.mango.util.AnnotatedPointValueUtils.createAnnotatedPointValueTime; + public class PointValueDAOMemory implements IPointValueDAO { private final Map pointValues; private final Map pointValuesAnno; private static final AtomicLong serial = new AtomicLong(222); + private static final AtomicLong annoSerial = new AtomicLong(111); private final IUserDAO usersDAO; @@ -60,16 +65,10 @@ public int createAnnotation(long pointValueId, String textPointValueShort, Strin public synchronized PointValueTime getPointValue(long id) { if(pointValuesAnno.containsKey(id)) { AnnotatedPointValueTime annotatedPointValueTime = pointValuesAnno.get(id); - PointValueTime pointValueTime = pointValues.get(id); - User user = usersDAO.getUser(annotatedPointValueTime.getSourceId()); - annotatedPointValueTime.setSourceDescriptionArgument(user.getUsername()); - if(pointValueTime.getValue() instanceof AlphanumericValue) { - return annotatedPointValueTime; - } else { - AnnotatedPointValueTime annotatedPointValueTime1 = new AnnotatedPointValueTime(pointValueTime.getValue(), pointValueTime.getTime(), SetPointSource.Types.USER, user.getId()); - annotatedPointValueTime1.setSourceDescriptionArgument(user.getUsername()); - return annotatedPointValueTime1; + if(annotatedPointValueTime.getSourceType() == SetPointSource.Types.USER) { + annotatedPointValueTime.setSourceDescriptionArgument(usersDAO.getUser(annotatedPointValueTime.getSourceId()).getUsername()); } + return annotatedPointValueTime; } return pointValues.get(id); } @@ -91,126 +90,146 @@ public synchronized void clear() { @Override public List findAll() { - return null; + throw new UnsupportedOperationException(); } @Override public PointValue findById(Object[] pk) { - return null; + throw new UnsupportedOperationException(); } @Override public List findByIdAndTs(long id, long ts) { - return null; + throw new UnsupportedOperationException(); } @Override public List filtered(String filter, Object[] argsFilter, long limit) { - return null; + throw new UnsupportedOperationException(); } @Override public Object[] create(PointValue entity) { - return new Object[0]; + throw new UnsupportedOperationException(); } @Override public Object[] createNoTransaction(int pointId, int dataType, double dvalue, long time) { - return new Object[0]; + throw new UnsupportedOperationException(); } @Override public void executeBatchUpdateInsert(List params) { - + throw new UnsupportedOperationException(); } @Override public Long getInceptionDate(int dataPointId) { - return null; + throw new UnsupportedOperationException(); } @Override public long dateRangeCount(int dataPointId, long from, long to) { - return 0; + throw new UnsupportedOperationException(); } @Override public LongPair getStartAndEndTime(List dataPointIds) { - return null; + throw new UnsupportedOperationException(); } @Override public long getStartTime(List dataPointIds) { - return 0; + throw new UnsupportedOperationException(); } @Override public long getEndTime(List dataPointIds) { - return 0; + throw new UnsupportedOperationException(); } @Override public List getFiledataIds() { - return null; + throw new UnsupportedOperationException(); } @Override public Long getLatestPointValue(int dataPointId) { - return null; + PointValueTime pointValue = getPointValue(dataPointId); + if(pointValue == null) + return null; + return pointValue.getTime(); } @Override public double applyBounds(double value) { - return 0; + if (Double.isNaN(value)) + return 0; + if (value == Double.POSITIVE_INFINITY) + return Double.MAX_VALUE; + if (value == Double.NEGATIVE_INFINITY) + return -Double.MAX_VALUE; + + return value; } @Override public long deletePointValuesBeforeWithOutLast(int dataPointId, long time) { - return 0; + throw new UnsupportedOperationException(); } @Override public long deletePointValuesBeforeWithOutLastTwo(int dataPointId, long time) { - return 0; + throw new UnsupportedOperationException(); } @Override public long deletePointValue(int dataPointId) { - return 0; + throw new UnsupportedOperationException(); } @Override public long deleteAllPointData() { - return 0; + throw new UnsupportedOperationException(); } @Override public long deletePointValuesWithMismatchedType(int dataPointId, int dataType) { - return 0; + throw new UnsupportedOperationException(); } @Override public long deletePointValuesWithValueLimit(int dataPointId, int limit) { - return 0; + throw new UnsupportedOperationException(); } @Override public long getMinTs(int dataPointId) { - return 0; + throw new UnsupportedOperationException(); } @Override public long getMaxTs(int dataPointId) { - return 0; + throw new UnsupportedOperationException(); } @Override public List getTopPointHistoryCounts() { - return null; + throw new UnsupportedOperationException(); } @Override public void updateAnnotation(int userId) { + throw new UnsupportedOperationException(); + } + @Override + public PointValueTime getPointValueBefore(int dataPointId, long time) { + throw new UnsupportedOperationException(); + } + + @Override + public PointValueTime getPointValueAt(int dataPointId, long time) { + throw new UnsupportedOperationException(); } } diff --git a/test/utils/mock/MockUtils.java b/test/utils/mock/MockUtils.java index f0a3212051..2122f62ec6 100644 --- a/test/utils/mock/MockUtils.java +++ b/test/utils/mock/MockUtils.java @@ -4,6 +4,7 @@ import com.serotonin.mango.db.dao.PointValueDao; import com.serotonin.mango.db.dao.UserDao; import com.serotonin.mango.rt.RuntimeManager; +import com.serotonin.mango.rt.maint.BackgroundProcessing; import com.serotonin.mango.vo.User; import com.serotonin.mango.web.ContextWrapper; import com.serotonin.util.PropertiesUtils; @@ -29,10 +30,12 @@ public static void configMock(RuntimeManager runtimeManager, User user) throws E ContextWrapper contextWrapper = mock(ContextWrapper.class); ServletContext servletContext = new ServletContextMock(a -> a.contains("scriptFunctions") ? "test/scriptFunctions.js" : "".equals(a) ? "test/" : ""); + BackgroundProcessing backgroundProcessing = mock(BackgroundProcessing.class); Common.ctx = contextWrapper; when(contextWrapper.getRuntimeManager()).thenReturn(runtimeManager); when(contextWrapper.getServletContext()).thenReturn(servletContext); + when(contextWrapper.getBackgroundProcessing()).thenReturn(backgroundProcessing); PointValueDao pointValueDao = mock(PointValueDao.class); whenNew(PointValueDao.class) diff --git a/webapp-resources/messages_de.properties b/webapp-resources/messages_de.properties index 2b5b9e6739..a3ee01559b 100644 --- a/webapp-resources/messages_de.properties +++ b/webapp-resources/messages_de.properties @@ -3334,4 +3334,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_en.properties b/webapp-resources/messages_en.properties index 2c75526a76..b30109299b 100644 --- a/webapp-resources/messages_en.properties +++ b/webapp-resources/messages_en.properties @@ -3337,4 +3337,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_es.properties b/webapp-resources/messages_es.properties index 4039c70224..d34a747fdd 100644 --- a/webapp-resources/messages_es.properties +++ b/webapp-resources/messages_es.properties @@ -3377,4 +3377,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_fi.properties b/webapp-resources/messages_fi.properties index f3d9c7b23a..812f1fe756 100644 --- a/webapp-resources/messages_fi.properties +++ b/webapp-resources/messages_fi.properties @@ -3463,4 +3463,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_fr.properties b/webapp-resources/messages_fr.properties index b37b69350f..4a1d179507 100644 --- a/webapp-resources/messages_fr.properties +++ b/webapp-resources/messages_fr.properties @@ -3331,4 +3331,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_lu.properties b/webapp-resources/messages_lu.properties index fcffdadd8d..56025f852b 100644 --- a/webapp-resources/messages_lu.properties +++ b/webapp-resources/messages_lu.properties @@ -3350,4 +3350,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_nl.properties b/webapp-resources/messages_nl.properties index dc9ff02d3b..cc838b5d15 100644 --- a/webapp-resources/messages_nl.properties +++ b/webapp-resources/messages_nl.properties @@ -3453,4 +3453,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_pl.properties b/webapp-resources/messages_pl.properties index d41ffc1c60..aef65b4b72 100644 --- a/webapp-resources/messages_pl.properties +++ b/webapp-resources/messages_pl.properties @@ -3476,3 +3476,4 @@ systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API diff --git a/webapp-resources/messages_pt.properties b/webapp-resources/messages_pt.properties index eb16fbfd9a..94316ea501 100644 --- a/webapp-resources/messages_pt.properties +++ b/webapp-resources/messages_pt.properties @@ -3489,4 +3489,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_ru.properties b/webapp-resources/messages_ru.properties index b99c28e26f..4aba684182 100644 --- a/webapp-resources/messages_ru.properties +++ b/webapp-resources/messages_ru.properties @@ -3485,4 +3485,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file diff --git a/webapp-resources/messages_zh.properties b/webapp-resources/messages_zh.properties index 25c80922a9..7d451f2719 100644 --- a/webapp-resources/messages_zh.properties +++ b/webapp-resources/messages_zh.properties @@ -3438,4 +3438,5 @@ common.addPoint=Add point systemsettings.webresource.uploads.path=Uploads images path systemsettings.webresource.graphics.path=Graphics images path systemsettings.webresource.uploads.path.wrong=Uploaded images save path must end with "uploads" or "uploads{0}" -systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" \ No newline at end of file +systemsettings.webresource.graphics.path.wrong=Graphics images path must end with "graphics" or "graphics{0}" +annotation.api=REST API \ No newline at end of file From 4cbfaca5f9e005c5db1fb7591281bf62011b63e9 Mon Sep 17 00:00:00 2001 From: Kamil Date: Tue, 20 Feb 2024 12:54:09 +0100 Subject: [PATCH 6/6] #2798 Corrected History Annotation Change Point Value By User : - corrected DataPointSynchronizedRT; - corrected PointValueStateUtils.isSetPoint include source: User, PointLinkSetPointSource, RestApiSource; - corrected PointValueCacheTest; --- .../mango/rt/dataImage/DataPointRT.java | 8 +++--- .../rt/dataImage/DataPointSynchronizedRT.java | 6 +++-- .../scada_lts/utils/PointValueStateUtils.java | 10 ++++--- .../rt/dataImage/PointValueCacheTest.java | 27 ++++++++++--------- 4 files changed, 29 insertions(+), 22 deletions(-) diff --git a/src/com/serotonin/mango/rt/dataImage/DataPointRT.java b/src/com/serotonin/mango/rt/dataImage/DataPointRT.java index b74d0dc75e..a7e621b84a 100644 --- a/src/com/serotonin/mango/rt/dataImage/DataPointRT.java +++ b/src/com/serotonin/mango/rt/dataImage/DataPointRT.java @@ -50,7 +50,7 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import static org.scada_lts.utils.PointValueStateUtils.isSetPointHandler; +import static org.scada_lts.utils.PointValueStateUtils.isSetPoint; public class DataPointRT implements IDataPoint, ILifecycle, TimeoutClient, ScadaWebSockets { private static final Log LOG = LogFactory.getLog(DataPointRT.class); @@ -237,10 +237,10 @@ protected void savePointValue(PointValueTime newValue, SetPointSource source, return; } - boolean isSetPointHandler = isSetPointHandler(source); + boolean isSetPoint = isSetPoint(source); boolean backdated = pointValue != null && newValue.getTime() < pointValue.getTime() - && !isSetPointHandler; + && !isSetPoint; // Determine whether the new value qualifies for logging. boolean logValue; @@ -303,7 +303,7 @@ else if (backdated) // Ignore historical values. - if (pointValue == null || newValue.getTime() >= pointValue.getTime() || isSetPointHandler) { + if (pointValue == null || newValue.getTime() >= pointValue.getTime() || isSetPoint) { PointValueTime oldValue = pointValue; pointValue = newValue; fireEvents(oldValue, newValue, source != null, false); diff --git a/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java b/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java index 1d10724ebd..cacc798699 100644 --- a/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java +++ b/src/com/serotonin/mango/rt/dataImage/DataPointSynchronizedRT.java @@ -188,8 +188,10 @@ public String toString() { private Optional createAndUpdateState(PointValueTime newValue, DataPointVO vo, SetPointSource source) { lock.writeLock().lock(); try { - pointValueState = PointValueState.newState(newValue, pointValueState, vo, source); - return Optional.of(pointValueState); + PointValueState state = PointValueState.newState(newValue, pointValueState, vo, source); + if(!state.isBackdated()) + pointValueState = state; + return Optional.of(state); } catch(Exception ex) { LOG.error(ex.getMessage(), ex); return Optional.empty(); diff --git a/src/org/scada_lts/utils/PointValueStateUtils.java b/src/org/scada_lts/utils/PointValueStateUtils.java index a310d755ef..31848ed516 100644 --- a/src/org/scada_lts/utils/PointValueStateUtils.java +++ b/src/org/scada_lts/utils/PointValueStateUtils.java @@ -1,11 +1,14 @@ package org.scada_lts.utils; +import com.serotonin.mango.rt.dataImage.PointLinkSetPointSource; import com.serotonin.mango.rt.dataImage.PointValueState; import com.serotonin.mango.rt.dataImage.PointValueTime; import com.serotonin.mango.rt.dataImage.SetPointSource; import com.serotonin.mango.rt.dataImage.types.NumericValue; import com.serotonin.mango.rt.event.handlers.SetPointHandlerRT; import com.serotonin.mango.vo.DataPointVO; +import com.serotonin.mango.vo.RestApiSource; +import com.serotonin.mango.vo.User; import com.serotonin.util.ObjectUtils; public final class PointValueStateUtils { @@ -63,11 +66,12 @@ public static boolean isSaveValue(DataPointVO vo, boolean logValue) { public static boolean isBackdated(PointValueTime newValue, PointValueState oldState, SetPointSource source) { return newValue != null && !oldState.isEmpty() && newValue.getTime() < oldState.getNewValue().getTime() - && !isSetPointHandler(source); + && !isSetPoint(source); } - public static boolean isSetPointHandler(SetPointSource source) { - return source instanceof SetPointHandlerRT; + public static boolean isSetPoint(SetPointSource source) { + return source instanceof SetPointHandlerRT || source instanceof User + || source instanceof PointLinkSetPointSource || source instanceof RestApiSource; } private static boolean isChange(PointValueTime newValue, PointValueState oldState, diff --git a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java index 076199411c..be4f8410fa 100644 --- a/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java +++ b/test/com/serotonin/mango/rt/dataImage/PointValueCacheTest.java @@ -12,6 +12,7 @@ import com.serotonin.mango.vo.event.EventHandlerVO; import com.serotonin.mango.vo.link.PointLinkVO; import com.serotonin.mango.web.ContextWrapper; +import com.serotonin.web.taglib.DateFunctions; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -44,6 +45,8 @@ public class PointValueCacheTest { private PointValueCache pointValueCache; private PointValueTime pvt; private User sourceUser; + private String annotatedPointValueTimeToStringExpected; + private String pointValueTimeToStringExpected; @Before public void config() throws Exception { @@ -76,9 +79,13 @@ public void config() throws Exception { mockStatic(Common.class); when(Common.getUser()).thenReturn(sourceUser); when(Common.getBundle()).thenReturn(ResourceBundle.getBundle("messages")); + long time = 1708165754243L; - pvt = new PointValueTime(MangoValue.stringToValue("1", DataTypes.BINARY), 1708165754243L); + pvt = new PointValueTime(MangoValue.stringToValue("1", DataTypes.BINARY), time); pointValueCache = new PointValueCache(-1, 1); + + annotatedPointValueTimeToStringExpected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@" + DateFunctions.getTime(time) + ")"; + pointValueTimeToStringExpected = "PointValueTime(true@" + DateFunctions.getTime(time) + ")"; } @Test @@ -98,14 +105,13 @@ public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_l public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_for_User_then_toString() { //given: - String expected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@Feb 17 11:29)"; pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, false, false); //when: PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertEquals(expected, pvt.toString()); + Assert.assertEquals(annotatedPointValueTimeToStringExpected, pvt.toString()); } @Test @@ -153,14 +159,13 @@ public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_s public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_for_User_then_toString() { //given: - String expected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@Feb 17 11:29)"; pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, true, false); //when: PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertEquals(expected, pvt.toString()); + Assert.assertEquals(annotatedPointValueTimeToStringExpected, pvt.toString()); } @Test @@ -208,14 +213,13 @@ public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_a public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_for_User_then_toString() { //given: - String expected = "AnnotatedPointValueTime(" + sourceUser.getUsername() + " -- true@Feb 17 11:29)"; pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, sourceUser, true, true); //when: PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertEquals(expected, pvt.toString()); + Assert.assertEquals(annotatedPointValueTimeToStringExpected, pvt.toString()); } @Test @@ -263,14 +267,13 @@ public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_l public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_logValue_false_source_null_then_toString() { //given: - String expected = "PointValueTime(true@Feb 17 11:29)"; pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, false, false); //when: PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertEquals(expected, pvt.toString()); + Assert.assertEquals(pointValueTimeToStringExpected, pvt.toString()); } @Test @@ -290,14 +293,13 @@ public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_s public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_sync_source_null_then_toString() { //given: - String expected = "PointValueTime(true@Feb 17 11:29)"; pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, true, false); //when: PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertEquals(expected, pvt.toString()); + Assert.assertEquals(pointValueTimeToStringExpected, pvt.toString()); } @Test @@ -317,13 +319,12 @@ public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_a public void when_getLatestPointValue_after_savePointValueIntoDaoAndCacheUpdate_async_source_null_then_toString() { //given: - String expected = "PointValueTime(true@Feb 17 11:29)"; pointValueCache.savePointValueIntoDaoAndCacheUpdate(pvt, null, true, true); //when: PointValueTime pvt = pointValueCache.getLatestPointValue(); //then: - Assert.assertEquals(expected, pvt.toString()); + Assert.assertEquals(pointValueTimeToStringExpected, pvt.toString()); } }