100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Replaced hard synchronization in most protocols with tryLock and timeout
Christian Bauerdd390af11c15
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.javaindex 4bdb96efa..7195278cb 100644--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java@@ -43,10 +43,31 @@ import org.openremote.model.value.*;import java.util.*;import java.util.concurrent.TimeUnit;+import java.util.concurrent.locks.ReentrantLock;import java.util.function.Consumer;+import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger;+import static java.util.logging.Level.FINEST;++/**+ * Thread-safe base implementation for protocols.+ * <p>+ * Subclasses should use the {@link #withLock} and {@link #withLockReturning} methods+ * to guard critical sections when modifying shared state:+ * <blockquote><pre>{@code+ * withLock(() -> {+ * // Critical section+ * });+ * }</pre></blockquote>+ * <blockquote><pre>{@code+ * return withLockReturning(() -> {+ * // Critical section+ * return ...;+ * });+ * }</pre></blockquote>+ */public abstract class AbstractProtocol implements Protocol {protected static class LinkedProtocolInfo {@@ -94,6 +115,9 @@ public abstract class AbstractProtocol implements Protocol {protected ProtocolExecutorService executorService;protected ProtocolAssetService assetService;+ // Provides exclusive access to shared protocol state+ protected final ReentrantLock lock = new ReentrantLock(true);+@Overridepublic void init(Container container) throws Exception {LOG.info("Initializing protocol: " + getProtocolName());@@ -108,66 +132,64 @@ public abstract class AbstractProtocol implements Protocol {this.messageBrokerContext = container.getService(MessageBrokerSetupService.class).getContext();this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();- synchronized (linkedAttributes) {- messageBrokerContext.addRoutes(new RouteBuilder() {- @Override- public void configure() throws Exception {- from(ACTUATOR_TOPIC)- .routeId("Actuator-" + getProtocolName())- .process(exchange -> {- String protocolName = exchange.getIn().getHeader(ACTUATOR_TOPIC_TARGET_PROTOCOL, String.class);- if (getProtocolName().equals(protocolName)) {- // TODO Use read/write lock for link/unlink attributes synchronization and additional optional exclusive lock for single-threaded implementors- synchronized (linkedAttributes) {- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);- AssetAttribute attribute = linkedAttributes.get(event.getAttributeRef());- if (attribute == null) {- LOG.warning("Attribute doesn't exist on this protocol: " + event.getAttributeRef());- } else {- AssetAttribute protocolConfiguration = getLinkedProtocolConfiguration(attribute);- processLinkedAttributeWrite(event, protocolConfiguration);- }- }- }- });- }- });- }+ withLock(() -> {+ try {+ messageBrokerContext.addRoutes(new RouteBuilder() {+ @Override+ public void configure() throws Exception {+ from(ACTUATOR_TOPIC)+ .routeId("Actuator-" + getProtocolName())+ .process(exchange -> {+ String protocolName = exchange.getIn().getHeader(ACTUATOR_TOPIC_TARGET_PROTOCOL, String.class);+ if (!getProtocolName().equals(protocolName))+ return;+ processLinkedAttributeWrite(exchange.getIn().getBody(AttributeEvent.class));+ });+ }+ });+ } catch (Exception ex) {+ throw new RuntimeException(ex);+ }+ });}@Overridepublic void stop(Container container) throws Exception {- synchronized (linkedAttributes) {+ withLock(() -> {linkedAttributes.clear();- messageBrokerContext.stopRoute("Actuator-" + getProtocolName(), 1, TimeUnit.MILLISECONDS);- messageBrokerContext.removeRoute("Actuator-" + getProtocolName());- }+ try {+ messageBrokerContext.stopRoute("Actuator-" + getProtocolName(), 1, TimeUnit.MILLISECONDS);+ messageBrokerContext.removeRoute("Actuator-" + getProtocolName());+ } catch (Exception ex) {+ throw new RuntimeException(ex);+ }+ });}@Overridepublic void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<ConnectionStatus> statusConsumer) {- synchronized (linkedProtocolConfigurations) {+ withLock(() -> {LOG.finer("Linking protocol configuration to protocol '" + getProtocolName() + "': " + protocolConfiguration);linkedProtocolConfigurations.put(protocolConfiguration.getReferenceOrThrow(),new LinkedProtocolInfo(protocolConfiguration, statusConsumer, ConnectionStatus.CONNECTING));doLinkProtocolConfiguration(protocolConfiguration);- }+ });}@Overridepublic void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {- synchronized (linkedProtocolConfigurations) {+ withLock(() -> {LOG.finer("Unlinking protocol configuration from protocol '" + getProtocolName() + "': " + protocolConfiguration);doUnlinkProtocolConfiguration(protocolConfiguration);linkedProtocolConfigurations.remove(protocolConfiguration.getReferenceOrThrow());- }+ });}@Overridepublic void linkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) {- synchronized (linkedAttributes) {+ withLock(() -> {attributes.forEach(attribute -> {LOG.fine("Linking attribute to '" + getProtocolName() + "': " + attribute);AttributeRef attributeRef = attribute.getReferenceOrThrow();@@ -177,15 +199,11 @@ public abstract class AbstractProtocol implements Protocol {Optional<List<MessageFilter>> messageFilters = Protocol.getLinkedAttributeMessageFilters(attribute);messageFilters.ifPresent(mFilters -> {- synchronized (linkedAttributeFilters) {- linkedAttributeFilters.put(attributeRef, mFilters);- }+ linkedAttributeFilters.put(attributeRef, mFilters);});attribute.getMetaItem(AssetMeta.LOCATION_LINK).ifPresent(metaItem -> {- synchronized (locationLinkedAttributes) {- locationLinkedAttributes.add(attribute.getReferenceOrThrow());- }+ locationLinkedAttributes.add(attribute.getReferenceOrThrow());});try {@@ -193,42 +211,32 @@ public abstract class AbstractProtocol implements Protocol {} catch (Exception e) {LOG.log(Level.SEVERE, "Failed to link attribute to protocol: " + attribute, e);linkedAttributes.remove(attributeRef);- synchronized (linkedAttributeFilters) {- linkedAttributeFilters.remove(attributeRef);- }- synchronized (locationLinkedAttributes) {- locationLinkedAttributes.remove(attributeRef);- }+ linkedAttributeFilters.remove(attributeRef);+ locationLinkedAttributes.remove(attributeRef);}});- }+ });}@Overridepublic void unlinkAttributes(Collection<AssetAttribute> attributes, AssetAttribute protocolConfiguration) throws Exception {- synchronized (linkedAttributes) {+ withLock(() ->attributes.forEach(attribute -> {LOG.fine("Unlinking attribute on '" + getProtocolName() + "': " + attribute);AttributeRef attributeRef = attribute.getReferenceOrThrow();linkedAttributes.remove(attributeRef);- synchronized (linkedAttributeFilters) {- linkedAttributeFilters.remove(attributeRef);- }- synchronized (locationLinkedAttributes) {- locationLinkedAttributes.remove(attributeRef);- }+ linkedAttributeFilters.remove(attributeRef);+ locationLinkedAttributes.remove(attributeRef);doUnlinkAttribute(attribute, protocolConfiguration);- });- }+ })+ );}/*** Gets a linked attribute by its attribute ref*/protected AssetAttribute getLinkedAttribute(AttributeRef attributeRef) {- synchronized (linkedAttributes) {- return linkedAttributes.get(attributeRef);- }+ return withLockReturning(() -> linkedAttributes.get(attributeRef));}/**@@ -240,12 +248,25 @@ public abstract class AbstractProtocol implements Protocol {}protected AssetAttribute getLinkedProtocolConfiguration(AttributeRef protocolConfigurationRef) {- synchronized (linkedProtocolConfigurations) {+ return withLockReturning(() -> {LinkedProtocolInfo linkedProtocolInfo = linkedProtocolConfigurations.get(protocolConfigurationRef);// Don't bother with null check if someone calls here with an attribute not linked to this protocol// then they're doing something wrong so fail hard and fastreturn linkedProtocolInfo.getProtocolConfiguration();- }+ });+ }++ protected void processLinkedAttributeWrite(AttributeEvent event) {+ LOG.finest("Processing linked attribute write on " + getProtocolName() + ": " + event);+ withLock(() -> {+ AssetAttribute attribute = linkedAttributes.get(event.getAttributeRef());+ if (attribute == null) {+ LOG.warning("Attribute doesn't exist on this protocol: " + event.getAttributeRef());+ } else {+ AssetAttribute protocolConfiguration = getLinkedProtocolConfiguration(attribute);+ processLinkedAttributeWrite(event, protocolConfiguration);+ }+ });}/**@@ -262,18 +283,14 @@ public abstract class AbstractProtocol implements Protocol {* publish new sensor values, which performs additional verification and uses a different messaging queue.*/protected void sendAttributeEvent(AttributeEvent event) {- // Don't allow updating linked attributes with this mechanism as it could cause an infinite loop- boolean isForLinkedAttribute;-- synchronized (linkedAttributes) {- isForLinkedAttribute = linkedAttributes.containsKey(event.getAttributeRef());- }-- if (isForLinkedAttribute) {- LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that: " + event);- return;- }- assetService.sendAttributeEvent(event);+ withLock(() -> {+ // Don't allow updating linked attributes with this mechanism as it could cause an infinite loop+ if (linkedAttributes.containsKey(event.getAttributeRef())) {+ LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that: " + event);+ return;+ }+ assetService.sendAttributeEvent(event);+ });}/**@@ -282,111 +299,102 @@ public abstract class AbstractProtocol implements Protocol {* before sending on the sensor queue.*/@SuppressWarnings("unchecked")- protected void updateLinkedAttribute(AttributeState state, long timestamp) {- AssetAttribute attribute;- boolean updateLocation;-- synchronized (linkedAttributes) {- attribute = linkedAttributes.get(state.getAttributeRef());- }-- if (attribute == null) {- LOG.severe("Update linked attribute called for un-linked attribute: " + state);- return;- }+ protected void updateLinkedAttribute(final AttributeState finalState, long timestamp) {+ withLock(() -> {+ AttributeState state = finalState;+ AssetAttribute attribute = linkedAttributes.get(state.getAttributeRef());++ if (attribute == null) {+ LOG.severe("Update linked attribute called for un-linked attribute: " + state);+ return;+ }- if (state.getValue().isPresent()) {- List<MessageFilter> filters;- Value value = state.getValue().get();+ if (state.getValue().isPresent()) {+ List<MessageFilter> filters;+ Value value = state.getValue().get();- synchronized (linkedAttributeFilters) {filters = linkedAttributeFilters.get(state.getAttributeRef());- }- if (filters != null) {- LOG.fine("Applying message filters to sensor value...");-- for (MessageFilter filter : filters) {- if (filter.getMessageType() != value.getType().getModelType()) {- LOG.fine("Message filter type '" + filter.getMessageType().getName()- + "' is not compatible with actual message type '" + value.getType().getModelType().getName()- + "': " + filter.getClass().getName());- value = null;- } else {- try {- LOG.finest("Applying message filter: " + filter.getClass().getName());- value = filter.process(value);- } catch (Exception e) {- LOG.log(- Level.SEVERE,- "Message filter threw and exception during processing of message: "- + filter.getClass().getName(),- e);+ if (filters != null) {+ LOG.fine("Applying message filters to sensor value...");++ for (MessageFilter filter : filters) {+ if (filter.getMessageType() != value.getType().getModelType()) {+ LOG.fine("Message filter type '" + filter.getMessageType().getName()+ + "' is not compatible with actual message type '" + value.getType().getModelType().getName()+ + "': " + filter.getClass().getName());value = null;+ } else {+ try {+ LOG.finest("Applying message filter: " + filter.getClass().getName());+ value = filter.process(value);+ } catch (Exception e) {+ LOG.log(+ Level.SEVERE,+ "Message filter threw and exception during processing of message: "+ + filter.getClass().getName(),+ e);+ value = null;+ }}- }- if (value == null) {- break;+ if (value == null) {+ break;+ }}}- }- // Do basic value conversion- Optional<ValueType> attributeValueType = attribute.getType().map(AttributeType::getValueType);-- if (value != null && attributeValueType.isPresent()) {- if (attributeValueType.get() != value.getType()) {- LOG.fine("Converting value: " + value.getType() + " -> " + attributeValueType.get());- Optional<Value> convertedValue = Values.convert(value, attributeValueType.get());- if (!convertedValue.isPresent()) {- LOG.warning("Failed to convert value: " + value.getType() + " -> " + attributeValueType.get());- } else {- value = convertedValue.get();+ // Do basic value conversion+ Optional<ValueType> attributeValueType = attribute.getType().map(AttributeType::getValueType);++ if (value != null && attributeValueType.isPresent()) {+ if (attributeValueType.get() != value.getType()) {+ LOG.fine("Converting value: " + value.getType() + " -> " + attributeValueType.get());+ Optional<Value> convertedValue = Values.convert(value, attributeValueType.get());+ if (!convertedValue.isPresent()) {+ LOG.warning("Failed to convert value: " + value.getType() + " -> " + attributeValueType.get());+ } else {+ value = convertedValue.get();+ }}}- }- state = new AttributeState(state.getAttributeRef(), value);- }- AttributeEvent attributeEvent = new AttributeEvent(state, timestamp);- LOG.fine("Sending on sensor queue: " + attributeEvent);- producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, attributeEvent, Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, getProtocolName());--- synchronized (locationLinkedAttributes) {- updateLocation = locationLinkedAttributes.contains(state.getAttributeRef());- }+ state = new AttributeState(state.getAttributeRef(), value);+ }+ AttributeEvent attributeEvent = new AttributeEvent(state, timestamp);+ LOG.fine("Sending on sensor queue: " + attributeEvent);+ producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, attributeEvent, Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, getProtocolName());- if (updateLocation) {+ if (locationLinkedAttributes.contains(state.getAttributeRef())) {- // Check value type is compatible- Point location = state.getValue().map(value -> {- if (value.getType() != ValueType.ARRAY) {- LOG.warning("Location linked attribute type is not an array");- return null;- }+ // Check value type is compatible+ Point location = state.getValue().map(value -> {+ if (value.getType() != ValueType.ARRAY) {+ LOG.warning("Location linked attribute type is not an array");+ return null;+ }- Optional<List<NumberValue>> coordinates = Values.getArrayElements((ArrayValue)value, NumberValue.class, false, false);- if (!coordinates.isPresent()- || coordinates.get().size() != 2- || Math.abs(coordinates.get().get(0).getNumber()) > 180- || Math.abs(coordinates.get().get(1).getNumber()) > 90) {- LOG.warning("Location linked attribute value must contain longitude then latitude in a 2 value number array");- return null;- }+ Optional<List<NumberValue>> coordinates = Values.getArrayElements((ArrayValue) value, NumberValue.class, false, false);+ if (!coordinates.isPresent()+ || coordinates.get().size() != 2+ || Math.abs(coordinates.get().get(0).getNumber()) > 180+ || Math.abs(coordinates.get().get(1).getNumber()) > 90) {+ LOG.warning("Location linked attribute value must contain longitude then latitude in a 2 value number array");+ return null;+ }- try {- return new GeometryFactory().createPoint(- new Coordinate(coordinates.get().get(0).getNumber(), coordinates.get().get(1).getNumber())- );- } catch (Exception e) {- return null;- }- }).orElse(null);+ try {+ return new GeometryFactory().createPoint(+ new Coordinate(coordinates.get().get(0).getNumber(), coordinates.get().get(1).getNumber())+ );+ } catch (Exception e) {+ return null;+ }+ }).orElse(null);- updateAssetLocation(state.getAttributeRef().getEntityId(), location);- }+ updateAssetLocation(state.getAttributeRef().getEntityId(), location);+ }+ });}/**@@ -398,7 +406,7 @@ public abstract class AbstractProtocol implements Protocol {}protected void updateAssetLocation(String assetId, Point location) {- assetService.updateAssetLocation(assetId, location);+ withLock(() -> assetService.updateAssetLocation(assetId, location));}/**@@ -407,35 +415,35 @@ public abstract class AbstractProtocol implements Protocol {* the consumer to perform the modification.*/protected void updateLinkedProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<AssetAttribute> protocolUpdater) {- // Clone the protocol configuration rather than modify this one- AssetAttribute modifiedProtocolConfiguration = protocolConfiguration.deepCopy();- protocolUpdater.accept(modifiedProtocolConfiguration);- assetService.updateProtocolConfiguration(modifiedProtocolConfiguration);+ withLock(() -> {+ // Clone the protocol configuration rather than modify this one+ AssetAttribute modifiedProtocolConfiguration = protocolConfiguration.deepCopy();+ protocolUpdater.accept(modifiedProtocolConfiguration);+ assetService.updateProtocolConfiguration(modifiedProtocolConfiguration);+ });}/*** Update the runtime status of a protocol configuration by its attribute ref*/protected void updateStatus(AttributeRef protocolRef, ConnectionStatus connectionStatus) {- synchronized (linkedProtocolConfigurations) {- linkedProtocolConfigurations.computeIfPresent(protocolRef,- (ref, linkedProtocolInfo) -> {- linkedProtocolInfo.getConnectionStatusConsumer().accept(connectionStatus);- linkedProtocolInfo.setCurrentConnectionStatus(connectionStatus);- return linkedProtocolInfo;- }- );- }+ withLock(() -> {+ LinkedProtocolInfo protocolInfo = linkedProtocolConfigurations.get(protocolRef);+ if (protocolInfo != null) {+ protocolInfo.getConnectionStatusConsumer().accept(connectionStatus);+ protocolInfo.setCurrentConnectionStatus(connectionStatus);+ }+ });}/*** Gets the current runtime status of a protocol configuration.*/protected ConnectionStatus getStatus(AssetAttribute protocolConfiguration) {- synchronized (linkedProtocolConfigurations) {+ return withLockReturning(() -> {LinkedProtocolInfo linkedProtocolInfo = linkedProtocolConfigurations.get(protocolConfiguration.getReferenceOrThrow());return linkedProtocolInfo.getCurrentConnectionStatus();- }+ });}@Override@@ -472,6 +480,39 @@ public abstract class AbstractProtocol implements Protocol {return result;}+ /**+ * @return Defaults to 6 seconds, should be longer than it takes the router to be enabled/disabled.+ */+ protected int getLockTimeoutMillis() {+ return 6000;+ }++ protected void withLock(Runnable runnable) {+ withLockReturning(() -> {+ runnable.run();+ return null;+ });+ }++ protected <R> R withLockReturning(Supplier<R> supplier) {+ try {+ if (lock.tryLock(getLockTimeoutMillis(), TimeUnit.MILLISECONDS)) {+ LOG.finest("+ Acquired lock on: " + getProtocolName());+ return supplier.get();+ } else {+ throw new IllegalStateException(+ "Could not acquire lock after waiting " + getLockTimeoutMillis() + "ms on: " + getProtocolName()+ );+ }+ } catch (InterruptedException ex) {+ LOG.log(FINEST, "Interrupted while waiting for lock on: " + getProtocolName());+ return null;+ } finally {+ LOG.finest("- Releasing lock on: " + getProtocolName());+ lock.unlock();+ }+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.javaindex 969e3cabf..c6bfba893 100644--- a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java@@ -81,7 +81,7 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;* Any {@link Attribute} whose value is to be set by the HTTP server response (i.e. it has an {@link* #META_ATTRIBUTE_POLLING_SECONDS} {@link MetaItem}) can use the standard {@link Protocol#META_PROTOCOL_FILTERS} in* order to filter the received HTTP response.- *+ * <p>* <h1>Connection Status</h1>* <p>* The {@link ConnectionStatus} of the {@link ProtocolConfiguration} is determined by the ping {@link@@ -177,13 +177,13 @@ public class HttpClientProtocol extends AbstractProtocol {this.contentType = contentType;dynamicQueryParameters = queryParameters != null&& queryParameters- .entrySet()- .stream()- .anyMatch(paramNameAndValues ->- paramNameAndValues.getValue() != null- && paramNameAndValues.getValue()- .stream()- .anyMatch(val -> val.contains(DYNAMIC_VALUE_PLACEHOLDER)));+ .entrySet()+ .stream()+ .anyMatch(paramNameAndValues ->+ paramNameAndValues.getValue() != null+ && paramNameAndValues.getValue()+ .stream()+ .anyMatch(val -> val.contains(DYNAMIC_VALUE_PLACEHOLDER)));if (bodyValue != null) {if (contentType == null) {@@ -457,7 +457,7 @@ public class HttpClientProtocol extends AbstractProtocol {number -> Values.getIntegerCoerced(number).orElse(null))).orElse(null);- Optional<MultivaluedMap<String,String>> headers = Values.getMetaItemValueOrThrow(+ Optional<MultivaluedMap<String, String>> headers = Values.getMetaItemValueOrThrow(protocolConfiguration,META_HEADERS,ObjectValue.class,@@ -465,7 +465,7 @@ public class HttpClientProtocol extends AbstractProtocol {true).flatMap(objectValue -> getMultivaluedMap(objectValue, true));- Optional<MultivaluedMap<String,String>> queryParams = Values.getMetaItemValueOrThrow(+ Optional<MultivaluedMap<String, String>> queryParams = Values.getMetaItemValueOrThrow(protocolConfiguration,META_QUERY_PARAMETERS,ObjectValue.class,@@ -495,7 +495,7 @@ public class HttpClientProtocol extends AbstractProtocol {username.ifPresent(stringValue -> {LOG.info("Adding Basic Authentication");webTargetBuilder.setBasicAuthentication(stringValue.getString(),- password.get().getString());+ password.get().getString());});}headers.ifPresent(webTargetBuilder::setInjectHeaders);@@ -504,9 +504,8 @@ public class HttpClientProtocol extends AbstractProtocol {LOG.fine("Creating web target client '" + baseUri + "'");ResteasyWebTarget client = webTargetBuilder.build();- synchronized (clientMap) {- clientMap.put(protocolRef, new Pair<>(client, failureCodes));- }++ clientMap.put(protocolRef, new Pair<>(client, failureCodes));updateStatus(protocolRef, ConnectionStatus.UNKNOWN);if (pingPath == null) {@@ -527,7 +526,7 @@ public class HttpClientProtocol extends AbstractProtocol {.flatMap(AbstractValueHolder::getValue).orElse(null);- MultivaluedMap<String,String> pingQueryParams = Values.getMetaItemValueOrThrow(+ MultivaluedMap<String, String> pingQueryParams = Values.getMetaItemValueOrThrow(protocolConfiguration,META_PROTOCOL_PING_QUERY_PARAMETERS,ObjectValue.class,@@ -570,30 +569,21 @@ public class HttpClientProtocol extends AbstractProtocol {pingBody,contentType);- LOG.info("Creating ping polling request '" + pingRequest +"'");+ LOG.info("Creating ping polling request '" + pingRequest + "'");- synchronized (requestMap) {- requestMap.put(protocolRef, pingRequest);- }-- synchronized (pollingMap) {- pollingMap.put(protocolRef, schedulePollingRequest(- null,- protocolRef,- pingRequest,- pingPollingSeconds));- }+ requestMap.put(protocolRef, pingRequest);+ pollingMap.put(protocolRef, schedulePollingRequest(+ null,+ protocolRef,+ pingRequest,+ pingPollingSeconds));}@Overrideprotected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {AttributeRef protocolConfigurationRef = protocolConfiguration.getReferenceOrThrow();- synchronized (clientMap) {- clientMap.remove(protocolConfigurationRef);- }- synchronized (requestMap) {- requestMap.remove(protocolConfigurationRef);- }+ clientMap.remove(protocolConfigurationRef);+ requestMap.remove(protocolConfigurationRef);cancelPolling(protocolConfigurationRef);}@@ -601,9 +591,7 @@ public class HttpClientProtocol extends AbstractProtocol {protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {AttributeRef protocolConfigurationRef = protocolConfiguration.getReferenceOrThrow();Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes;- synchronized (clientMap) {- clientAndFailureCodes = clientMap.get(protocolConfigurationRef);- }+ clientAndFailureCodes = clientMap.get(protocolConfigurationRef);WebTarget client = clientAndFailureCodes != null ? clientAndFailureCodes.key : null;if (client == null) {@@ -666,7 +654,7 @@ public class HttpClientProtocol extends AbstractProtocol {return null;});- MultivaluedMap<String,String> headers = Values.getMetaItemValueOrThrow(+ MultivaluedMap<String, String> headers = Values.getMetaItemValueOrThrow(attribute,META_HEADERS,ObjectValue.class,@@ -675,7 +663,7 @@ public class HttpClientProtocol extends AbstractProtocol {.flatMap(objectValue -> getMultivaluedMap(objectValue, true)).orElse(null);- MultivaluedMap<String,String> queryParams = Values.getMetaItemValueOrThrow(+ MultivaluedMap<String, String> queryParams = Values.getMetaItemValueOrThrow(attribute,META_QUERY_PARAMETERS,ObjectValue.class,@@ -700,56 +688,43 @@ public class HttpClientProtocol extends AbstractProtocol {final AttributeRef attributeRef = attribute.getReferenceOrThrow();- synchronized (pollingMap) {- boolean updateConnectionStatus = !pollingMap.containsKey(protocolConfigurationRef);+ boolean updateConnectionStatus = !pollingMap.containsKey(protocolConfigurationRef);- HttpClientRequest clientRequest = buildClientRequest(- client,- path,- method,- headers,- queryParams,- failureCodes,- updateConnectionStatus,- body,- contentType);+ HttpClientRequest clientRequest = buildClientRequest(+ client,+ path,+ method,+ headers,+ queryParams,+ failureCodes,+ updateConnectionStatus,+ body,+ contentType);- LOG.fine("Creating HTTP request for linked attribute '" + clientRequest + "': " + attributeRef);+ LOG.fine("Creating HTTP request for linked attribute '" + clientRequest + "': " + attributeRef);- synchronized (requestMap) {- requestMap.put(attributeRef, clientRequest);- }+ requestMap.put(attributeRef, clientRequest);- pollingSeconds.ifPresent(seconds ->- pollingMap.put(attributeRef, schedulePollingRequest(- attributeRef,- protocolConfigurationRef,- clientRequest,- seconds)));- }+ pollingSeconds.ifPresent(seconds ->+ pollingMap.put(attributeRef, schedulePollingRequest(+ attributeRef,+ protocolConfigurationRef,+ clientRequest,+ seconds)));}@Overrideprotected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {AttributeRef attributeRef = attribute.getReferenceOrThrow();- synchronized (requestMap) {- requestMap.remove(attributeRef);- }+ requestMap.remove(attributeRef);cancelPolling(attributeRef);}@Overrideprotected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();- HttpClientRequest request;- Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes;-- synchronized (requestMap) {- request = requestMap.get(event.getAttributeRef());- }- synchronized (clientMap) {- clientAndFailureCodes = clientMap.get(protocolRef);- }+ HttpClientRequest request = requestMap.get(event.getAttributeRef());+ Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes = clientMap.get(protocolRef);// If permanent failure code occurred then protocol configuration could be about to be unlinked (disabled)// so the check here catches time between marked as disabled and actually being unlinked@@ -762,7 +737,7 @@ public class HttpClientProtocol extends AbstractProtocol {request,response,protocolRef- ));+ ));} else {LOG.finest("Ignoring attribute write request as either attribute or protocol configuration is not linked: " + event);}@@ -787,16 +762,16 @@ public class HttpClientProtocol extends AbstractProtocol {return !attribute.hasMetaItem(META_PROTOCOL_OAUTH_GRANT)? Optional.empty(): Optional.of(attribute.getMetaItem(META_PROTOCOL_OAUTH_GRANT)- .flatMap(AbstractValueHolder::getValueAsObject)- .map(objValue -> {- String json = objValue.toJson();- try {- return Container.JSON.readValue(json, OAuthGrant.class);- } catch (IOException e) {- throw new IllegalArgumentException("OAuth Grant meta item is not valid", e);- }- })- .orElseThrow(() -> new IllegalArgumentException("OAuth grant meta item must be an ObjectValue")));+ .flatMap(AbstractValueHolder::getValueAsObject)+ .map(objValue -> {+ String json = objValue.toJson();+ try {+ return Container.JSON.readValue(json, OAuthGrant.class);+ } catch (IOException e) {+ throw new IllegalArgumentException("OAuth Grant meta item is not valid", e);+ }+ })+ .orElseThrow(() -> new IllegalArgumentException("OAuth grant meta item must be an ObjectValue")));}public static Optional<MultivaluedMap<String, String>> getMultivaluedMap(ObjectValue objectValue, boolean throwOnError) throws ClassCastException, IllegalArgumentException {@@ -816,7 +791,7 @@ public class HttpClientProtocol extends AbstractProtocol {}break;case ARRAY:- Values.getArrayElements(((ArrayValue)keyAndValue.value),+ Values.getArrayElements(((ArrayValue) keyAndValue.value),StringValue.class,throwOnError,false,@@ -907,7 +882,7 @@ public class HttpClientProtocol extends AbstractProtocol {Value value = null;- if (response != null && response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {+ if (response != null && response.hasEntity() && response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {try {String responseBody = response.readEntity(String.class);value = responseBody != null ? Values.create(responseBody) : null;@@ -944,12 +919,12 @@ public class HttpClientProtocol extends AbstractProtocol {}protected void cancelPolling(AttributeRef attributeRef) {- synchronized (pollingMap) {+ withLock(() -> {ScheduledFuture pingPoll = pollingMap.remove(attributeRef);if (pingPoll != null) {pingPoll.cancel(false);}- }+ });}protected void updateConnectionStatus(HttpClientRequest request, AttributeRef protocolConfigurationRef, int responseCode) {@@ -984,7 +959,7 @@ public class HttpClientProtocol extends AbstractProtocol {}LOG.fine("Updating connection status based on polling response code: URI=" + request +- ", ResponseCode=" + responseCode + ", Status=" + connectionStatus);+ ", ResponseCode=" + responseCode + ", Status=" + connectionStatus);updateStatus(protocolConfigurationRef, connectionStatus);}diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.javaindex d06779a22..12b7e0a3a 100644--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java@@ -29,6 +29,7 @@ import org.openremote.model.value.ValueType;import org.openremote.model.value.Values;import java.util.*;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ScheduledFuture;import java.util.logging.Logger;@@ -81,9 +82,7 @@ public class MacroProtocol extends AbstractProtocol {}void start() {- synchronized (executions) {- executions.put(attributeRef, this);- }+ executions.put(attributeRef, this);updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.RUNNING.asValue()));run();}@@ -92,9 +91,7 @@ public class MacroProtocol extends AbstractProtocol {LOG.fine("Macro Execution cancel");scheduledFuture.cancel(false);cancelled = true;- synchronized (executions) {- executions.remove(attributeRef);- }+ executions.remove(attributeRef);updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.CANCELLED.asValue()));}@@ -122,10 +119,7 @@ public class MacroProtocol extends AbstractProtocol {}if ((isLast && !restart)) {- synchronized (executions) {- executions.remove(attributeRef);- }-+ executions.remove(attributeRef);// Update the command Status of this attributeupdateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.COMPLETED.asValue()));return;@@ -139,9 +133,8 @@ public class MacroProtocol extends AbstractProtocol {}}- protected final Map<AttributeRef, Pair<Boolean, List<MacroAction>>> macroMap = new HashMap<>();- protected final Map<AttributeRef, AttributeRef> macroAttributeMap = new HashMap<>();- protected final Map<AttributeRef, MacroExecutionTask> executions = new HashMap<>();+ protected final Map<AttributeRef, Pair<Boolean, List<MacroAction>>> macroMap = new ConcurrentHashMap<>();+ protected final Map<AttributeRef, MacroExecutionTask> executions = new ConcurrentHashMap<>();@Overridepublic String getProtocolName() {@@ -189,38 +182,29 @@ public class MacroProtocol extends AbstractProtocol {AttributeRef macroRef = protocolConfiguration.getReferenceOrThrow();boolean isEnabled = protocolConfiguration.isEnabled();- synchronized (macroMap) {- // Check macro configuration is valid- if (!isValidMacroConfiguration(protocolConfiguration)) {- LOG.fine("Macro configuration is not valid: " + protocolConfiguration);- updateStatus(macroRef, ConnectionStatus.ERROR);- // Put an empty list of actions against this macro- macroMap.put(macroRef, new Pair<>(isEnabled, Collections.emptyList()));- } else {- // Store the macro actions for later execution requests- macroMap.put(macroRef, new Pair<>(isEnabled, MacroConfiguration.getMacroActions(protocolConfiguration)));- updateStatus(macroRef, isEnabled ? ConnectionStatus.CONNECTED : ConnectionStatus.DISABLED);- }+ // Check macro configuration is valid+ if (!isValidMacroConfiguration(protocolConfiguration)) {+ LOG.fine("Macro configuration is not valid: " + protocolConfiguration);+ updateStatus(macroRef, ConnectionStatus.ERROR);+ // Put an empty list of actions against this macro+ macroMap.put(macroRef, new Pair<>(isEnabled, Collections.emptyList()));+ } else {+ // Store the macro actions for later execution requests+ macroMap.put(macroRef, new Pair<>(isEnabled, MacroConfiguration.getMacroActions(protocolConfiguration)));+ updateStatus(macroRef, isEnabled ? ConnectionStatus.CONNECTED : ConnectionStatus.DISABLED);}}@Overrideprotected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {AttributeRef macroRef = protocolConfiguration.getReferenceOrThrow();- synchronized (macroMap) {- macroMap.remove(macroRef);- }+ macroMap.remove(macroRef);}@Overrideprotected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {AttributeRef macroRef = protocolConfiguration.getReferenceOrThrow();- // Store link between attribute and configuration- synchronized (macroAttributeMap) {- macroAttributeMap.put(attribute.getReferenceOrThrow(), macroRef);- }-// Check for executable meta itemif (attribute.isExecutable()) {LOG.fine("Macro linked attribute is marked as executable so it will be linked to the firing of the macro");@@ -270,12 +254,6 @@ public class MacroProtocol extends AbstractProtocol {@Overrideprotected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {- // Store the macro actions for later execution requests- AttributeRef reference = attribute.getReferenceOrThrow();-- synchronized (macroAttributeMap) {- macroAttributeMap.remove(reference);- }}@Override@@ -294,15 +272,12 @@ public class MacroProtocol extends AbstractProtocol {// Check if it's a cancellation requestif (status == AttributeExecuteStatus.REQUEST_CANCEL) {LOG.fine("Request received to cancel macro execution: " + event);- synchronized (executions) {- executions.computeIfPresent(attributeRef,- (attributeRef1, macroExecutionTask) -> {- macroExecutionTask.cancel();- return macroExecutionTask;- }- );- }-+ executions.computeIfPresent(attributeRef,+ (attributeRef1, macroExecutionTask) -> {+ macroExecutionTask.cancel();+ return macroExecutionTask;+ }+ );return;}@@ -349,22 +324,20 @@ public class MacroProtocol extends AbstractProtocol {}protected List<MacroAction> getMacroActions(AttributeRef protocolConfigurationRef) {- synchronized (macroMap) {- Pair<Boolean, List<MacroAction>> actionsEnabledInfo;- actionsEnabledInfo = macroMap.get(protocolConfigurationRef);+ Pair<Boolean, List<MacroAction>> actionsEnabledInfo;+ actionsEnabledInfo = macroMap.get(protocolConfigurationRef);- if (actionsEnabledInfo == null || actionsEnabledInfo.value.size() == 0) {- LOG.fine("No macro actions found for macro configuration: " + protocolConfigurationRef);- return Collections.emptyList();- }-- if (!actionsEnabledInfo.key) {- LOG.fine("Macro configuration is disabled");- return Collections.emptyList();- }+ if (actionsEnabledInfo == null || actionsEnabledInfo.value.size() == 0) {+ LOG.fine("No macro actions found for macro configuration: " + protocolConfigurationRef);+ return Collections.emptyList();+ }- return actionsEnabledInfo.value;+ if (!actionsEnabledInfo.key) {+ LOG.fine("Macro configuration is disabled");+ return Collections.emptyList();}++ return actionsEnabledInfo.value;}protected void executeMacro(AttributeRef attributeRef, List<MacroAction> actions, boolean repeat) {diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.javaindex 02d787061..518173cbc 100644--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java@@ -20,10 +20,10 @@package org.openremote.agent.protocol.simulator;import org.openremote.agent.protocol.AbstractProtocol;-import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.AbstractValueHolder;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.attribute.*;import org.openremote.model.simulator.SimulatorElement;import org.openremote.model.simulator.SimulatorState;@@ -197,50 +197,43 @@ public class SimulatorProtocol extends AbstractProtocol {protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();- synchronized (instances) {- instances- .computeIfAbsent(- protocolRef,- ref -> {- Mode mode = protocolConfiguration- .getMetaItem(CONFIG_MODE)- .map(item ->- item.getValueAsString()- .map(value -> {- try {- return Mode.valueOf(value);- } catch (Exception e) {- LOG.fine("Invalid Mode value '" + item + "' provided");- return null;- }- })- .orElse(null)- )- .orElse(Mode.WRITE_THROUGH_IMMEDIATE);-- int writeDelay = protocolConfiguration.getMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS)- .flatMap(AbstractValueHolder::getValueAsInteger)- .orElse(DEFAULT_WRITE_DELAY);-- updateStatus(protocolRef, protocolConfiguration.isEnabled() ? ConnectionStatus.CONNECTED : ConnectionStatus.DISABLED);- return new Instance(mode, writeDelay, protocolConfiguration.isEnabled());- }- );- }+ instances.computeIfAbsent(+ protocolRef,+ ref -> {+ Mode mode = protocolConfiguration+ .getMetaItem(CONFIG_MODE)+ .map(item ->+ item.getValueAsString()+ .map(value -> {+ try {+ return Mode.valueOf(value);+ } catch (Exception e) {+ LOG.fine("Invalid Mode value '" + item + "' provided");+ return null;+ }+ })+ .orElse(null)+ )+ .orElse(Mode.WRITE_THROUGH_IMMEDIATE);++ int writeDelay = protocolConfiguration.getMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS)+ .flatMap(AbstractValueHolder::getValueAsInteger)+ .orElse(DEFAULT_WRITE_DELAY);++ updateStatus(protocolRef, protocolConfiguration.isEnabled() ? ConnectionStatus.CONNECTED : ConnectionStatus.DISABLED);+ return new Instance(mode, writeDelay, protocolConfiguration.isEnabled());+ }+ );}@Overrideprotected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {AttributeRef configRef = protocolConfiguration.getReferenceOrThrow();-- synchronized (instances) {- instances.remove(configRef);- }+ instances.remove(configRef);}@Overrideprotected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {-// Get element type from the attribute metaOptional<String> elementType = getElementType(attribute);if (!elementType.isPresent()) {@@ -268,20 +261,15 @@ public class SimulatorProtocol extends AbstractProtocol {LOG.info("Putting element '" + element + "' for: " + attribute);- synchronized (instances) {- elements.put(attributeRef, element);- attributeInstanceMap.put(attributeRef, configRef);- }+ elements.put(attributeRef, element);+ attributeInstanceMap.put(attributeRef, configRef);}@Overrideprotected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {AttributeRef attributeRef = attribute.getReferenceOrThrow();-- synchronized (instances) {- elements.remove(attributeRef);- attributeInstanceMap.remove(attributeRef);- }+ elements.remove(attributeRef);+ attributeInstanceMap.remove(attributeRef);}@Override@@ -337,27 +325,25 @@ public class SimulatorProtocol extends AbstractProtocol {return;}- Instance instance;-- synchronized (instances) {- instance = instances.get(instanceRef);- }+ withLock(() -> {+ Instance instance = instances.get(instanceRef);- if (instance == null) {- LOG.warning("No instance found by name '" + instanceRef + "'");- return;- }+ if (instance == null) {+ LOG.warning("No instance found by name '" + instanceRef + "'");+ return;+ }- if (!instance.isEnabled()) {- LOG.fine("Simulator protocol configuration is disabled so cannot process request");- return;- }+ if (!instance.isEnabled()) {+ LOG.fine("Simulator protocol configuration is disabled so cannot process request");+ return;+ }- if (updateSensorDelayMilliseconds <= 0) {- updateLinkedAttribute(state);- } else {- executorService.schedule(() -> updateLinkedAttribute(state), updateSensorDelayMilliseconds);- }+ if (updateSensorDelayMilliseconds <= 0) {+ updateLinkedAttribute(state);+ } else {+ executorService.schedule(() -> updateLinkedAttribute(state), updateSensorDelayMilliseconds);+ }+ });}/**@@ -393,11 +379,8 @@ public class SimulatorProtocol extends AbstractProtocol {return false;}- Instance instance;-- synchronized (instances) {- instance = instances.get(instanceRef);-+ return withLockReturning(() -> {+ Instance instance = instances.get(instanceRef);if (instance == null) {LOG.warning("No instance found by name '" + instanceRef + "'");return false;@@ -425,13 +408,13 @@ public class SimulatorProtocol extends AbstractProtocol {LOG.warning("Failed to update simulator element, state validation failures " + failures + ": " + attributeRef);return false;}- }- if (instance.getMode() != Mode.MANUAL) {- updateSensor(attributeRef, instance.getMode() == Mode.WRITE_THROUGH_IMMEDIATE ? 0 : instance.getDelayMilliseconds());- }+ if (instance.getMode() != Mode.MANUAL) {+ updateSensor(attributeRef, instance.getMode() == Mode.WRITE_THROUGH_IMMEDIATE ? 0 : instance.getDelayMilliseconds());+ }- return true;+ return true;+ });}/**@@ -445,10 +428,10 @@ public class SimulatorProtocol extends AbstractProtocol {* Call this to get the current value of an attribute.*/public Optional<Value> getValue(AttributeRef attributeRef) {- synchronized (instances) {+ return withLockReturning(() -> {SimulatorElement element = elements.get(attributeRef);return element != null ? element.getValue() : Optional.empty();- }+ });}public List<SimulatorElement> getLinkedElements(AttributeRef protocolConfigurationRef) {@@ -469,7 +452,7 @@ public class SimulatorProtocol extends AbstractProtocol {* Read a state snapshot.*/public Optional<SimulatorState> getSimulatorState(AttributeRef protocolConfigurationRef) {- synchronized (instances) {+ return withLockReturning(() -> {LOG.info("Getting simulator state for protocol configuration: " + protocolConfigurationRef);if (!instances.containsKey(protocolConfigurationRef))return Optional.empty();@@ -481,14 +464,14 @@ public class SimulatorProtocol extends AbstractProtocol {linkedElements.toArray(new SimulatorElement[linkedElements.size()])));- }+ });}/*** Write a state snapshot.*/public void updateSimulatorState(SimulatorState simulatorState) {- synchronized (instances) {+ withLock(() -> {AttributeRef protocolConfigurationRef = simulatorState.getProtocolConfigurationRef();if (!instances.containsKey(protocolConfigurationRef)) {LOG.info("Ignoring simulator update, no instance for protocol configuration: " + protocolConfigurationRef);@@ -498,7 +481,7 @@ public class SimulatorProtocol extends AbstractProtocol {for (SimulatorElement updatedElement : simulatorState.getElements()) {putValue(updatedElement.getAttributeRef(), updatedElement.getValue().orElse(null));}- }+ });}protected SimulatorElement createElement(String elementType, AssetAttribute attribute) {diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.javaindex b093d77f0..56c869552 100644--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java@@ -20,9 +20,9 @@package org.openremote.agent.protocol.timer;import org.openremote.agent.protocol.AbstractProtocol;-import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.attribute.*;import org.openremote.model.util.TextUtil;import org.openremote.model.value.Value;@@ -168,9 +168,7 @@ public class TimerProtocol extends AbstractProtocol {return;}- synchronized (cronExpressionMap) {- cronExpressionMap.put(protocolRef, expressionParser);- }+ cronExpressionMap.put(protocolRef, expressionParser);if (protocolConfiguration.isEnabled()) {updateStatus(protocolRef, ConnectionStatus.CONNECTED);@@ -192,10 +190,8 @@ public class TimerProtocol extends AbstractProtocol {protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {AttributeRef protocolConfigRef = protocolConfiguration.getReferenceOrThrow();- synchronized (cronExpressionMap) {- if (cronExpressionMap.remove(protocolConfigRef) != null) {- getCronScheduler().removeJob(getTimerId(protocolConfigRef));- }+ if (cronExpressionMap.remove(protocolConfigRef) != null) {+ getCronScheduler().removeJob(getTimerId(protocolConfigRef));}}@@ -248,7 +244,7 @@ public class TimerProtocol extends AbstractProtocol {LOG.warning("Send to actuator value for time trigger must be a non empty string");return;}- CronExpressionParser parser = getCronExpressionParser(protocolConfiguration.getReferenceOrThrow());+ CronExpressionParser parser = cronExpressionMap.get(protocolConfiguration.getReferenceOrThrow());if (parser == null) {LOG.info("Ignoring trigger update because current cron expression is invalid");return;@@ -292,7 +288,7 @@ public class TimerProtocol extends AbstractProtocol {break;case CRON_EXPRESSION:case TIME:- CronExpressionParser parser = getCronExpressionParser(protocolConfiguration.getReferenceOrThrow());+ CronExpressionParser parser = cronExpressionMap.get(protocolConfiguration.getReferenceOrThrow());if (parser == null) {LOG.info("Attribute is linked to an invalid timer so it will be ignored");return;@@ -353,12 +349,6 @@ public class TimerProtocol extends AbstractProtocol {return cronScheduler;}- protected CronExpressionParser getCronExpressionParser(AttributeRef timerRef) {- synchronized (cronExpressionMap) {- return cronExpressionMap.get(timerRef);- }- }-@Overridepublic String getVersion() {return VERSION;diff --git a/client/src/main/java/org/openremote/app/client/simulator/Simulator.java b/client/src/main/java/org/openremote/app/client/simulator/Simulator.javaindex c0fd8a243..d8e93a88c 100644--- a/client/src/main/java/org/openremote/app/client/simulator/Simulator.java+++ b/client/src/main/java/org/openremote/app/client/simulator/Simulator.java@@ -107,7 +107,7 @@ public class Simulator extends AbstractAttributeViewExtension {String elementName = simulatorState.getElementName(element);FormLabel formLabel = new FormLabel(elementName);- formLabel.addStyleName("larger");+ formLabel.addStyleName("largest");formGroup.setFormLabel(formLabel);FormField formField = new FormField();diff --git a/client/src/main/webapp/src/or-app/or-style.html b/client/src/main/webapp/src/or-app/or-style.htmlindex e3d09ec0f..3a71d3c36 100644--- a/client/src/main/webapp/src/or-app/or-style.html+++ b/client/src/main/webapp/src/or-app/or-style.html@@ -353,6 +353,10 @@width: 15em;}+ .or-FormLabel.largest {+ width: 25em;+ }+.or-FormField {min-width: 10em;}diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.javaindex d88380ef4..201fe9759 100644--- a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java@@ -19,6 +19,10 @@*/package org.openremote.container.persistence;+import org.apache.camel.Predicate;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetType;+import java.util.Arrays;public class PersistenceEvent<T> {@@ -33,6 +37,23 @@ public class PersistenceEvent<T> {INSERT, UPDATE, DELETE}+ public static Predicate isPersistenceEventForEntityType(Class<?> type) {+ return exchange -> {+ Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);+ return type.isAssignableFrom(entityType);+ };+ }++ public static Predicate isPersistenceEventForAssetType(AssetType assetType) {+ return exchange -> {+ if (!(exchange.getIn().getBody() instanceof PersistenceEvent))+ return false;+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ Asset asset = (Asset) persistenceEvent.getEntity();+ return asset.getWellKnownType() == assetType;+ };+ }+final protected Cause cause;final protected T entity;final protected String[] propertyNames;diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.javaindex 9147e2606..9d5d5d3bc 100644--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java@@ -55,9 +55,9 @@ import java.util.stream.Stream;import static org.openremote.agent.protocol.Protocol.ACTUATOR_TOPIC;import static org.openremote.agent.protocol.Protocol.SENSOR_QUEUE;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;+import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForAssetType;+import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForEntityType;import static org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE;-import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForAssetType;-import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForEntityType;import static org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME;import static org.openremote.model.asset.AssetAttribute.attributesFromJson;import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes;diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex 72405d724..8c2b0d276 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -57,7 +57,7 @@ import java.util.function.Consumer;import java.util.logging.Logger;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;-import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForEntityType;+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.BaseAssetQuery.*;diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java b/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.javaindex 99028822b..7f4f5b9d7 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java@@ -19,34 +19,13 @@*/package org.openremote.manager.asset;-import org.apache.camel.Predicate;-import org.openremote.container.persistence.PersistenceEvent;-import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetType;import org.openremote.model.attribute.AttributeEvent.Source;import javax.persistence.EntityManager;public interface AssetUpdateProcessor {- static Predicate isPersistenceEventForEntityType(Class<?> type) {- return exchange -> {- Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);- return type.isAssignableFrom(entityType);- };- }-- static Predicate isPersistenceEventForAssetType(AssetType assetType) {- return exchange -> {- if (!(exchange.getIn().getBody() instanceof PersistenceEvent))- return false;- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- Asset asset = (Asset) persistenceEvent.getEntity();- return asset.getWellKnownType() == assetType;- };- }-/*** @param em The current session and transaction on the database, processors may use this to query additional data.* @param asset The current asset state with the old value and old value timestamp.diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 06504a37d..20efb242d 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -295,10 +295,11 @@ public class RulesEngine<T extends Ruleset> {// Remove any expired temporary factsboolean factsExpired = facts.removeExpiredTemporaryFacts();- // TODO Optimize:+ // TODO Optimize if scheduled firing of rules becomes a performance problem:// Add fire(scheduledFiring) boolean// Add enableTimer() as rule declaration option, each rule which uses time windows must set it// Only fire if factsExpired || deployment.isAnyRuleEnabledTimer()+ // Rules could default to enableTimer(true) and they could reduce firing frequency with enableTimer("1m")for (RulesetDeployment deployment : deployments.values()) {try {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex f057b3e15..cb4a87ca1 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -52,8 +52,8 @@ import java.util.stream.Stream;import static java.util.logging.Level.FINEST;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;+import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForEntityType;import static org.openremote.container.util.MapAccess.getString;-import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForEntityType;import static org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME;import static org.openremote.model.asset.AssetAttribute.attributesFromJson;import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes;diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.javaindex b31966204..31dc9d849 100644--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java@@ -20,9 +20,6 @@package org.openremote.model.asset;import jsinterop.annotations.JsType;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetQuery;-import org.openremote.model.asset.UserAsset;import org.openremote.model.http.RequestParams;import org.openremote.model.http.SuccessStatusCode;diff --git a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java b/model/src/main/java/org/openremote/model/rules/TemporaryFact.javaindex cd4ee9a90..4ed5d6863 100644--- a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java+++ b/model/src/main/java/org/openremote/model/rules/TemporaryFact.java@@ -37,7 +37,8 @@ public class TemporaryFact<T> extends Event {* This value defines the periodic firing of the rules engines when temporary* facts are present, and therefore has an impact on system load. If a temporary* fact has a shorter expiration time, it's not guaranteed to be removed within- * that time.+ * that time. Any time-based operation, such as matching temporary facts in a+ * sliding time window, must be designed with this margin in mind.*/public static final int GUARANTEED_MIN_EXPIRATION_MILLIS = 3000;diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovyindex c8f968df4..417ab0ea2 100644--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy@@ -24,7 +24,6 @@ import org.jboss.resteasy.util.BasicAuthHelperimport org.openremote.agent.protocol.Protocolimport org.openremote.agent.protocol.filter.RegexFilterimport org.openremote.agent.protocol.http.*-import org.openremote.container.Containerimport org.openremote.manager.agent.AgentServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService@@ -42,7 +41,6 @@ import org.openremote.model.value.ObjectValueimport org.openremote.model.value.Valueimport org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTrait-import spock.lang.Ignoreimport spock.lang.Sharedimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -55,8 +53,6 @@ import java.util.concurrent.TimeUnitimport static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration-@Ignore-// TODO Often ends in deadlock in protocol doLinkAttribute()class HttpClientProtocolTest extends Specification implements ManagerContainerTrait {@Shared@@ -370,7 +366,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTrThread.sleep(50)assert mockServer.pingCount == pingCount- /* Test ping using POST with body and query parameters */+ // Test ping using POST with body and query parameterswhen: "ping count is reset"mockServer.pingCount = 0