Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Added AssetEvent and removed LocationEvent (location updates just go through standard AttributeEvent mechanism), some cleanup of model

Rich Turnerbd45bd7a8e18
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java
index ced40cd36..76455172c 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java
@@ -33,10 +33,7 @@ import org.openremote.app.client.interop.value.ObjectValueMapper;
import org.openremote.app.client.simulator.Simulator;
import org.openremote.app.client.widget.FormButton;
import org.openremote.model.Constants;
-import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.asset.AssetResource;
-import org.openremote.model.asset.AssetType;
-import org.openremote.model.asset.ReadAssetAttributesEvent;
+import org.openremote.model.asset.*;
import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.AgentResource;
import org.openremote.model.asset.agent.AgentStatusEvent;
@@ -190,7 +187,7 @@ public class AssetViewActivity
if (subscribe) {
environment.getEventService().subscribe(
AttributeEvent.class,
- new AttributeEvent.EntityIdFilter(asset.getId())
+ new AssetEvent.AssetIdFilter(asset.getId())
);
} else {
environment.getEventService().unsubscribe(
diff --git a/client/src/main/java/org/openremote/app/client/map/MapActivity.java b/client/src/main/java/org/openremote/app/client/map/MapActivity.java
index 10b5ac254..b42a3fbcd 100644
--- a/client/src/main/java/org/openremote/app/client/map/MapActivity.java
+++ b/client/src/main/java/org/openremote/app/client/map/MapActivity.java
@@ -33,6 +33,7 @@ import org.openremote.app.client.mvp.AcceptsView;
import org.openremote.app.client.mvp.AppActivity;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetEvent;
import org.openremote.model.asset.AssetResource;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeValueDescriptor;
@@ -180,7 +181,7 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
showAssetInfoItems();
environment.getEventService().subscribe(
AttributeEvent.class,
- new AttributeEvent.EntityIdFilter(asset.getId())
+ new AssetEvent.AssetIdFilter(asset.getId())
);
}
});
diff --git a/client/src/main/webapp/src/or-app/or-app-events.html b/client/src/main/webapp/src/or-app/or-app-events.html
index fed43affd..6ae370090 100644
--- a/client/src/main/webapp/src/or-app/or-app-events.html
+++ b/client/src/main/webapp/src/or-app/or-app-events.html
@@ -41,8 +41,8 @@
this.subscribe({
eventType: "attribute",
filter: {
- filterType: "attribute-entity-id",
- entityIds: assetIds
+ filterType: "asset-id",
+ assetIds: assetIds
}
});
}
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java
index d5c9b4198..308140a47 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java
@@ -35,7 +35,7 @@ public class PersistenceEvent<T> {
public static final String HEADER_ENTITY_TYPE = PersistenceEvent.class.getSimpleName() + ".ENTITY_TYPE";
public enum Cause {
- INSERT, UPDATE, DELETE
+ CREATE, UPDATE, DELETE
}
public static Predicate isPersistenceEventForEntityType(Class<?> type) {
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java b/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java
index b70e22dcf..9e7da161a 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java
@@ -55,7 +55,7 @@ public class PersistenceEventInterceptor extends EmptyInterceptor {
Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
persistenceEvents.add(new PersistenceEvent(
- PersistenceEvent.Cause.INSERT,
+ PersistenceEvent.Cause.CREATE,
entity,
propertyNames,
state
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
index dbafd5c41..a4a9cf717 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
@@ -294,7 +294,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
LOG.finest("Processing agent persistence event: " + persistenceEvent.getCause());
switch (persistenceEvent.getCause()) {
- case INSERT:
+ case CREATE:
addReplaceAgent(agent);
linkProtocolConfigurations(
agent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)
@@ -365,7 +365,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
LOG.finest("Processing asset persistence event: " + persistenceEvent.getCause());
switch (persistenceEvent.getCause()) {
- case INSERT:
+ case CREATE:
// Asset insert persistence events can be fired before the agent insert persistence event
// so need to check that all protocol configs exist - any that don't we will exclude here
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 96dd17d07..b11619843 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -160,15 +160,24 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
clientEventService = container.getService(ClientEventService.class);
clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {
- if (!subscription.isEventType(AttributeEvent.class)) {
+ if (!subscription.isEventType(AttributeEvent.class) && !subscription.isEventType(AssetEvent.class)) {
return false;
}
- // Always must have a filter, as you can't subscribe to ALL asset attribute events
- if (subscription.getFilter() != null && subscription.getFilter() instanceof AttributeEvent.EntityIdFilter) {
- AttributeEvent.EntityIdFilter filter = (AttributeEvent.EntityIdFilter) subscription.getFilter();
+ // Only Asset ID filters allowed
+ if (subscription.getFilter() != null && !(subscription.getFilter() instanceof AssetEvent.AssetIdFilter)) {
+ return false;
+ }
+
+ // Attribute event subscriptions must have a filter, as you can't subscribe to ALL asset attribute events
+ if (subscription.isEventType(AttributeEvent.class) && subscription.getFilter() == null) {
+ return false;
+ }
+
+ if (subscription.getFilter() != null) {
+ AssetEvent.AssetIdFilter filter = (AssetEvent.AssetIdFilter) subscription.getFilter();
- // Superuser can get attribute events for any asset
+ // Superuser can get events for any asset
if (auth.isSuperUser())
return true;
@@ -180,18 +189,18 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
boolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth.getUserId());
// Client can subscribe to several assets
- for (String assetId : filter.getEntityIds()) {
+ for (String assetId : filter.getAssetIds()) {
Asset asset = assetStorageService.find(assetId);
// If the asset doesn't exist, subscription must fail
if (asset == null)
return false;
if (isRestrictedUser) {
- // Restricted users can only get attribute events for their linked assets
+ // Restricted users can only get events for their linked assets
if (!assetStorageService.isUserAsset(auth.getUserId(), assetId))
return false;
// TODO Restricted clients should only receive events for RESTRICTED_READ attributes!
} else {
- // Regular users can only get attribute events for assets in their realm
+ // Regular users can only get events for assets in their realm
if (!asset.getRealm().equals(auth.getAuthenticatedRealm()))
return false;
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 42579aec2..174fa06b4 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -46,7 +46,6 @@ import org.openremote.model.Constants;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.MetaItemDescriptor;
import org.openremote.model.attribute.MetaItemType;
import org.openremote.model.calendar.CalendarEvent;
@@ -75,19 +74,18 @@ import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.stream.Stream;
+import java.util.stream.Collectors;
import static java.util.stream.Collectors.joining;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForEntityType;
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;
import static org.openremote.manager.event.ClientEventService.getSessionKey;
-import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
+import static org.openremote.model.asset.AssetAttribute.*;
import static org.openremote.model.query.BaseAssetQuery.*;
import static org.openremote.model.query.BaseAssetQuery.Access.PRIVATE_READ;
import static org.openremote.model.query.BaseAssetQuery.Access.RESTRICTED_READ;
-import static org.openremote.model.query.BaseAssetQuery.Include.ALL;
-import static org.openremote.model.query.BaseAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;
+import static org.openremote.model.query.BaseAssetQuery.Include.*;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetStorageService extends RouteBuilder implements ContainerService {
@@ -109,15 +107,64 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
+ protected interface ParameterBinder extends Consumer<PreparedStatement> {
+
+ @Override
+ default void accept(PreparedStatement st) {
+ try {
+ acceptStatement(st);
+ } catch (SQLException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ void acceptStatement(PreparedStatement st) throws SQLException;
+ }
+ private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());
protected static String META_ITEM_RESTRICTED_READ_SQL_FRAGMENT;
protected static String META_ITEM_PUBLIC_READ_SQL_FRAGMENT;
- private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());
-
protected TimerService timerService;
protected PersistenceService persistenceService;
protected ManagerIdentityService identityService;
protected ClientEventService clientEventService;
+ protected static boolean calendarEventPredicateMatches(CalendarEventActivePredicate eventActivePredicate, Asset asset) {
+ return CalendarEventConfiguration.getCalendarEvent(asset)
+ .map(calendarEvent -> calendarEventActiveOn(calendarEvent,
+ new Date(1000L * eventActivePredicate.timestampSeconds)))
+ .orElse(true);
+ }
+
+ protected static boolean calendarEventActiveOn(CalendarEvent calendarEvent, Date when) {
+ if (calendarEvent.getRecurrence() == null) {
+ return (!when.before(calendarEvent.getStart()) && !when.after(calendarEvent.getEnd()));
+ }
+
+ RecurrenceRule recurrenceRule = calendarEvent.getRecurrence();
+ Recur recurrence;
+
+ if (recurrenceRule.getCount() != null) {
+ recurrence = new Recur(recurrenceRule.getFrequency().name(), recurrenceRule.getCount());
+ } else if (recurrenceRule.getUntil() != null) {
+ recurrence = new Recur(recurrenceRule.getFrequency().name(),
+ new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));
+ } else {
+ recurrence = new Recur(recurrenceRule.getFrequency().name(), null);
+ }
+
+ if (recurrenceRule.getInterval() != null) {
+ recurrence.setInterval(recurrenceRule.getInterval());
+ }
+
+ RRule rRule = new RRule(recurrence);
+ VEvent vEvent = new VEvent(new DateTime(calendarEvent.getStart()),
+ new DateTime(calendarEvent.getEnd()), "");
+ vEvent.getProperties().add(rRule);
+ Period period = new Period(new DateTime(when), new Dur(0, 0, 1, 0));
+ PeriodRule periodRule = new PeriodRule(period);
+ return periodRule.evaluate(vEvent);
+ }
+
@Override
public int getPriority() {
return ContainerService.DEFAULT_PRIORITY;
@@ -137,34 +184,33 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
" ('" + Arrays.stream(AssetModelUtil.getMetaItemDescriptors()).filter(i -> i.getAccess().publicRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";
clientEventService.addSubscriptionAuthorizer((auth, subscription) ->
- (subscription.isEventType(AssetTreeModifiedEvent.class) || subscription.isEventType(
- LocationEvent.class))
- && identityService.getIdentityProvider().canSubscribeWith(
- auth,
- subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,
- ClientRole.READ_ASSETS)
+ (subscription.isEventType(AssetTreeModifiedEvent.class))
+ && identityService.getIdentityProvider().canSubscribeWith(
+ auth,
+ subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,
+ ClientRole.READ_ASSETS)
);
container.getService(ManagerWebService.class).getApiSingletons().add(
- new AssetModelResourceImpl(
- container.getService(TimerService.class),
- identityService
- )
+ new AssetModelResourceImpl(
+ container.getService(TimerService.class),
+ identityService
+ )
);
container.getService(ManagerWebService.class).getApiSingletons().add(
- new AssetResourceImpl(
- container.getService(TimerService.class),
- identityService,
- this,
- container.getService(MessageBrokerService.class)
- )
+ new AssetResourceImpl(
+ container.getService(TimerService.class),
+ identityService,
+ this,
+ container.getService(MessageBrokerService.class)
+ )
);
container.getService(ManagerWebService.class).getApiSingletons().add(
- new ConsoleResourceImpl(container.getService(TimerService.class),
- identityService,
- this)
+ new ConsoleResourceImpl(container.getService(TimerService.class),
+ identityService,
+ this)
);
container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
@@ -184,47 +230,47 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
public void configure() throws Exception {
// If any asset was modified in the database, publish events
from(PERSISTENCE_TOPIC)
- .routeId("AssetPersistenceChanges")
- .filter(isPersistenceEventForEntityType(Asset.class))
- .process(exchange -> publishModificationEvents(exchange.getIn().getBody(PersistenceEvent.class)));
+ .routeId("AssetPersistenceChanges")
+ .filter(isPersistenceEventForEntityType(Asset.class))
+ .process(exchange -> publishModificationEvents(exchange.getIn().getBody(PersistenceEvent.class)));
- // React if a client wants to read attribute state
+ // React if a client wants to read assets and attributes
from(CLIENT_EVENT_TOPIC)
- .routeId("FromClientReadRequests")
- .filter(body().isInstanceOf(ReadAssetAttributesEvent.class))
- .process(exchange -> {
- ReadAssetAttributesEvent event = exchange.getIn().getBody(ReadAssetAttributesEvent.class);
- LOG.fine("Handling from client: " + event);
-
- if (event.getAssetId() == null || event.getAssetId().isEmpty())
- return;
-
- String sessionKey = getSessionKey(exchange);
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
-
- // Superuser can get all
- if (authContext.isSuperUser()) {
- Asset asset = find(event.getAssetId(), true);
- if (asset != null)
- replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, event.getAttributeNames());
- return;
- }
+ .routeId("FromClientReadRequests")
+ .filter(exchange ->
+ (exchange.getIn().getBody() instanceof ReadAssetAttributesEvent) || (exchange.getIn().getBody() instanceof ReadAssetEvent))
+ .process(exchange -> {
+ ReadAssetEvent event = exchange.getIn().getBody(ReadAssetEvent.class);
+ LOG.fine("Handling from client: " + event);
+ boolean isAttributeRead = event instanceof ReadAssetAttributesEvent;
- // User must have role
- if (!authContext.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- return;
- }
+ if (event.getAssetId() == null || event.getAssetId().isEmpty())
+ return;
- Asset asset = find(
- event.getAssetId(),
- true,
- identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? RESTRICTED_READ : PRIVATE_READ
- );
- if (asset != null) {
- replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, event.getAttributeNames());
- }
- });
+ String sessionKey = getSessionKey(exchange);
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+
+
+ // Superuser can get all, User must have role
+ if (!authContext.isSuperUser() && !authContext.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
+ return;
+ }
+
+ Access access = authContext.isSuperUser() || !identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? PRIVATE_READ : RESTRICTED_READ;
+ Asset asset = find(
+ new AssetQuery()
+ .select(new Select(ALL, access))
+ .id(event.getAssetId()));
+
+ if (asset != null) {
+ if (isAttributeRead) {
+ replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, ((ReadAssetAttributesEvent)event).getAttributeNames());
+ } else {
+ replyWithAssetEvent(sessionKey, event.getSubscriptionId(), asset);
+ }
+ }
+ });
}
public Asset find(String assetId) {
@@ -257,7 +303,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)).id(
- assetId));
+ assetId));
}
public Asset find(BaseAssetQuery query) {
@@ -286,9 +332,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// TODO: Do this in a loop in reasonably sized batches
return persistenceService.doReturningTransaction(em -> {
List<Object[]> result = em.createQuery("select a.id, a.name from Asset a where a.id in :ids",
- Object[].class)
- .setParameter("ids", Arrays.asList(ids))
- .getResultList();
+ Object[].class)
+ .setParameter("ids", Arrays.asList(ids))
+ .getResultList();
List<String> names = new ArrayList<>();
for (String id : ids) {
for (Object[] tuple : result) {
@@ -426,7 +472,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
Asset asset = em.find(Asset.class, assetId);
if (asset != null) {
List<Asset> children = findAll(em, new AssetQuery()
- .parent(new ParentPredicate(asset.getId()))
+ .parent(new ParentPredicate(asset.getId()))
);
if (children.size() > 0)
return false;
@@ -438,19 +484,19 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
public boolean isUserAsset(String assetId) {
- return isUserAsset((String)null, assetId);
+ return isUserAsset((String) null, assetId);
}
public boolean isUserAsset(String userId, String assetId) {
return persistenceService.doReturningTransaction(entityManager -> {
try {
String queryStr = TextUtil.isNullOrEmpty(userId) ?
- "select count(ua) from UserAsset ua where ua.id.assetId = :assetId" :
- "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId = :assetId";
+ "select count(ua) from UserAsset ua where ua.id.assetId = :assetId" :
+ "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId = :assetId";
TypedQuery<Long> query = entityManager.createQuery(
- queryStr,
- Long.class).setParameter("assetId", assetId);
+ queryStr,
+ Long.class).setParameter("assetId", assetId);
if (!TextUtil.isNullOrEmpty(userId)) {
query.setParameter("userId", userId);
@@ -482,11 +528,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
try {
return entityManager.createQuery(
- "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId in :assetIds",
- Long.class)
- .setParameter("userId", userId)
- .setParameter("assetIds", assetIds)
- .getSingleResult() == assetIds.size();
+ "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId in :assetIds",
+ Long.class)
+ .setParameter("userId", userId)
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
} catch (NoResultException ex) {
return false;
}
@@ -507,11 +553,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
try {
return entityManager.createQuery(
- "select count(a) from Asset a where a.realm = :realm and a.id in :assetIds",
- Long.class)
- .setParameter("realm", realm)
- .setParameter("assetIds", assetIds)
- .getSingleResult() == assetIds.size();
+ "select count(a) from Asset a where a.realm = :realm and a.id in :assetIds",
+ Long.class)
+ .setParameter("realm", realm)
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
} catch (NoResultException ex) {
return false;
}
@@ -566,6 +612,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
});
}
+ /* ####################################################################################### */
+
/**
* This used to automatically make the user restricted as well but this has been disabled as it no longer fitted
* with use cases.
@@ -591,30 +639,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
entityManager.merge(userAsset);
}
- /* ####################################################################################### */
-
- protected interface ParameterBinder extends Consumer<PreparedStatement> {
-
- @Override
- default void accept(PreparedStatement st) {
- try {
- acceptStatement(st);
- } catch (SQLException ex) {
- throw new RuntimeException(ex);
- }
- }
-
- void acceptStatement(PreparedStatement st) throws SQLException;
- }
-
protected Asset find(EntityManager em, String assetId, boolean loadComplete, Access access) {
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
return find(
- em,
- new AssetQuery().select(
- new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)
- ).id(assetId)
+ em,
+ new AssetQuery().select(
+ new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)
+ ).id(assetId)
);
}
@@ -698,13 +730,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append("select A.ID as ID, A.NAME as NAME, A.ACCESS_PUBLIC_READ as ACCESS_PUBLIC_READ");
sb.append(
- ", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM AS REALM");
+ ", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM AS REALM");
if (include == AssetQuery.Include.ONLY_ID_AND_NAME) {
return sb.toString();
}
switch (include) {
case ALL_EXCEPT_PATH_AND_ATTRIBUTES:
+ case ALL_EXCEPT_ATTRIBUTES:
case ALL_EXCEPT_PATH:
case ALL:
sb.append(", A.OBJ_VERSION as OBJ_VERSION");
@@ -716,14 +749,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
if (!recursive || level == 3) {
- if (include == ALL) {
+ if (include == ALL || include == ALL_EXCEPT_ATTRIBUTES) {
sb.append(", get_asset_tree_path(A.ID) as PATH");
} else {
sb.append(", NULL as PATH");
}
}
- if (include != ALL_EXCEPT_PATH_AND_ATTRIBUTES) {
+ if (include != ALL_EXCEPT_PATH_AND_ATTRIBUTES && include != ALL_EXCEPT_ATTRIBUTES) {
if (recursive && level != 3) {
sb.append(", A.ATTRIBUTES as ATTRIBUTES");
@@ -761,7 +794,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// Use sub-select for processing the attributes the meta inside each attribute is replaced with filtered meta
// (coalesce null to empty array because jsonb_set() with null will clear the whole object)
sb.append(
- "select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), false)) from jsonb_each(A.attributes) as AX");
+ "select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), false)) from jsonb_each(A.attributes) as AX");
// Use implicit inner join on meta array set to only select attributes with a non-private access meta item
sb.append(", jsonb_array_elements(AX.VALUE #> '{meta}') as AM");
// Use subquery to filter out meta items not marked as non-private access
@@ -790,9 +823,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (access != PRIVATE_READ) {
// Filter non-private access attributes
AttributeMetaPredicate accessPredicate =
- new AttributeMetaPredicate()
- .itemName(access == RESTRICTED_READ ? MetaItemType.ACCESS_RESTRICTED_READ : MetaItemType.ACCESS_PUBLIC_READ)
- .itemValue(new BooleanPredicate(true));
+ new AttributeMetaPredicate()
+ .itemName(access == RESTRICTED_READ ? MetaItemType.ACCESS_RESTRICTED_READ : MetaItemType.ACCESS_PUBLIC_READ)
+ .itemValue(new BooleanPredicate(true));
sb.append(buildAttributeMetaFilter(accessPredicate, binders));
}
@@ -817,8 +850,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
boolean includeRealmInfo = query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME &&
- query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES &&
- query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
+ query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES &&
+ query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
if ((!recursive || level == 3) && (includeRealmInfo || query.tenant != null)) {
sb.append("join PUBLIC.REALM R on R.NAME = A.REALM ");
@@ -1005,8 +1038,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributeMetaPredicate.itemNamePredicate != null) {
attributeMetaBuilder.append(attributeMetaPredicate.itemNamePredicate.caseSensitive
- ? " and AM.VALUE #>> '{name}'"
- : " and upper(AM.VALUE #>> '{name}')"
+ ? " and AM.VALUE #>> '{name}'"
+ : " and upper(AM.VALUE #>> '{name}')"
);
switch (attributeMetaPredicate.itemNamePredicate.match) {
case EXACT:
@@ -1028,8 +1061,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributeMetaPredicate.itemValuePredicate instanceof StringPredicate) {
StringPredicate stringPredicate = (StringPredicate) attributeMetaPredicate.itemValuePredicate;
attributeMetaBuilder.append(stringPredicate.caseSensitive
- ? " and AM.VALUE #>> '{value}'"
- : " and upper(AM.VALUE #>> '{value}')"
+ ? " and AM.VALUE #>> '{value}'"
+ : " and upper(AM.VALUE #>> '{value}')"
);
attributeMetaBuilder.append(buildMatchFilter(stringPredicate.match));
@@ -1038,15 +1071,15 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributeMetaPredicate.itemValuePredicate instanceof BooleanPredicate) {
BooleanPredicate booleanPredicate = (BooleanPredicate) attributeMetaPredicate.itemValuePredicate;
attributeMetaBuilder.append(" and AM.VALUE #> '{value}' = to_jsonb(")
- .append(booleanPredicate.value)
- .append(")");
+ .append(booleanPredicate.value)
+ .append(")");
} else if (attributeMetaPredicate.itemValuePredicate instanceof StringArrayPredicate) {
StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeMetaBuilder.append(stringPredicate.caseSensitive
- ? " and AM.VALUE #> '{value}' ->> " + i
- : " and upper(AM.VALUE #> '{value}' ->> " + i + ")"
+ ? " and AM.VALUE #> '{value}' ->> " + i
+ : " and upper(AM.VALUE #> '{value}' ->> " + i + ")"
);
attributeMetaBuilder.append(buildMatchFilter(stringPredicate.match));
final int pos = binders.size() + 1;
@@ -1063,8 +1096,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributePredicate.name != null) {
attributeBuilder.append(attributePredicate.name.caseSensitive
- ? " and AX.key"
- : " and upper(AX.key)"
+ ? " and AX.key"
+ : " and upper(AX.key)"
);
attributeBuilder.append(buildMatchFilter(attributePredicate.name.match));
@@ -1075,8 +1108,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributePredicate.value instanceof StringPredicate) {
StringPredicate stringPredicate = (StringPredicate) attributePredicate.value;
attributeBuilder.append(stringPredicate.caseSensitive
- ? " and AX.VALUE #>> '{value}'"
- : " and upper(AX.VALUE #>> '{value}')"
+ ? " and AX.VALUE #>> '{value}'"
+ : " and upper(AX.VALUE #>> '{value}')"
);
attributeBuilder.append(buildMatchFilter(stringPredicate.match));
final int pos = binders.size() + 1;
@@ -1084,15 +1117,15 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributePredicate.value instanceof BooleanPredicate) {
BooleanPredicate booleanPredicate = (BooleanPredicate) attributePredicate.value;
attributeBuilder.append(" and AX.VALUE #> '{value}' = to_jsonb(")
- .append(booleanPredicate.value)
- .append(")");
+ .append(booleanPredicate.value)
+ .append(")");
} else if (attributePredicate.value instanceof StringArrayPredicate) {
StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributePredicate.value;
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeBuilder.append(stringPredicate.caseSensitive
- ? " and AX.VALUE #> '{value}' ->> " + i
- : " and upper(AX.VALUE #> '{value}' ->> " + i + ")"
+ ? " and AX.VALUE #> '{value}' ->> " + i
+ : " and upper(AX.VALUE #> '{value}' ->> " + i + ")"
);
attributeBuilder.append(buildMatchFilter(stringPredicate.match));
final int pos = binders.size() + 1;
@@ -1253,44 +1286,40 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
return asset;
- case ALL_EXCEPT_PATH_AND_ATTRIBUTES:
- case ALL_EXCEPT_PATH:
- case ALL:
+ default:
Array path = rs.getArray("PATH");
String attributes = rs.getString("ATTRIBUTES");
return new Asset(
- rs.getString("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"),
- rs.getString("ASSET_TYPE"), rs.getBoolean("ACCESS_PUBLIC_READ"),
- rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),
- rs.getString("REALM"),
- path != null ? (String[]) path.getArray() : null,
- attributes != null && attributes.length() > 0 ? Values.instance().<ObjectValue>parse(attributes).orElse(
- null)
- : null);
- default:
- throw new UnsupportedOperationException("Select include option not supported: " + query.select.include);
+ rs.getString("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"),
+ rs.getString("ASSET_TYPE"), rs.getBoolean("ACCESS_PUBLIC_READ"),
+ rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),
+ rs.getString("REALM"),
+ path != null ? (String[]) path.getArray() : null,
+ attributes != null && attributes.length() > 0 ? Values.instance().<ObjectValue>parse(attributes).orElse(
+ null)
+ : null);
}
}
public boolean storeAttributeValue(EntityManager em, String assetId, String attributeName, Value value, String timestamp) {
return em.unwrap(Session.class).doReturningWork(connection -> {
String update =
- "update ASSET" +
- " set ATTRIBUTES = jsonb_set(jsonb_set(ATTRIBUTES, ?, ?, true), ?, ?, true)" +
- " where ID = ? and ATTRIBUTES -> ? is not null";
+ "update ASSET" +
+ " set ATTRIBUTES = jsonb_set(jsonb_set(ATTRIBUTES, ?, ?, true), ?, ?, true)" +
+ " where ID = ? and ATTRIBUTES -> ? is not null";
try (PreparedStatement statement = connection.prepareStatement(update)) {
// Bind the value (and check we don't have a SQL injection hole in attribute name!)
if (!AssetAttribute.ATTRIBUTE_NAME_VALIDATOR.test(attributeName)) {
LOG.fine(
- "Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName
+ "Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName
);
return false;
}
Array attributeValuePath = connection.createArrayOf(
- "text",
- new String[]{attributeName, "value"}
+ "text",
+ new String[]{attributeName, "value"}
);
statement.setArray(1, attributeValuePath);
@@ -1302,8 +1331,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// Bind the value timestamp
Array attributeValueTimestampPath = connection.createArrayOf(
- "text",
- new String[]{attributeName, "valueTimestamp"}
+ "text",
+ new String[]{attributeName, "valueTimestamp"}
);
statement.setArray(3, attributeValueTimestampPath);
PGobject pgJsonValueTimestamp = new PGobject();
@@ -1317,46 +1346,80 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
int updatedRows = statement.executeUpdate();
LOG.fine("Stored asset '" + assetId
- + "' attribute '" + attributeName
- + "' (affected rows: " + updatedRows + ") value: "
- + (value != null ? value.toJson() : "null"));
+ + "' attribute '" + attributeName
+ + "' (affected rows: " + updatedRows + ") value: "
+ + (value != null ? value.toJson() : "null"));
return updatedRows == 1;
}
});
}
+ // TODO: Remove AssetTreeModifiedEvent once GWT client replaced
protected void publishModificationEvents(PersistenceEvent<Asset> persistenceEvent) {
Asset asset = persistenceEvent.getEntity();
switch (persistenceEvent.getCause()) {
- case INSERT:
+ case CREATE:
+ // Fully load the asset (excluding attributes)
+ Asset loadedAsset = find(new AssetQuery().select(new Select(ALL_EXCEPT_ATTRIBUTES)).id(asset.getId()));
+
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
+ new AssetEvent(AssetEvent.Cause.CREATE, loadedAsset, null)
+ );
+
+ clientEventService.publishEvent(
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
);
if (asset.getParentId() != null) {
// Child asset created
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getParentId(),
- true)
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getParentId(),
+ true)
);
} else {
// Child asset created (root asset)
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), true)
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), true)
);
}
+
+ // Raise attribute event for each attribute
+ asset.getAttributesStream().forEach(newAttribute ->
+ clientEventService.publishEvent(
+ new AttributeEvent(asset.getId(),
+ newAttribute.getNameOrThrow(),
+ newAttribute.getValue().orElse(null),
+ newAttribute.getValueTimestamp().orElse(timerService.getCurrentTimeMillis()))
+ ));
break;
case UPDATE:
+ // Use simple equality check on each property
+ String[] updatedProperties = Arrays.stream(persistenceEvent.getPropertyNames()).filter(propertyName -> {
+ if ("attributes".equals(propertyName)) {
+ return false;
+ }
+ Object oldValue = persistenceEvent.getPreviousState(propertyName);
+ Object newValue = persistenceEvent.getCurrentState(propertyName);
+ return !Objects.equals(oldValue, newValue);
+ }).toArray(String[]::new);
+
+ // Fully load the asset (excluding attributes)
+ loadedAsset = find(new AssetQuery().select(new Select(ALL_EXCEPT_ATTRIBUTES)).id(asset.getId()));
+
+ clientEventService.publishEvent(
+ new AssetEvent(AssetEvent.Cause.UPDATE, loadedAsset, updatedProperties)
+ );
+
// Did the name change?
String previousName = persistenceEvent.getPreviousState("name");
String currentName = persistenceEvent.getCurrentState("name");
if (!Objects.equals(previousName, currentName)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getId())
);
break;
}
@@ -1366,9 +1429,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentParentId = persistenceEvent.getCurrentState("parentId");
if (!Objects.equals(previousParentId, currentParentId)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getId())
);
break;
}
@@ -1378,39 +1441,55 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentRealm = persistenceEvent.getCurrentState("realm");
if (!Objects.equals(previousRealm, currentRealm)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getId())
);
break;
}
- // Did the location change?
- Stream<AssetAttribute> oldAttributes = attributesFromJson(persistenceEvent.getPreviousState("attributes"),
- asset.getId());
- Stream<AssetAttribute> currentAttributes = attributesFromJson(persistenceEvent.getCurrentState(
- "attributes"), asset.getId());
+ // Did any attributes change if so raise attribute events on the event bus
+ List<AssetAttribute> oldAttributes = attributesFromJson(persistenceEvent.getPreviousState("attributes"),
+ asset.getId()).collect(Collectors.toList());
+ List<AssetAttribute> newAttributes = attributesFromJson(persistenceEvent.getCurrentState(
+ "attributes"), asset.getId()).collect(Collectors.toList());
- Optional<AssetAttribute> oldLocation = oldAttributes.filter(assetAttribute -> assetAttribute.name.equals(
- AttributeType.LOCATION.getAttributeName())).findFirst();
- Optional<AssetAttribute> currentLocation = currentAttributes.filter(assetAttribute -> assetAttribute.name.equals(
- AttributeType.LOCATION.getAttributeName())).findFirst();
-
- if (!(!oldLocation.isPresent() && !currentLocation.isPresent())) {
- if (!oldLocation.isPresent() || !currentLocation.isPresent() || !oldLocation.get().equals(
- currentLocation.get())) {
+ // Get removed attributes and raise an attribute event with deleted flag in attribute state
+ getAddedAttributes(newAttributes, oldAttributes).forEach(obsoleteAttribute ->
clientEventService.publishEvent(
- new LocationEvent(asset.getId(),
- asset.getCoordinates(),
- timerService.getCurrentTimeMillis())
- );
- }
- }
+ new AttributeEvent(asset.getId(), obsoleteAttribute.getNameOrThrow(), true)
+ ));
+
+
+ // Get new or modified attributes
+ getAddedOrModifiedAttributes(oldAttributes,
+ newAttributes)
+ .forEach(newOrModifiedAttribute ->
+ clientEventService.publishEvent(
+ new AttributeEvent(
+ asset.getId(),
+ newOrModifiedAttribute.getNameOrThrow(),
+ newOrModifiedAttribute.getValue().orElse(null),
+ newOrModifiedAttribute.getValueTimestamp().orElse(timerService.getCurrentTimeMillis()))
+ ));
break;
case DELETE:
+
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
+ new AssetEvent(AssetEvent.Cause.DELETE, asset, null)
);
+
+ clientEventService.publishEvent(
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
+ );
+
+ // Raise attribute event with deleted flag for each attribute
+ attributesFromJson(persistenceEvent.getPreviousState("attributes"), asset.getId())
+ .forEach(obsoleteAttribute ->
+ clientEventService.publishEvent(
+ new AttributeEvent(asset.getId(), obsoleteAttribute.getNameOrThrow(), true)
+ ));
+
break;
}
}
@@ -1429,45 +1508,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
clientEventService.sendToSession(sessionKey, triggeredEventSubscription);
}
- protected static boolean calendarEventPredicateMatches(CalendarEventActivePredicate eventActivePredicate, Asset asset) {
- return CalendarEventConfiguration.getCalendarEvent(asset)
- .map(calendarEvent -> calendarEventActiveOn(calendarEvent,
- new Date(1000L * eventActivePredicate.timestampSeconds)))
- .orElse(true);
- }
-
- protected static boolean calendarEventActiveOn(CalendarEvent calendarEvent, Date when) {
- if (calendarEvent.getRecurrence() == null) {
- return (!when.before(calendarEvent.getStart()) && !when.after(calendarEvent.getEnd()));
- }
-
- RecurrenceRule recurrenceRule = calendarEvent.getRecurrence();
- Recur recurrence;
-
- if (recurrenceRule.getCount() != null) {
- recurrence = new Recur(recurrenceRule.getFrequency().name(), recurrenceRule.getCount());
- } else if (recurrenceRule.getUntil() != null) {
- recurrence = new Recur(recurrenceRule.getFrequency().name(),
- new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));
- } else {
- recurrence = new Recur(recurrenceRule.getFrequency().name(), null);
- }
-
- if (recurrenceRule.getInterval() != null) {
- recurrence.setInterval(recurrenceRule.getInterval());
- }
-
- RRule rRule = new RRule(recurrence);
- VEvent vEvent = new VEvent(new DateTime(calendarEvent.getStart()),
- new DateTime(calendarEvent.getEnd()), "");
- vEvent.getProperties().add(rRule);
- Period period = new Period(new DateTime(when), new Dur(0, 0, 1, 0));
- PeriodRule periodRule = new PeriodRule(period);
- return periodRule.evaluate(vEvent);
+ protected void replyWithAssetEvent(String sessionKey, String subscriptionId, Asset asset) {
+ AssetEvent event = new AssetEvent(AssetEvent.Cause.READ,asset, null);
+ TriggeredEventSubscription<AssetEvent> triggeredEventSubscription = new TriggeredEventSubscription<>(new AssetEvent[] {event}, subscriptionId);
+ clientEventService.sendToSession(sessionKey, triggeredEventSubscription);
}
public String toString() {
return getClass().getSimpleName() + "{" +
- '}';
+ '}';
}
}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index 61177ded8..bbf8b134c 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -483,7 +483,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
switch (persistenceEvent.getCause()) {
- case INSERT:
+ case CREATE:
case UPDATE:
consoleFCMTokenMap.put(asset.getId(), getFcmToken(asset).orElse(null));
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index ca05e706e..e3a94961e 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -362,7 +362,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
new AssetState(loadedAsset, attribute.deepCopy(), Source.INTERNAL);
switch (persistenceEvent.getCause()) {
- case INSERT: {
+ case CREATE: {
// New asset has been created so get attributes that have RULE_STATE meta
List<AssetAttribute> ruleStateAttributes =
asset.getAttributesStream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());
@@ -483,7 +483,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
} else if (ruleset instanceof AssetRuleset) {
- // Must reload from the database, the ruleset might not be completely hydrated on INSERT or UPDATE
+ // Must reload from the database, the ruleset might not be completely hydrated on CREATE or UPDATE
AssetRuleset assetRuleset = rulesetStorageService.findById(AssetRuleset.class, ruleset.getId());
RulesEngine newEngine = deployAssetRuleset(assetRuleset);
if (newEngine != null) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
index e60a2e8a1..b4beb5806 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
@@ -283,7 +283,7 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
withLock(getClass().getSimpleName() + "::processAssetChange", () -> {
switch (persistenceEvent.getCause()) {
- case INSERT:
+ case CREATE:
case UPDATE:
if (isLinkedToORConsoleGeofenceAdapter(asset)) {
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index 7ffa9aede..f6af76a71 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -372,7 +372,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
getRealms(clientRequestInfo).create(realmRepresentation);
createClientApplication(clientRequestInfo, realmRepresentation.getRealm());
- publishModification(PersistenceEvent.Cause.INSERT, tenant);
+ publishModification(PersistenceEvent.Cause.CREATE, tenant);
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
index dc7ed4578..5fca3ac18 100644
--- a/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
@@ -33,6 +33,7 @@ import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.*;
+import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.value.Values;
import java.time.DayOfWeek;
@@ -74,7 +75,7 @@ public abstract class AbstractManagerSetup implements Setup {
// ################################ Demo apartment with complex scenes ###################################
- protected Asset createDemoApartment(Asset parent, String name) {
+ protected Asset createDemoApartment(Asset parent, String name, GeoJSONPoint location) {
Asset apartment = new Asset(name, RESIDENCE, parent);
apartment.setAttributes(
new AssetAttribute("alarmEnabled", AttributeValueType.BOOLEAN)
@@ -111,7 +112,9 @@ public abstract class AbstractManagerSetup implements Setup {
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(RULE_STATE, Values.create(true)),
new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))
- )
+ ),
+ new AssetAttribute(AttributeType.LOCATION, location.toValue())
+ .setMeta(new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)))
/* TODO Unused, can be removed? Port schedule prediction from DRL...
new AssetAttribute("autoSceneSchedule", AttributeValueType.BOOLEAN)
.setMeta(
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
index 3c45bbcb0..d0d460f02 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
@@ -413,8 +413,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
smartBuildingId = smartBuilding.getId();
// The "Apartment 1" is the demo apartment with complex scenes
- Asset apartment1 = createDemoApartment(smartBuilding, "Apartment 1")
- .addAttributes(new AssetAttribute(AttributeType.LOCATION, locationValueA));
+ Asset apartment1 = createDemoApartment(smartBuilding, "Apartment 1", SMART_BUILDING_LOCATION);
apartment1 = assetStorageService.merge(apartment1);
apartment1Id = apartment1.getId();
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
index 7f218ba4b..18096f382 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -516,6 +516,16 @@ public class AssetAttribute extends Attribute {
);
}
+ /**
+ * @return All attributes that exist only in the new list (based on name).
+ */
+ public static Stream<AssetAttribute> getAddedAttributes(List<AssetAttribute> oldAttributes,
+ List<AssetAttribute> newAttributes) {
+ return newAttributes.stream().filter(newAttribute -> oldAttributes.stream().noneMatch(
+ oldAttribute -> newAttribute.getNameOrThrow().equals(newAttribute.getNameOrThrow())
+ ));
+ }
+
public static Stream<AssetAttribute> attributesFromJson(ObjectValue objectValue, String assetId) {
if (objectValue == null || objectValue.keys().length == 0) {
return Stream.empty();
diff --git a/model/src/main/java/org/openremote/model/asset/AssetEvent.java b/model/src/main/java/org/openremote/model/asset/AssetEvent.java
new file mode 100644
index 000000000..ee6be575e
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/AssetEvent.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2019, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.asset;
+
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.event.shared.EventFilter;
+import org.openremote.model.event.shared.SharedEvent;
+
+import java.util.Arrays;
+
+/**
+ * This event is used when an {@link Asset} is created, read, updated or deleted (updates are only fired when one or more top
+ * level {@link Asset} properties are changed (excluding {@link Asset#getAttributes}. Attribute changes are handled via
+ * the {@link org.openremote.model.attribute.AttributeEvent}. When the cause is {@link Cause#READ} then the asset's
+ * {@link org.openremote.model.attribute.Attribute}s will be included in the asset otherwise they are not.
+ */
+public class AssetEvent extends SharedEvent {
+
+ public static class AssetIdFilter extends EventFilter<AttributeEvent> {
+
+ public static final String FILTER_TYPE = "asset-id";
+
+ protected String[] assetIds = new String[0];
+
+ protected AssetIdFilter() {
+ }
+
+ public AssetIdFilter(String... assetIds) {
+ this.assetIds = assetIds;
+ }
+
+ public String[] getAssetIds() {
+ return assetIds;
+ }
+
+ @Override
+ public String getFilterType() {
+ return FILTER_TYPE;
+ }
+
+ @Override
+ public boolean apply(AttributeEvent event) {
+ return Arrays.asList(assetIds).contains(event.getEntityId());
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "assetIds='" + Arrays.toString(assetIds) + '\'' +
+ '}';
+ }
+ }
+
+ public enum Cause {
+ CREATE,
+ READ,
+ UPDATE,
+ DELETE
+ }
+
+ protected Cause cause;
+ protected Asset asset;
+ protected String[] updatedProperties;
+
+
+ public AssetEvent(Cause cause, Asset asset, String[] updatedProperties) {
+ this.cause = cause;
+ this.asset = asset;
+ this.updatedProperties = updatedProperties;
+ }
+
+ public Cause getCause() {
+ return cause;
+ }
+
+ public Asset getAsset() {
+ return asset;
+ }
+
+ public String[] getUpdatedProperties() {
+ return updatedProperties;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "cause=" + cause +
+ ", asset=" + asset +
+ ", updatedProperties=" + Arrays.toString(updatedProperties) +
+ ", timestamp=" + timestamp +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.java
index 3926b2f85..ff85e034c 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetType.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java
@@ -45,15 +45,15 @@ public enum AssetType implements AssetDescriptor {
FLOOR(ASSET_NAMESPACE + ":floor", "server"),
- RESIDENCE(ASSET_NAMESPACE + ":residence", "cubes"),
+ RESIDENCE(ASSET_NAMESPACE + ":residence", "home"),
- ROOM(ASSET_NAMESPACE + ":room", "cube"),
+ ROOM(ASSET_NAMESPACE + ":room", "office"),
AGENT(ASSET_NAMESPACE + ":agent", "cogs"),
- CONSOLE(ASSET_NAMESPACE + ":console", "mobile-alt"),
+ CONSOLE(ASSET_NAMESPACE + ":console", "cellphone-android"),
- THING(ASSET_NAMESPACE + ":thing", "cog");
+ THING(ASSET_NAMESPACE + ":thing", "settings");
final protected String type;
final protected String icon;
diff --git a/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java b/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java
index 9fc06b969..17afd1c59 100644
--- a/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java
@@ -34,30 +34,18 @@ import java.util.Arrays;
* If no attribute names and only an asset identifier are provided, all attributes
* of the asset, accessible by the client, will be read/returned.
*/
-public class ReadAssetAttributesEvent extends SharedEvent {
-
- protected String assetId;
+public class ReadAssetAttributesEvent extends ReadAssetEvent {
protected String[] attributeNames;
- protected String subscriptionId;
-
protected ReadAssetAttributesEvent() {
}
public ReadAssetAttributesEvent(String assetId, String... attributeNames) {
- this.assetId = assetId;
+ super(assetId);
this.attributeNames = attributeNames;
}
- public String getAssetId() {
- return assetId;
- }
-
- public void setAssetId(String assetId) {
- this.assetId = assetId;
- }
-
public String[] getAttributeNames() {
return attributeNames;
}
@@ -66,19 +54,12 @@ public class ReadAssetAttributesEvent extends SharedEvent {
this.attributeNames = attributeNames;
}
- public String getSubscriptionId() {
- return subscriptionId;
- }
-
- public void setSubscriptionId(String subscriptionId) {
- this.subscriptionId = subscriptionId;
- }
-
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"assetId='" + assetId + '\'' +
", attributeNames=" + Arrays.toString(attributeNames) +
+ ", subscriptionId='" + subscriptionId + '\'' +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/LocationEvent.java b/model/src/main/java/org/openremote/model/asset/ReadAssetEvent.java
similarity index 51%
rename from model/src/main/java/org/openremote/model/asset/LocationEvent.java
rename to model/src/main/java/org/openremote/model/asset/ReadAssetEvent.java
index 7d358645d..5dd49afa2 100644
--- a/model/src/main/java/org/openremote/model/asset/LocationEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/ReadAssetEvent.java
@@ -19,46 +19,55 @@
*/
package org.openremote.model.asset;
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.event.shared.SharedEvent;
-import org.openremote.model.geo.GeoJSONPoint;
import java.util.Arrays;
/**
- * A location event.
+ * A client sends this event to the server to refresh its attribute state, expecting
+ * the server to answer "soon" with {@link AttributeEvent}s. If the server
+ * decides that the client doesn't have the right permissions, or if anything
+ * else is not in order (e.g. the asset doesn't exist), the server might not react
+ * at all.
+ * <p>
+ * If no attribute names and only an asset identifier are provided, all attributes
+ * of the asset, accessible by the client, will be read/returned.
*/
-public class LocationEvent extends SharedEvent {
+public class ReadAssetEvent extends SharedEvent {
protected String assetId;
- protected GeoJSONPoint coordinates;
- @JsonCreator
- public LocationEvent(
- @JsonProperty("assetId") String assetId,
- @JsonProperty("coordinates") GeoJSONPoint coordinates,
- @JsonProperty("timestamp") long timestamp
- ) {
- super(timestamp);
+ protected String subscriptionId;
+
+ protected ReadAssetEvent() {
+ }
+
+ public ReadAssetEvent(String assetId) {
this.assetId = assetId;
- this.coordinates = coordinates;
}
public String getAssetId() {
return assetId;
}
- public GeoJSONPoint getCoordinates() {
- return coordinates;
+ public void setAssetId(String assetId) {
+ this.assetId = assetId;
+ }
+
+ public String getSubscriptionId() {
+ return subscriptionId;
+ }
+
+ public void setSubscriptionId(String subscriptionId) {
+ this.subscriptionId = subscriptionId;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "timestamp=" + timestamp +
- ", assetId=" + assetId +
- ", coordinates=" + (coordinates == null ? "null" : coordinates.toValue()) +
- "}";
+ "assetId='" + assetId + '\'' +
+ ", subscriptionId='" + subscriptionId + '\'' +
+ '}';
}
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
index 6a99f22c5..a29a4383a 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
@@ -19,11 +19,9 @@
*/
package org.openremote.model.attribute;
-import org.openremote.model.event.shared.EventFilter;
import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.value.Value;
-import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
@@ -63,45 +61,6 @@ public class AttributeEvent extends SharedEvent {
SENSOR
}
- public static class EntityIdFilter extends EventFilter<AttributeEvent> {
-
- public static final String FILTER_TYPE = "attribute-entity-id";
-
- protected String[] entityIds = new String[0];
-
- protected EntityIdFilter() {
- }
-
- public EntityIdFilter(String... entityIds) {
- this.entityIds = entityIds;
- }
-
- public String[] getEntityIds() {
- return entityIds;
- }
-
- public void setEntityIds(String[] entityIds) {
- this.entityIds = entityIds;
- }
-
- @Override
- public String getFilterType() {
- return FILTER_TYPE;
- }
-
- @Override
- public boolean apply(AttributeEvent event) {
- return Arrays.asList(entityIds).contains(event.getEntityId());
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "entityIds='" + Arrays.toString(entityIds) + '\'' +
- '}';
- }
- }
-
protected AttributeState attributeState;
protected AttributeEvent() {
@@ -115,6 +74,11 @@ public class AttributeEvent extends SharedEvent {
this(new AttributeState(new AttributeRef(entityId, attributeName)));
}
+ public AttributeEvent(String entityId, String attributeName, boolean deleted) {
+ this(new AttributeState(new AttributeRef(entityId, attributeName)));
+ attributeState.deleted = deleted;
+ }
+
public AttributeEvent(String entityId, String attributeName, Value value, long timestamp) {
this(new AttributeState(new AttributeRef(entityId, attributeName), value), timestamp);
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeState.java b/model/src/main/java/org/openremote/model/attribute/AttributeState.java
index 835db403e..91d030299 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeState.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeState.java
@@ -37,6 +37,7 @@ public class AttributeState {
protected AttributeRef attributeRef;
protected Value value;
+ protected boolean deleted;
protected AttributeState() {
}
@@ -75,10 +76,17 @@ public class AttributeState {
return Optional.ofNullable(value);
}
+ public boolean isDeleted() {
+ return deleted;
+ }
+
public ObjectValue toObjectValue() {
ObjectValue objectValue = Values.createObject();
objectValue.put("attributeRef", getAttributeRef().toArrayValue());
getValue().ifPresent(v -> objectValue.put("value", value));
+ if (deleted) {
+ objectValue.put("deleted", Values.create(true));
+ }
return objectValue;
}
@@ -87,6 +95,7 @@ public class AttributeState {
return getClass().getSimpleName() + "{" +
"attributeRef=" + attributeRef +
", value=" + value +
+ ", deleted=" + deleted +
'}';
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java
index 8a9237ee4..5abd8e2c1 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java
@@ -42,15 +42,15 @@ import static org.openremote.model.attribute.AttributeValueType.AttributeValueTy
*/
public enum AttributeValueType implements AttributeValueDescriptor {
- STRING("file-text-o", ValueType.STRING),
+ STRING("format-text", ValueType.STRING),
- NUMBER("hashtag", ValueType.NUMBER),
+ NUMBER("numeric", ValueType.NUMBER),
- BOOLEAN("toggle-off", ValueType.BOOLEAN),
+ BOOLEAN("toggle-switch", ValueType.BOOLEAN),
- OBJECT("cubes", ValueType.OBJECT),
+ OBJECT("cube", ValueType.OBJECT),
- ARRAY("ellipsis-h", ValueType.ARRAY),
+ ARRAY("code-array", ValueType.ARRAY),
// TODO Implement "Saved Filter/Searches" properly, see AssetResourceImpl
RULES_TEMPLATE_FILTER("filter", ValueType.ARRAY),
@@ -68,28 +68,28 @@ public enum AttributeValueType implements AttributeValueDescriptor {
TIMESTAMP_SECONDS("clock-o", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%d s"))),
- TIME_SECONDS("clock-o", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f s"))),
+ TIME_SECONDS("clock-outline", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f s"))),
- TIME_MINUTES("clock-o", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f min"))),
+ TIME_MINUTES("clock-outline", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f min"))),
DATETIME("calendar", ValueType.STRING),
- COLOR_RGB("paint-brush", ValueType.ARRAY, value -> Values.getArray(value)
+ COLOR_RGB("brush", ValueType.ARRAY, value -> Values.getArray(value)
.filter(array -> array.length() != 3)
.map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))
),
- COLOR_ARGB("paint-brush", ValueType.ARRAY, value -> Values.getArray(value)
+ COLOR_ARGB("brush", ValueType.ARRAY, value -> Values.getArray(value)
.filter(array -> array.length() != 4)
.map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))
),
- COLOR_HEX("paint-brush", ValueType.STRING, value -> Values.getString(value)
+ COLOR_HEX("brush", ValueType.STRING, value -> Values.getString(value)
.filter(s -> !s.matches("[a-fA-F0-9]{6}"))
.map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))
),
- SOUND_DB("file-sound-o", ValueType.NUMBER, value -> Values.getNumber(value)
+ SOUND_DB("ear-hearing", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(n -> n < 0)
.map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_SOUND_OUT_OF_RANGE)),
FORMAT.withInitialValue(Values.create("%d dB"))
@@ -112,31 +112,31 @@ public enum AttributeValueType implements AttributeValueDescriptor {
.map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE))
),
- RAINFALL("tint", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f mm/h"))),
+ RAINFALL("water", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f mm/h"))),
- BRIGHTNESS_LUX("sun-o", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%d lx"))),
+ BRIGHTNESS_LUX("white-balance-sunny", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%d lx"))),
- DISTANCE_M("arrows-h", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f m"))),
+ DISTANCE_M("ruler", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f m"))),
- DISTANCE_CM("arrows-h", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f cm"))),
+ DISTANCE_CM("ruler", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f cm"))),
- DISTANCE_MM("arrows-h", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f mm"))),
+ DISTANCE_MM("ruler", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f mm"))),
- DISTANCE_IN("arrows-h", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f \""))),
+ DISTANCE_IN("ruler", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f \""))),
- DISTANCE_FT("arrows-h", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f '"))),
+ DISTANCE_FT("ruler", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f '"))),
- DISTANCE_YARD("arrows-h", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f yd"))),
+ DISTANCE_YARD("ruler", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f yd"))),
- SPEED_MS("rocket", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.3f m/s"))),
+ SPEED_MS("speedometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.3f m/s"))),
- SPEED_KPH("rocket", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f km/h"))),
+ SPEED_KPH("speedometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f km/h"))),
- SPEED_MPH("rocket", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f mi/h"))),
+ SPEED_MPH("speedometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f mi/h"))),
CO2_PPM("leaf", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%4d ppm"))),
- HUMIDITY_PERCENTAGE("tint", ValueType.NUMBER, value -> Values.getNumber(value)
+ HUMIDITY_PERCENTAGE("water-percent", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(number -> number < 0 || number > 100)
.map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),
RANGE_MIN.withInitialValue(Values.create(0)),
@@ -144,17 +144,17 @@ public enum AttributeValueType implements AttributeValueDescriptor {
FORMAT.withInitialValue(Values.create("%3d %%"))
),
- HUMIDITY_GPCM("tint", ValueType.NUMBER),
+ HUMIDITY_GPCM("water-percent", ValueType.NUMBER),
- POWER_WATT("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f W"))),
+ POWER_WATT("flash", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f W"))),
- POWER_KILOWATT("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f KW"))),
+ POWER_KILOWATT("flash", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f KW"))),
- POWER_MEGAWATT("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f MW"))),
+ POWER_MEGAWATT("flash", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f MW"))),
- POWER_PERCENTAGE("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%3d %%"))),
+ POWER_PERCENTAGE("flash", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%3d %%"))),
- CHARGE_PERCENTAGE("battery-full", ValueType.NUMBER, value -> Values.getNumber(value)
+ CHARGE_PERCENTAGE("battery", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(number -> number < 0 || number > 100)
.map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),
RANGE_MIN.withInitialValue(Values.create(0)),
@@ -162,23 +162,23 @@ public enum AttributeValueType implements AttributeValueDescriptor {
FORMAT.withInitialValue(Values.create("%3d %%"))
),
- CHARGE_KWH("battery-full", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f KWh"))),
+ CHARGE_KWH("battery", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f KWh"))),
- ENERGY_KWH("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f KWh"))),
+ ENERGY_KWH("power-plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f KWh"))),
- ENERGY_JOULE("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f J"))),
+ ENERGY_JOULE("power-plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f J"))),
- ENERGY_MEGAJOULE("plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f MJ"))),
+ ENERGY_MEGAJOULE("power-plug", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f MJ"))),
- FLOW_LPM("tachometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f L/m"))),
+ FLOW_LPM("gauge", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f L/m"))),
- FLOW_CMPS("tachometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f m³/s"))),
+ FLOW_CMPS("gauge", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f m³/s"))),
- FLOW_CCMPS("tachometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f cm³/s"))),
+ FLOW_CCMPS("gauge", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f cm³/s"))),
- FLOW_CFPS("tachometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f cfs"))),
+ FLOW_CFPS("gauge", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f cfs"))),
- FLOW_GPM("tachometer", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f gpm"))),
+ FLOW_GPM("gauge", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.5f gpm"))),
DIRECTION_DECIMAL_DEGREES("compass", ValueType.NUMBER, FORMAT.withInitialValue(Values.create("%0.1f deg"))),
diff --git a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java b/model/src/main/java/org/openremote/model/event/shared/EventFilter.java
index 7fe2b6ec6..9c2f4c714 100644
--- a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java
+++ b/model/src/main/java/org/openremote/model/event/shared/EventFilter.java
@@ -22,7 +22,7 @@ package org.openremote.model.event.shared;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.asset.AssetEvent;
import org.openremote.model.simulator.SimulatorState;
import org.openremote.model.syslog.SyslogEvent;
@@ -32,7 +32,7 @@ import org.openremote.model.syslog.SyslogEvent;
@JsonSubTypes({
@JsonSubTypes.Type(value = TenantFilter.class, name = TenantFilter.FILTER_TYPE),
@JsonSubTypes.Type(value = SyslogEvent.LevelCategoryFilter.class, name = SyslogEvent.LevelCategoryFilter.FILTER_TYPE),
- @JsonSubTypes.Type(value = AttributeEvent.EntityIdFilter.class, name = AttributeEvent.EntityIdFilter.FILTER_TYPE),
+ @JsonSubTypes.Type(value = AssetEvent.AssetIdFilter.class, name = AssetEvent.AssetIdFilter.FILTER_TYPE),
@JsonSubTypes.Type(value = SimulatorState.ConfigurationFilter.class, name = SimulatorState.ConfigurationFilter.FILTER_TYPE)
})
@JsonTypeInfo(
diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
index da5ea39f4..551216ad3 100644
--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
@@ -22,9 +22,10 @@ package org.openremote.model.event.shared;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.openremote.model.asset.AssetEvent;
import org.openremote.model.asset.AssetTreeModifiedEvent;
-import org.openremote.model.asset.LocationEvent;
import org.openremote.model.asset.ReadAssetAttributesEvent;
+import org.openremote.model.asset.ReadAssetEvent;
import org.openremote.model.asset.agent.AgentStatusEvent;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.event.Event;
@@ -41,13 +42,14 @@ import org.openremote.model.syslog.SyslogEvent;
// Events used on client and server (serializable)
@JsonSubTypes.Type(value = SyslogEvent.class, name = "syslog"),
@JsonSubTypes.Type(value = AttributeEvent.class, name = "attribute"),
+ @JsonSubTypes.Type(value = AssetEvent.class, name = "asset"),
@JsonSubTypes.Type(value = ReadAssetAttributesEvent.class, name = "read-asset-attributes"),
+ @JsonSubTypes.Type(value = ReadAssetEvent.class, name = "read-asset"),
@JsonSubTypes.Type(value = AssetTreeModifiedEvent.class, name = "asset-tree-modified"),
@JsonSubTypes.Type(value = SimulatorState.class, name = "simulator-state"),
@JsonSubTypes.Type(value = RequestSimulatorState.class, name = "request-simulator-state"),
@JsonSubTypes.Type(value = AgentStatusEvent.class, name = "agent-status"),
@JsonSubTypes.Type(value = RulesEngineStatusEvent.class, name = "rules-engine-status"),
- @JsonSubTypes.Type(value = LocationEvent.class, name = "location"),
@JsonSubTypes.Type(value = RulesetChangedEvent.class, name = "ruleset-changed")
})
@JsonTypeInfo(
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java b/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java
index 645720e12..6cf4311f4 100644
--- a/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java
@@ -20,6 +20,7 @@
package org.openremote.model.geo;
import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.openremote.model.value.ArrayValue;
@@ -56,18 +57,22 @@ public class GeoJSONPoint extends GeoJSONGeometry {
return coordinates;
}
+ @JsonIgnore
public double getX() {
return coordinates.getX();
}
+ @JsonIgnore
public double getY() {
return coordinates.getY();
}
+ @JsonIgnore
public Double getZ() {
return coordinates.getZ();
}
+ @JsonIgnore
public boolean hasZ() {
return coordinates.hasZ();
}
diff --git a/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
index 6064abba7..d101ed537 100644
--- a/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
+++ b/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
@@ -37,6 +37,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
public enum Include {
ALL_EXCEPT_PATH_AND_ATTRIBUTES,
ALL_EXCEPT_PATH,
+ ALL_EXCEPT_ATTRIBUTES,
ONLY_ID_AND_NAME,
ONLY_ID_AND_NAME_AND_ATTRIBUTES,
ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES,
diff --git a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
index 7bb5f298f..f91d2c14c 100644
--- a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
@@ -24,8 +24,8 @@ import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.setup.SetupService
import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.asset.AssetEvent
import org.openremote.model.attribute.MetaItemType
-import org.openremote.model.asset.LocationEvent
import org.openremote.model.asset.agent.AgentStatusEvent
import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.model.attribute.AttributeEvent
@@ -132,46 +132,46 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
assert collectedSharedEvents.isEmpty()
}
- when: "a subscription is made to the location event"
- clientEventService.subscribe(LocationEvent.class)
+ when: "a subscription is made to the attribute event"
+ clientEventService.subscribe(AttributeEvent.class, new AssetEvent.AssetIdFilter(managerDemoSetup.thingId))
and: "an assets location is changed"
def asset = assetStorageService.find(managerDemoSetup.thingId, true)
asset.setCoordinates(new GeoJSONPoint(120.1d, 50.43d))
asset = assetStorageService.merge(asset)
- then: "the location event should have been received"
+ then: "the attribute event should have been received"
conditions.eventually {
assert collectedSharedEvents.size() == 1
- assert collectedSharedEvents[0] instanceof LocationEvent
- assert (collectedSharedEvents[0] as LocationEvent).assetId == managerDemoSetup.thingId
- assert (collectedSharedEvents[0] as LocationEvent).coordinates.x == 120.1d
- assert (collectedSharedEvents[0] as LocationEvent).coordinates.y == 50.43d
+ assert collectedSharedEvents[0] instanceof AttributeEvent
+ assert (collectedSharedEvents[0] as AttributeEvent).entityId == managerDemoSetup.thingId
+ assert (collectedSharedEvents[0] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.x}.orElse(null) == 120.1d
+ assert (collectedSharedEvents[0] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.y}.orElse(null) == 50.43d
}
when: "the assets location is set to null"
asset.setCoordinates(null)
asset = assetStorageService.merge(asset)
- then: "the location event should have been received with null coordinates"
+ then: "the attribute event should have been received with null coordinates"
conditions.eventually {
assert collectedSharedEvents.size() == 2
- assert collectedSharedEvents[1] instanceof LocationEvent
- assert (collectedSharedEvents[1] as LocationEvent).assetId == managerDemoSetup.thingId
- assert (collectedSharedEvents[1] as LocationEvent).coordinates == null
+ assert collectedSharedEvents[1] instanceof AttributeEvent
+ assert (collectedSharedEvents[1] as AttributeEvent).entityId == managerDemoSetup.thingId
+ assert !(collectedSharedEvents[1] as AttributeEvent).value.isPresent()
}
when: "the location is changed"
asset.setCoordinates(new GeoJSONPoint(-10.11d, -50.233d))
asset = assetStorageService.merge(asset)
- then: "the location event should have been received"
+ then: "the attribute event should have been received"
conditions.eventually {
assert collectedSharedEvents.size() == 3
- assert collectedSharedEvents[2] instanceof LocationEvent
- assert (collectedSharedEvents[2] as LocationEvent).assetId == managerDemoSetup.thingId
- assert (collectedSharedEvents[2] as LocationEvent).coordinates.x == -10.11d
- assert (collectedSharedEvents[2] as LocationEvent).coordinates.y == -50.233d
+ assert collectedSharedEvents[2] instanceof AttributeEvent
+ assert (collectedSharedEvents[2] as AttributeEvent).entityId == managerDemoSetup.thingId
+ assert (collectedSharedEvents[2] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.x}.orElse(null) == -10.11d
+ assert (collectedSharedEvents[2] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.y}.orElse(null) == -50.233d
}
when: "the location is set with the same value"
@@ -183,11 +183,11 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
assert collectedSharedEvents.size() == 3
when: "the subscription is removed"
- clientEventService.unsubscribe(LocationEvent.class)
+ clientEventService.unsubscribe(AttributeEvent.class)
collectedSharedEvents.clear()
and: "a new attribute event subscription is added"
- clientEventService.subscribe(AttributeEvent.class, new AttributeEvent.EntityIdFilter(managerDemoSetup.thingId))
+ clientEventService.subscribe(AttributeEvent.class, new AssetEvent.AssetIdFilter(managerDemoSetup.thingId))
and: "an internal attribute event subscription is made"
List<AttributeEvent> internalReceivedEvents = []
@@ -196,7 +196,7 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
false,
new EventSubscription<>(
AttributeEvent.class,
- new AttributeEvent.EntityIdFilter(managerDemoSetup.thingId),
+ new AssetEvent.AssetIdFilter(managerDemoSetup.thingId),
{ triggeredEventSubscription ->
internalReceivedEvents.add(triggeredEventSubscription.events[0] as AttributeEvent)
}