Skip to content

armgit / core

Public Imported from GitHub
0

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

Model renaming, cleanup and documentation

Christian Bauerf98af2bbc603
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
index 4b0080b90..b14a91369 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
@@ -27,7 +27,7 @@ import org.openremote.model.asset.ThingAttribute;
import org.openremote.container.Container;
import org.openremote.container.message.MessageBrokerContext;
import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeValueChange;
+import org.openremote.model.AttributeState;
import java.util.Collection;
import java.util.HashMap;
@@ -39,12 +39,12 @@ public abstract class AbstractProtocol implements Protocol {
private static final Logger LOG = Logger.getLogger(AbstractProtocol.class.getName());
- static Predicate isAttributeValueChangeIn(Collection<AttributeRef> attributeRefs) {
+ static Predicate isAttributeStateIn(Collection<AttributeRef> attributeRefs) {
return exchange -> {
- if (!(exchange.getIn().getBody() instanceof AttributeValueChange))
+ if (!(exchange.getIn().getBody() instanceof AttributeState))
return false;
- AttributeValueChange valueChange = exchange.getIn().getBody(AttributeValueChange.class);
- return attributeRefs.contains(valueChange.getAttributeRef());
+ AttributeState attributeState = exchange.getIn().getBody(AttributeState.class);
+ return attributeRefs.contains(attributeState.getAttributeRef());
};
}
@@ -71,8 +71,8 @@ public abstract class AbstractProtocol implements Protocol {
.process(exchange -> {
synchronized (linkedAttributes) {
// TODO This could be optimized, we must avoid inspecting all messages (maybe tag with protocol name in header?)
- if (isAttributeValueChangeIn(linkedAttributes.keySet()).matches(exchange)) {
- sendToActuator(exchange.getIn().getBody(AttributeValueChange.class));
+ if (isAttributeStateIn(linkedAttributes.keySet()).matches(exchange)) {
+ sendToActuator(exchange.getIn().getBody(AttributeState.class));
}
}
});
@@ -128,11 +128,11 @@ public abstract class AbstractProtocol implements Protocol {
}
}
- protected void onSensorUpdate(AttributeValueChange attributeValueChange) {
- producerTemplate.sendBody(SENSOR_TOPIC, attributeValueChange);
+ protected void onSensorUpdate(AttributeState attributeState) {
+ producerTemplate.sendBody(SENSOR_TOPIC, attributeState);
}
- abstract protected void sendToActuator(AttributeValueChange attributeValueChange);
+ abstract protected void sendToActuator(AttributeState attributeState);
abstract protected void onAttributeAdded(ThingAttribute attribute);
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
index db4b0d89e..f79de5148 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
@@ -20,6 +20,7 @@
package org.openremote.agent3.protocol;
import org.openremote.container.ContainerService;
+import org.openremote.model.AttributeState;
import org.openremote.model.Constants;
import org.openremote.model.asset.ThingAttribute;
@@ -31,8 +32,8 @@ import java.util.Collection;
* OpenRemote protocols are in {@link Constants#PROTOCOL_NAMESPACE}, third-party protocols
* should use their own URN namespace identifier.
* <p>
- * The protocol implementation can receive {@link org.openremote.model.AttributeValueChange} messages on the
- * {@link #ACTUATOR_TOPIC}. It can produce {@link org.openremote.model.AttributeValueChange} messages on the
+ * The protocol implementation can receive {@link AttributeState} messages on the
+ * {@link #ACTUATOR_TOPIC}. It can produce {@link AttributeState} messages on the
* {@link #SENSOR_TOPIC}.
* <p>
* The linked attributes of a protocol provide the model for the protocol to perform these operations. How
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
index 2bb64864f..6f1b4c420 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
@@ -23,8 +23,8 @@ import elemental.json.JsonValue;
import org.openremote.agent3.protocol.AbstractProtocol;
import org.openremote.agent3.protocol.simulator.element.*;
import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeValueChange;
-import org.openremote.model.MetadataItem;
+import org.openremote.model.AttributeState;
+import org.openremote.model.MetaItem;
import org.openremote.model.asset.ThingAttribute;
import java.util.HashMap;
@@ -33,8 +33,8 @@ import java.util.Map;
import java.util.logging.Logger;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
-import static org.openremote.model.asset.AssetAttributeMeta.RANGE_MAX;
-import static org.openremote.model.asset.AssetAttributeMeta.RANGE_MIN;
+import static org.openremote.model.asset.AssetMeta.RANGE_MAX;
+import static org.openremote.model.asset.AssetMeta.RANGE_MIN;
public class SimulatorProtocol extends AbstractProtocol {
@@ -70,8 +70,8 @@ public class SimulatorProtocol extends AbstractProtocol {
}
@Override
- protected void sendToActuator(AttributeValueChange attributeValueChange) {
- putState(attributeValueChange.getAttributeRef(), attributeValueChange.getValue(), false);
+ protected void sendToActuator(AttributeState attributeState) {
+ putState(attributeState.getAttributeRef(), attributeState.getValue(), false);
}
public void putState(String entityId, String attributeName, JsonValue value) {
@@ -83,7 +83,7 @@ public class SimulatorProtocol extends AbstractProtocol {
}
/**
- * @param isSensorUpdate <code>true</code> if an {@link AttributeValueChange} message should be produced
+ * @param isSensorUpdate <code>true</code> if an {@link AttributeState} message should be produced
*/
public void putState(AttributeRef attributeRef, JsonValue value, boolean isSensorUpdate) {
synchronized (elements) {
@@ -97,7 +97,7 @@ public class SimulatorProtocol extends AbstractProtocol {
if (isSensorUpdate) {
LOG.fine("Propagating state change as sensor update: " + element);
- onSensorUpdate(new AttributeValueChange(attributeRef, value));
+ onSensorUpdate(new AttributeState(attributeRef, value));
}
}
}
@@ -124,8 +124,8 @@ public class SimulatorProtocol extends AbstractProtocol {
case "decimal":
return new DecimalSimulatorElement();
case "range":
- MetadataItem minItem = attribute.firstMetaItem(RANGE_MIN);
- MetadataItem maxItem = attribute.firstMetaItem(RANGE_MAX);
+ MetaItem minItem = attribute.firstMetaItem(RANGE_MIN);
+ MetaItem maxItem = attribute.firstMetaItem(RANGE_MAX);
double min = minItem != null ? minItem.getValueAsInteger() : 0;
double max = maxItem != null ? maxItem.getValueAsInteger() : 100;
return new IntegerSimulatorElement(min, max);
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
index a17f43a24..77c9d225e 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
@@ -24,6 +24,6 @@ import org.openremote.model.AttributeType;
public class ColorSimulatorElement extends SimulatorElement {
public ColorSimulatorElement() {
- super(AttributeType.OBJECT);
+ super(AttributeType.INTEGER_ARRAY);
}
}
diff --git a/container/src/main/java/org/openremote/container/web/ExtensibleResteasyClientBuilder.java b/container/src/main/java/org/openremote/container/web/ExtensibleResteasyClientBuilder.java
index 1356711d5..c1c15c752 100644
--- a/container/src/main/java/org/openremote/container/web/ExtensibleResteasyClientBuilder.java
+++ b/container/src/main/java/org/openremote/container/web/ExtensibleResteasyClientBuilder.java
@@ -33,7 +33,7 @@ public class ExtensibleResteasyClientBuilder extends ResteasyClientBuilder {
@Override
public ResteasyClient build() {
- httpEngine(initDefaultEngine43());
+ httpEngine(initDefaultEngine43(this));
return super.build();
}
@@ -51,14 +51,15 @@ public class ExtensibleResteasyClientBuilder extends ResteasyClientBuilder {
// The rest is copy/paste pretty much
- public ApacheHttpClient43Engine initDefaultEngine43() {
+ static public ApacheHttpClient43Engine initDefaultEngine43(ExtensibleResteasyClientBuilder that) {
+
HttpClient httpClient = null;
HostnameVerifier verifier = null;
- if (verifier != null) {
- verifier = new ExtensibleResteasyClientBuilder.VerifierWrapper(verifier);
+ if (that.verifier != null) {
+ verifier = new ExtensibleResteasyClientBuilder.VerifierWrapper(that.verifier);
} else {
- switch (policy) {
+ switch (that.policy) {
case ANY:
verifier = new NoopHostnameVerifier();
break;
@@ -72,8 +73,8 @@ public class ExtensibleResteasyClientBuilder extends ResteasyClientBuilder {
}
try {
SSLConnectionSocketFactory sslsf = null;
- SSLContext theContext = sslContext;
- if (disableTrustManager) {
+ SSLContext theContext = that.sslContext;
+ if (that.disableTrustManager) {
theContext = SSLContext.getInstance("SSL");
theContext.init(null, new TrustManager[]{new PassthroughTrustManager()},
new SecureRandom());
@@ -83,21 +84,21 @@ public class ExtensibleResteasyClientBuilder extends ResteasyClientBuilder {
sslsf = new SSLConnectionSocketFactory(theContext, verifier) {
@Override
protected void prepareSocket(SSLSocket socket) throws IOException {
- prepareSocketForSni(socket);
+ that.prepareSocketForSni(socket);
}
};
- } else if (clientKeyStore != null || truststore != null) {
+ } else if (that.clientKeyStore != null || that.truststore != null) {
SSLContext ctx = SSLContexts.custom()
.useProtocol(SSLConnectionSocketFactory.TLS)
.setSecureRandom(null)
- .loadKeyMaterial(clientKeyStore,
- clientPrivateKeyPassword != null ? clientPrivateKeyPassword.toCharArray() : null)
- .loadTrustMaterial(truststore, TrustSelfSignedStrategy.INSTANCE)
+ .loadKeyMaterial(that.clientKeyStore,
+ that.clientPrivateKeyPassword != null ? that.clientPrivateKeyPassword.toCharArray() : null)
+ .loadTrustMaterial(that.truststore, TrustSelfSignedStrategy.INSTANCE)
.build();
sslsf = new SSLConnectionSocketFactory(ctx, verifier) {
@Override
protected void prepareSocket(SSLSocket socket) throws IOException {
- prepareSocketForSni(socket);
+ that.prepareSocketForSni(socket);
}
};
} else {
@@ -112,14 +113,14 @@ public class ExtensibleResteasyClientBuilder extends ResteasyClientBuilder {
.build();
HttpClientConnectionManager cm = null;
- if (connectionPoolSize > 0) {
+ if (that.connectionPoolSize > 0) {
PoolingHttpClientConnectionManager tcm = new PoolingHttpClientConnectionManager(
- registry, null, null, null, connectionTTL, connectionTTLUnit);
- tcm.setMaxTotal(connectionPoolSize);
- if (maxPooledPerRoute == 0) {
- maxPooledPerRoute = connectionPoolSize;
+ registry, null, null, null, that.connectionTTL, that.connectionTTLUnit);
+ tcm.setMaxTotal(that.connectionPoolSize);
+ if (that.maxPooledPerRoute == 0) {
+ that.maxPooledPerRoute = that.connectionPoolSize;
}
- tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
+ tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute);
cm = tcm;
} else {
@@ -127,26 +128,28 @@ public class ExtensibleResteasyClientBuilder extends ResteasyClientBuilder {
}
RequestConfig.Builder rcBuilder = RequestConfig.custom();
- if (socketTimeout > -1) {
- rcBuilder.setSocketTimeout((int) socketTimeoutUnits.toMillis(socketTimeout));
+ if (that.socketTimeout > -1) {
+ rcBuilder.setSocketTimeout((int) that.socketTimeoutUnits.toMillis(that.socketTimeout));
}
- if (establishConnectionTimeout > -1) {
- rcBuilder.setConnectTimeout((int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
+ if (that.establishConnectionTimeout > -1) {
+ rcBuilder.setConnectTimeout((int) that.establishConnectionTimeoutUnits.toMillis(that.establishConnectionTimeout));
}
- if (connectionCheckoutTimeoutMs > -1) {
- rcBuilder.setConnectionRequestTimeout(connectionCheckoutTimeoutMs);
+ if (that.connectionCheckoutTimeoutMs > -1) {
+ rcBuilder.setConnectionRequestTimeout(that.connectionCheckoutTimeoutMs);
}
- httpClient = configure(HttpClientBuilder.create()
- .setConnectionManager(cm)
- .setDefaultRequestConfig(rcBuilder.build())
- .setProxy(defaultProxy)
- .disableContentCompression()
+ // The magic configure()
+ httpClient = that.configure(
+ HttpClientBuilder.create()
+ .setConnectionManager(cm)
+ .setDefaultRequestConfig(rcBuilder.build())
+ .setProxy(that.defaultProxy)
+ .disableContentCompression()
).build();
ApacheHttpClient43Engine engine =
(ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient, true);
- engine.setResponseBufferSize(responseBufferSize);
+ engine.setResponseBufferSize(that.responseBufferSize);
engine.setHostnameVerifier(verifier);
// this may be null. We can't really support this with Apache Client.
engine.setSslContext(theContext);
diff --git a/manager/client/build.gradle b/manager/client/build.gradle
index 8b1cc6ce9..a6d0d3547 100644
--- a/manager/client/build.gradle
+++ b/manager/client/build.gradle
@@ -13,12 +13,16 @@ dependencies {
compile "com.google.gwt:gwt-user:$gwtVersion"
compile("com.google.gwt.inject:gin:$ginVersion")
+
+ // TODO https://github.com/nmorel/gwt-jackson/issues/106
compile files(['lib/gwt-jackson-0.14.2-SNAPSHOT.jar'])
//compile "com.github.nmorel.gwtjackson:gwt-jackson:$gwtJacksonVersion"
// This is not on regular classpath, only used when compiling GWT/running codeserver
- gwtDev files(['lib/javapoet-1.0.0.jar', 'lib/jackson-annotations-2.8.6-sources.jar'])
gwtDev "com.google.gwt:gwt-dev:$gwtVersion"
+ // TODO https://github.com/nmorel/gwt-jackson/issues/106
+ gwtDev files(['lib/javapoet-1.0.0.jar', 'lib/jackson-annotations-2.8.6-sources.jar'])
+
}
def gwtOutputDir = "${project.buildDir}/gwt/out"
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java
index a037b8711..2f01f71be 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributesEditor.java
@@ -21,7 +21,10 @@ package org.openremote.manager.client.widget;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.DomEvent;
-import com.google.gwt.user.client.ui.*;
+import com.google.gwt.user.client.ui.FlowPanel;
+import com.google.gwt.user.client.ui.InsertPanel;
+import com.google.gwt.user.client.ui.IsWidget;
+import com.google.gwt.user.client.ui.Label;
import elemental.json.Json;
import elemental.json.JsonType;
import elemental.json.JsonValue;
@@ -33,9 +36,10 @@ import org.openremote.manager.shared.event.ui.ShowFailureEvent;
import org.openremote.manager.shared.event.ui.ShowInfoEvent;
import org.openremote.model.*;
import org.openremote.model.Runnable;
-import org.openremote.model.asset.AssetAttributeMeta;
+import org.openremote.model.asset.AssetMeta;
-import java.util.*;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
import java.util.logging.Logger;
import static org.openremote.manager.shared.util.Util.sortMap;
@@ -194,7 +198,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
formGroup.addFormField(formField);
formField.add(createEditor(attribute, formGroup));
- MetadataItem description = AssetAttributeMeta.getFirst(attribute, AssetAttributeMeta.DESCRIPTION);
+ MetaItem description = AssetMeta.getFirst(attribute, AssetMeta.DESCRIPTION);
if (description != null) {
formGroup.addInfolabel(new Label(description.getValueAsString()));
}
@@ -219,7 +223,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
protected FormLabel createAttributeLabel(Attribute attribute) {
String label = attribute.getName();
- MetadataItem labelItem = AssetAttributeMeta.getFirst(attribute, AssetAttributeMeta.LABEL);
+ MetaItem labelItem = AssetMeta.getFirst(attribute, AssetMeta.LABEL);
if (labelItem != null) {
label = labelItem.getValueAsString();
}
@@ -236,7 +240,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
protected IsWidget createEditor(Attribute attribute, FormGroup formGroup) {
IsWidget editor;
S style = container.getStyle();
- MetadataItem defaultValueItem = AssetAttributeMeta.getFirst(attribute, AssetAttributeMeta.DEFAULT);
+ MetaItem defaultValueItem = AssetMeta.getFirst(attribute, AssetMeta.DEFAULT);
Consumer<String> errorConsumer = msg -> {
formGroup.setError(true);
showValidationError(msg);
@@ -247,7 +251,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;
Consumer<String> updateConsumer = isDefaultReadOnly(attribute) ? null : value -> {
formGroup.setError(false);
- attribute.setValue(value);
+ attribute.setValueAsString(value);
};
editor = createStringEditor(style, currentValue, defaultValue, updateConsumer);
} else if (attribute.getType().equals(AttributeType.INTEGER)) {
@@ -255,7 +259,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
Integer defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsInteger() : null;
Consumer<Integer> updateConsumer = isDefaultReadOnly(attribute) ? null : value -> {
formGroup.setError(false);
- attribute.setValue(value);
+ attribute.setValueAsInteger(value);
};
editor = createIntegerEditor(style, currentValue, defaultValue, updateConsumer, errorConsumer);
} else if (attribute.getType().equals(AttributeType.DECIMAL)) {
@@ -263,7 +267,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
Double defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsDecimal() : null;
Consumer<Double> updateConsumer = isDefaultReadOnly(attribute) ? null : value -> {
formGroup.setError(false);
- attribute.setValue(value);
+ attribute.setValueAsDecimal(value);
};
editor = createDecimalEditor(style, currentValue, defaultValue, updateConsumer, errorConsumer);
} else if (attribute.getType().equals(AttributeType.BOOLEAN)) {
@@ -271,7 +275,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
Boolean defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsBoolean() : null;
Consumer<Boolean> updateConsumer = isDefaultReadOnly(attribute) ? null : value -> {
formGroup.setError(false);
- attribute.setValue(value);
+ attribute.setValueAsBoolean(value);
};
editor = createBooleanEditor(style, currentValue, defaultValue, updateConsumer);
} else {
@@ -284,7 +288,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
return editor;
}
- protected IsWidget createEditor(MetadataItem item, JsonType valueType, boolean forceEditable, FormGroup formGroup) {
+ protected IsWidget createEditor(MetaItem item, JsonType valueType, boolean forceEditable, FormGroup formGroup) {
IsWidget editor;
S style = container.getStyle();
@@ -292,8 +296,8 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
formGroup.setError(true);
showValidationError(msg);
};
- // For some metadata items we know if we can edit them or not... custom items are always editable
- Boolean isEditable = AssetAttributeMeta.isEditable(item.getName());
+ // For some meta items we know if we can edit them or not... custom items are always editable
+ Boolean isEditable = AssetMeta.isEditable(item.getName());
// TODO: We should support more JSON types, and have special editors for well-known meta items
// Default to STRING editor if value is empty/no type available
@@ -301,21 +305,21 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
String currentValue = item.getValueAsString();
Consumer<String> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {
formGroup.setError(false);
- item.setValue(value);
+ item.setValueAsString(value);
} : null;
editor = createStringEditor(style, currentValue, null, updateConsumer);
} else if (valueType.equals(JsonType.NUMBER)) {
Double currentValue = item.getValueAsDecimal();
Consumer<Double> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {
formGroup.setError(false);
- item.setValue(value);
+ item.setValueAsDecimal(value);
} : null;
editor = createDecimalEditor(style, currentValue, null, updateConsumer, errorConsumer);
} else if (valueType.equals(JsonType.BOOLEAN)) {
Boolean currentValue = item.getValueAsBoolean();
Consumer<Boolean> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {
formGroup.setError(false);
- item.setValue(value);
+ item.setValueAsBoolean(value);
} : null;
editor = createBooleanEditor(style, currentValue, null, updateConsumer);
} else {
@@ -343,7 +347,11 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
if (updateConsumer != null) {
input.addValueChangeHandler(
event -> {
- updateConsumer.accept(event.getValue());
+ updateConsumer.accept(
+ event.getValue() != null && event.getValue().length() > 0
+ ? event.getValue()
+ : null
+ );
}
);
} else {
@@ -368,7 +376,11 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
if (updateConsumer != null) {
input.addValueChangeHandler(event -> {
try {
- updateConsumer.accept(Integer.valueOf(event.getValue()));
+ updateConsumer.accept(
+ event.getValue() != null && event.getValue().length() > 0
+ ? Integer.valueOf(event.getValue())
+ : null
+ );
} catch (NumberFormatException ex) {
errorConsumer.accept(environment.getMessages().enterOnlyNumbers());
}
@@ -395,7 +407,11 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
if (updateConsumer != null) {
input.addValueChangeHandler(event -> {
try {
- updateConsumer.accept(Double.valueOf(event.getValue()));
+ updateConsumer.accept(
+ event.getValue() != null && event.getValue().length() > 0
+ ? Double.valueOf(event.getValue())
+ : null
+ );
} catch (NumberFormatException ex) {
errorConsumer.accept(environment.getMessages().enterOnlyDecimals());
}
@@ -492,15 +508,15 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
protected void buildItemList() {
itemListPanel.clear();
- if (!attribute.hasMetadata() || attribute.getMetadata().all().length == 0) {
+ if (!attribute.hasMeta() || attribute.getMeta().all().length == 0) {
itemListSectionLabel.setVisible(false);
return;
}
itemListSectionLabel.setVisible(true);
- MetadataItem[] items = attribute.getMetadata().all();
+ MetaItem[] items = attribute.getMeta().all();
for (int i = 0; i < items.length; i++) {
- MetadataItem item = items[i];
+ MetaItem item = items[i];
FormGroup formGroup = new FormGroup();
FormLabel label = new FormLabel(item.getName());
@@ -535,7 +551,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
deleteButton.setIcon("remove");
int index = i;
deleteButton.addClickHandler(clickEvent -> {
- attribute.getMetadata().remove(index);
+ attribute.getMeta().remove(index);
buildItemList();
});
formGroupActions.add(deleteButton);
@@ -549,7 +565,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
protected void buildItemEditor() {
itemEditorPanel.clear();
- MetadataItem item = new MetadataItem();
+ MetaItem item = new MetaItem();
FormListBox valueTypeListBox = new FormListBox();
FormGroup itemNameEditorGroup = createItemNameEditor(item, valueTypeListBox);
@@ -567,11 +583,11 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
itemNameEditorGroup.setError(false);
itemValueEditorGroup.setError(false);
// TODO This is necessary because JSON elemental behavior is weird
- MetadataItem storedItem = new MetadataItem(Json.parse(item.getJsonObject().toJson()));
- if (!attribute.hasMetadata()) {
- attribute.setMetadata(new Metadata());
+ MetaItem storedItem = new MetaItem(Json.parse(item.getJsonObject().toJson()));
+ if (!attribute.hasMeta()) {
+ attribute.setMeta(new Meta());
}
- attribute.getMetadata().add(storedItem);
+ attribute.getMeta().add(storedItem);
buildItemList();
buildItemEditor();
} else {
@@ -584,7 +600,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
itemValueEditorGroup.addFormGroupActions(formGroupActions);
}
- protected FormGroup createItemNameEditor(MetadataItem item, FormListBox typeListBox) {
+ protected FormGroup createItemNameEditor(MetaItem item, FormListBox typeListBox) {
FormGroup formGroup = new FormGroup();
FormLabel label = new FormLabel(environment.getMessages().itemName());
@@ -596,7 +612,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
FormListBox wellknownListBox = new FormListBox();
wellknownListBox.addItem(environment.getMessages().selectStandard());
- for (AssetAttributeMeta wellknown : AssetAttributeMeta.editable()) {
+ for (AssetMeta wellknown : AssetMeta.editable()) {
wellknownListBox.addItem(wellknown.name());
}
formField.add(wellknownListBox);
@@ -612,11 +628,11 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
wellknownListBox.addChangeHandler(event -> {
if (wellknownListBox.getSelectedIndex() > 0) {
- AssetAttributeMeta assetAttributeMeta = AssetAttributeMeta.editable()[wellknownListBox.getSelectedIndex() - 1];
- itemNameInput.setText(assetAttributeMeta.getName());
- item.setName(assetAttributeMeta.getName());
+ AssetMeta assetMeta = AssetMeta.editable()[wellknownListBox.getSelectedIndex() - 1];
+ itemNameInput.setText(assetMeta.getName());
+ item.setName(assetMeta.getName());
typeListBox.setSelectedIndex(
- AssetAttributeMeta.ValueType.byValueType(assetAttributeMeta.getValueType()).ordinal() + 1
+ AssetMeta.ValueType.byValueType(assetMeta.getValueType()).ordinal() + 1
);
} else {
itemNameInput.setText(null);
@@ -629,7 +645,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
return formGroup;
}
- protected FormGroup createItemValueEditor(MetadataItem item, FormListBox typeListBox) {
+ protected FormGroup createItemValueEditor(MetaItem item, FormListBox typeListBox) {
FormGroup formGroup = new FormGroup();
FormLabel label = new FormLabel(environment.getMessages().value());
@@ -640,7 +656,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
formGroup.addFormField(formField);
typeListBox.addItem(environment.getMessages().selectType());
- for (AssetAttributeMeta.ValueType metaValueType : AssetAttributeMeta.ValueType.values()) {
+ for (AssetMeta.ValueType metaValueType : AssetMeta.ValueType.values()) {
typeListBox.addItem(metaValueType.name, metaValueType.name());
}
typeListBox.addChangeHandler(event -> resetItemValueEditor(item, formGroup, formField, typeListBox));
@@ -653,7 +669,7 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
return formGroup;
}
- protected void resetItemValueEditor(MetadataItem item, FormGroup formGroup, FormField formField, FormListBox typeListBox) {
+ protected void resetItemValueEditor(MetaItem item, FormGroup formGroup, FormField formField, FormListBox typeListBox) {
// Remove the last used editor (last widget in form field)
if (formField.getWidgetCount() > 1)
formField.remove(formField.getWidget(formField.getWidgetCount() - 1));
@@ -661,10 +677,10 @@ public class AttributesEditor<S extends AttributesEditor.Style> {
// Create and add new editor, default to empty STRING
item.clearValue();
JsonType valueType = typeListBox.getSelectedIndex() > 0
- ? AssetAttributeMeta.ValueType.valueOf(typeListBox.getSelectedValue()).valueType
+ ? AssetMeta.ValueType.valueOf(typeListBox.getSelectedValue()).valueType
: JsonType.STRING;
if (valueType == JsonType.BOOLEAN) {
- item.setValue(false); // Special case boolean editor, has an "initial" state, there is always a value
+ item.setValueAsBoolean(false); // Special case boolean editor, has an "initial" state, there is always a value
}
IsWidget editor = createEditor(item, valueType, true, formGroup);
formField.add(editor);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentAttributes.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentAttributes.java
index a1cdbaf26..7c30334f9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentAttributes.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentAttributes.java
@@ -63,7 +63,7 @@ public class AgentAttributes extends Attributes {
public AgentAttributes setEnabled(boolean enabled) {
if (hasAttribute("enabled")) {
- get("enabled").setValue(enabled);
+ get("enabled").setValueAsBoolean(enabled);
} else {
put(new Attribute("enabled", AttributeType.BOOLEAN, Json.create(enabled)));
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index f4c83fad9..8e8d19181 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
@@ -27,7 +27,7 @@ import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.manager.server.asset.AssetService;
import org.openremote.manager.server.asset.datapoint.DatapointService;
-import org.openremote.model.AttributeValueChange;
+import org.openremote.model.AttributeState;
import org.openremote.model.asset.*;
import java.util.Collection;
@@ -97,20 +97,20 @@ public class AgentService extends RouteBuilder implements ContainerService {
// Update thing asset when attribute change value messages are published on the sensor topic
from(SENSOR_TOPIC)
- .filter(body().isInstanceOf(AttributeValueChange.class))
+ .filter(body().isInstanceOf(AttributeState.class))
.process(exchange -> {
- AttributeValueChange attributeValueChange =
- exchange.getIn().getBody(AttributeValueChange.class);
+ AttributeState attributeState =
+ exchange.getIn().getBody(AttributeState.class);
// Note that this is a _direct_ update of the attribute value in the database, it will
// not trigger a persistence event - we don't want to redeploy a thing just because an
// attribute value changed!
- boolean success = assetService.updateThingAttributeValue(attributeValueChange);
+ boolean success = assetService.updateThingAttributeValue(attributeState);
// TODO If success then... notify asset listener clients? If not, then handle error?
if (success) {
- LOG.fine("Asset database update successful: " + attributeValueChange);
- datapointService.storeAssetDatapoint(attributeValueChange);
+ LOG.fine("Asset database update successful: " + attributeState);
+ datapointService.storeAssetDatapoint(attributeState);
} else {
- throw new RuntimeException("Asset database update failed for: " + attributeValueChange);
+ throw new RuntimeException("Asset database update failed for: " + attributeState);
}
});
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
index f1768cd21..66c289e1f 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
@@ -35,13 +35,12 @@ import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.asset.SubscribeAssetModified;
import org.openremote.manager.shared.asset.UnsubscribeAssetModified;
import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeValueChange;
+import org.openremote.model.AttributeState;
import org.openremote.model.Function;
import org.openremote.model.asset.*;
import org.postgresql.util.PGobject;
import javax.persistence.EntityManager;
-import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.sql.Array;
import java.sql.PreparedStatement;
@@ -363,17 +362,17 @@ public class AssetService extends RouteBuilder implements ContainerService {
});
}
- public boolean updateThingAttributeValue(AttributeValueChange attributeValueChange) {
+ public boolean updateThingAttributeValue(AttributeState attributeState) {
// TODO: More fine-grained return to distinguish failures ("wrong value type" is not the same as "not found")
- AttributeRef attributeRef = attributeValueChange.getAttributeRef();
+ AttributeRef attributeRef = attributeState.getAttributeRef();
ServerAsset thing = find(attributeRef.getEntityId());
if (thing == null) {
- LOG.fine("Ignoring attribute update for unknown asset: " + attributeValueChange);
+ LOG.fine("Ignoring attribute update for unknown asset: " + attributeState);
return false;
}
if (thing.getWellKnownType() != THING) {
- LOG.fine("Ignoring attribute update '" + attributeValueChange + "' for non-thing asset: " + thing);
+ LOG.fine("Ignoring attribute update '" + attributeState + "' for non-thing asset: " + thing);
return false;
}
ThingAttributes thingAttributes = new ThingAttributes(thing);
@@ -381,16 +380,16 @@ public class AssetService extends RouteBuilder implements ContainerService {
agentLinkResolver, attributeRef.getAttributeName()
);
if (thingAttribute == null) {
- LOG.fine("Ignoring attribute update '" + attributeValueChange + "' for unknown/unlinked attribute: " + thing);
+ LOG.fine("Ignoring attribute update '" + attributeState + "' for unknown/unlinked attribute: " + thing);
return false;
}
- if (thingAttribute.getType().getJsonType() != attributeValueChange.getValue().getType()) {
- LOG.fine("Ignoring attribute update '" + attributeValueChange + "', wrong value type '" + attributeValueChange.getValue().getType() + "': " + thing);
+ if (thingAttribute.getType().getJsonType() != attributeState.getValue().getType()) {
+ LOG.fine("Ignoring attribute update '" + attributeState + "', wrong value type '" + attributeState.getValue().getType() + "': " + thing);
return false;
}
- LOG.fine("Applying '" + attributeValueChange + "' on: " + thing);
- thingAttribute.setValue(attributeValueChange.getValue());
+ LOG.fine("Applying '" + attributeState + "' on: " + thing);
+ thingAttribute.setValue(attributeState.getValue());
return updateAttributeValue(thing.getId(), thingAttribute.getName(), thingAttribute.getValue_TODO_BUG_IN_JAVASCRIPT());
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java
index 6119a16bb..86496cee4 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/datapoint/DatapointService.java
@@ -3,7 +3,7 @@ package org.openremote.manager.server.asset.datapoint;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.persistence.PersistenceService;
-import org.openremote.model.AttributeValueChange;
+import org.openremote.model.AttributeState;
import org.openremote.model.datapoint.AssetDatapoint;
import java.util.logging.Logger;
@@ -30,8 +30,8 @@ public class DatapointService implements ContainerService {
public void stop(Container container) throws Exception {
}
- public void storeAssetDatapoint(AttributeValueChange attributeValueChange) {
- AssetDatapoint assetDatapoint = new AssetDatapoint(attributeValueChange);
+ public void storeAssetDatapoint(AttributeState attributeState) {
+ AssetDatapoint assetDatapoint = new AssetDatapoint(attributeState);
// TODO
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/AbstractContextBrokerResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/AbstractContextBrokerResourceImpl.java
deleted file mode 100644
index 980b7df26..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/AbstractContextBrokerResourceImpl.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.jgroups.util.Tuple;
-import org.openremote.manager.shared.ngsi.*;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Logger;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-public abstract class AbstractContextBrokerResourceImpl implements RegistrationProvider {
- protected static final Logger LOG = Logger.getLogger(AbstractContextBrokerResourceImpl.class.getName());
- public static final int REFRESH_INTERVAL = 180;
- // Key = ENTITY_ID
- // Value = MAP<ATTRIBUTE, PROVIDER>
- protected Map<Tuple<String,String>, Map<Attribute, EntityProvider>> providers = new HashMap<>();
- protected int refreshInterval = REFRESH_INTERVAL;
-
- @Override
- public synchronized boolean registerEntityProvider(String entityType, String entityId, List<Attribute> attributes, EntityProvider provider) {
- LOG.fine("Registering EntityProvider for '" + entityId + "'");
- List<Attribute> regAttributes = new ArrayList<>(attributes);
- Map.Entry<Tuple<String, String>, Map<Attribute, EntityProvider>> providerEntry = providers
- .entrySet()
- .stream()
- .filter(es -> es.getKey().getVal1().equalsIgnoreCase(entityId))
- .findFirst()
- .orElse(null);
- Map<Attribute, EntityProvider> providerInfo = providerEntry != null ? providerEntry.getValue() : null;
-
- if (providerInfo != null) {
- // If any attrs are already registered with another provider then don't proceed
- Stream<EntityProvider> providers = attributes.stream().filter(providerInfo::containsKey).map(providerInfo::get).distinct();
-
- if (providers.count() > 0 && providers.anyMatch(p -> p != provider)) {
- LOG.info("Request failed because one or more attrs already registered with another provider");
- return false;
- }
-
- regAttributes = Stream.concat(regAttributes.stream(), providerInfo.keySet().stream()).collect(Collectors.toList());
- } else {
- providerInfo = new HashMap<>();
- }
-
- // Register all entity attrs with the Context Broker (updates or creates registration)
- updateRegistration(entityType, entityId, regAttributes);
-
- for (Attribute attr : attributes) {
- providerInfo.put(attr, provider);
- }
-
- providers.putIfAbsent(new Tuple<>(entityId, entityType), providerInfo);
- return true;
- }
-
- @Override
- public synchronized void unregisterEntityProvider(EntityProvider provider) {
- providers
- .entrySet()
- .stream()
- .filter(es -> es.getValue().containsValue(provider))
- .forEach(es -> unregisterEntityProvider(es.getKey().getVal1(), es.getKey().getVal2(), provider));
- }
-
- @Override
- public synchronized void unregisterEntityProvider(String entityType, String entityId, EntityProvider provider) {
- Map.Entry<Tuple<String, String>, Map<Attribute, EntityProvider>> providerEntry = providers
- .entrySet()
- .stream()
- .filter(es -> es.getKey().getVal1().equalsIgnoreCase(entityId))
- .findFirst()
- .orElse(null);
- Map<Attribute, EntityProvider> providerInfo = providerEntry != null ? providerEntry.getValue() : null;
-
- if (providerInfo == null) {
- return;
- }
-
- // Split attrs into those to be removed and those to remain
- Map<Boolean, List<Map.Entry<Attribute, EntityProvider>>> splitAttributes = providerInfo.entrySet().stream().collect(Collectors.partitioningBy(es -> es.getValue() == provider));
-
- // Remove obsolete attrs
- splitAttributes.get(true).forEach(es -> providerInfo.remove(es.getKey()));
-
- // Update context provider registration
- List<Attribute> remainingAttributes = splitAttributes.get(false).stream().map(Map.Entry::getKey).collect(Collectors.toList());
- updateRegistration(entityType, entityId, remainingAttributes);
-
- if (remainingAttributes.size() == 0) {
- providers.remove(providerEntry.getKey());
- }
- }
-
- @Override
- public int getRefreshInterval() {
- return refreshInterval;
- }
-
- @Override
- public void setRefreshInterval(int seconds) {
- seconds = Math.max(30, seconds);
- this.refreshInterval = seconds;
- }
-
- protected abstract void updateRegistration(String entityType, String entityId, List<Attribute> attributes);
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV1Resource.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV1Resource.java
deleted file mode 100644
index 068fa34e6..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV1Resource.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.openremote.manager.shared.ngsi.*;
-
-import javax.ws.rs.*;
-
-import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
-
-/**
- * http://fiware-orion.readthedocs.io/en/1.2.1/user/walkthrough_apiv1/index.html#ngsi9-standard-operations
- */
-@Path("v1")
-public interface ContextBrokerV1Resource {
- /*
- * ***************************************
- * NGSI10
- * ***************************************
- */
-
- @POST
- @Path("queryContext")
- @Consumes(APPLICATION_JSON)
- @Produces(APPLICATION_JSON)
- QueryResponseWrapper queryContext(EntityAttributeQuery query);
-
- @POST
- @Path("updateContext")
- @Consumes(APPLICATION_JSON)
- @Produces(APPLICATION_JSON)
- QueryResponseWrapper updateContext(UpdateRequestV1 updateRequest);
-
- /*
- * ***************************************
- * NGSI9
- * ***************************************
- */
-
- @POST
- @Path("registry/registerContext")
- @Consumes(APPLICATION_JSON)
- @Produces(APPLICATION_JSON)
- RegistrationResponseV1 registerContext(RegistrationRequestV1 registration);
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV1ResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV1ResourceImpl.java
deleted file mode 100644
index cf0ccae81..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV1ResourceImpl.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import elemental.json.Json;
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.jgroups.util.Tuple;
-import org.openremote.container.Container;
-import org.openremote.container.web.WebService;
-import org.openremote.manager.shared.ngsi.*;
-import org.openremote.manager.shared.ngsi.ContextEntity;
-
-import javax.ws.rs.*;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.core.UriBuilder;
-import java.net.URI;
-import java.util.*;
-import java.util.logging.Logger;
-import java.util.stream.Collectors;
-
-import static org.openremote.container.web.WebClient.getTarget;
-import static org.openremote.manager.server.ngsi.ContextBrokerV1ResourceImpl.CONTEXT_PROVIDER_V1_ENDPOINT_PATH;
-import static org.openremote.model.Constants.MASTER_REALM;
-
-/**
- * This implementation only needs to support queryContext for resolving context provider requests
- */
-@Path(CONTEXT_PROVIDER_V1_ENDPOINT_PATH)
-public class ContextBrokerV1ResourceImpl extends AbstractContextBrokerResourceImpl implements ContextBrokerV1Resource {
- public static final String CONTEXT_PROVIDER_V1_ENDPOINT_PATH = "ngsi/v1";
- protected static final Logger LOG = Logger.getLogger(ContextBrokerV1ResourceImpl.class.getName());
- protected UriBuilder contextBrokerHostUri;
- protected URI hostUri;
- protected ObjectMapper mapper;
- protected Client httpClient;
- protected RegistrationRequestV1 providerRegistration = new RegistrationRequestV1(new ArrayList<>(), null);
- protected Timer updateTimer;
-
- ContextBrokerV1ResourceImpl(Client httpClient, UriBuilder contextBrokerHostUri) {
- this.httpClient = httpClient;
- this.contextBrokerHostUri = contextBrokerHostUri;
- }
-
- @Override
- public void configure(Container container) throws Exception {
- hostUri = container.getService(WebService.class).getHostUri();
- mapper = container.JSON;
- container.getService(WebService.class).getApiSingletons().add(this);
- }
-
- @Override
- public synchronized void stop() {
- if (updateTimer != null) {
- updateTimer.cancel();
- }
- }
-
- @Override
- public QueryResponseWrapper queryContext(EntityAttributeQuery query) {
- List<QueryResponse> responses = query.getEntities()
- .stream()
- .map(e -> getContextResponse(e, query.getAttributes().stream().map(attr -> new Tuple<String, String>(attr, null)).collect(Collectors.toList()), false))
- .filter(cr -> cr != null)
- .collect(Collectors.toList());
-
- if (responses.size() == 0) {
- return new QueryResponseWrapper(null, new StatusCode("404", "No context element found"));
- } else {
- return new QueryResponseWrapper(responses);
- }
- }
-
- @Override
- public QueryResponseWrapper updateContext(UpdateRequestV1 updateRequest) {
- return null;
- }
-
- @Override
- public RegistrationResponseV1 registerContext(RegistrationRequestV1 registration) {
- return null;
- }
-
- @Override
- public String getRegistrationCallbackUri() {
- return UriBuilder.fromUri(hostUri)
- .path(MASTER_REALM)
- .path(CONTEXT_PROVIDER_V1_ENDPOINT_PATH)
- .build()
- .toString();
- }
-
- public ContextBrokerV1Resource getContextBrokerV1() {
- return getContextBrokerV1(getTarget(httpClient, contextBrokerHostUri.build()));
- }
-
- public ContextBrokerV1Resource getContextBrokerV1(ResteasyWebTarget target) {
- return target.proxy(ContextBrokerV1Resource.class);
- }
-
- protected synchronized QueryResponse getContextResponse(ContextEntity entityQuery, List<Tuple<String,String>> attributesAndValues, boolean isUpdate) {
- Map.Entry<Tuple<String, String>, Map<Attribute, EntityProvider>> providerEntry = providers
- .entrySet()
- .stream()
- .filter(es -> es.getKey().getVal1().equalsIgnoreCase(entityQuery.getId()))
- .findFirst()
- .orElse(null);
- Map<Attribute, EntityProvider> providerInfo = providerEntry != null ? providerEntry.getValue() : null;
- Map<EntityProvider, List<Attribute>> attributeProviders = null;
-
- if (providerInfo != null) {
- if (attributesAndValues == null || attributesAndValues.isEmpty()) {
- // Get all attribute providers for these attrs
- attributeProviders = providerInfo
- .entrySet()
- .stream()
- .collect(Collectors.groupingBy(es -> es.getValue(), Collectors.mapping(es -> es.getKey(), Collectors.toList())));
- } else {
- attributeProviders = attributesAndValues
- .stream()
- .map(attr -> {
- Map.Entry<Attribute, EntityProvider> entry = providerInfo
- .entrySet()
- .stream()
- .filter(es -> es.getKey().getName().equals(attr.getVal1()))
- .findFirst()
- .orElse(null);
- return new Tuple<>(entry.getValue(), entry.getKey());
- })
- .filter(p -> p.getVal1() != null)
- .collect(Collectors.groupingBy(Tuple::getVal1, Collectors.mapping(Tuple::getVal2, Collectors.toList())));
- }
- }
-
- if (attributeProviders == null || attributeProviders.isEmpty()) {
- LOG.info("No EntityProvider found");
- return null;
- }
-
- List<Attribute> attributes;
-
- if (isUpdate) {
- attributes = attributeProviders.entrySet()
- .stream()
- .filter(es -> !es.getValue().isEmpty())
- .flatMap(es -> {
- List<Attribute> attrs = attributesAndValues
- .stream()
- .filter(attrVal ->
- es.getValue()
- .stream()
- .anyMatch(attr -> attr.getName().equalsIgnoreCase(attrVal.getVal1())))
- .map(attrValue -> new Attribute(attrValue.getVal1(), null, Json.create(attrValue.getVal2())))
- .collect(Collectors.toList());
- // Call set attrs on provider
-
- es.getKey().setAttributeValues(entityQuery.getId(), attrs);
- return attrs.stream();
- })
- .collect(Collectors.toList());
- } else {
- attributes = attributeProviders.entrySet()
- .stream()
- .filter(es -> !es.getValue().isEmpty())
- .flatMap(es -> es.getKey().getAttributeValues(entityQuery.getId(), es.getValue().stream().map(Attribute::getName).collect(Collectors.toList())).stream())
- .collect(Collectors.toList());
- }
-
- if (attributes.isEmpty()) {
- LOG.info("EntityProvider returned no attrs when asked for the value of one or more attrs");
- return null;
- }
-
- return new QueryResponse(
- new ContextElement(entityQuery.getType(),entityQuery.getId(), false, attributes),
- new StatusCode("200", "OK"));
- }
-
- @Override
- protected synchronized void updateRegistration(String entityType, String entityId, List<Attribute> attributes) {
- // Check if this entity ID is already registered
- EntityAttributeListV1 existingReg = providerRegistration.getRegistrations()
- .stream()
- .filter(reg ->
- reg.getEntities()
- .stream()
- .anyMatch(e -> e.getId().equalsIgnoreCase(entityId)))
- .findFirst()
- .orElse(null);
-
- if (existingReg != null) {
- ContextEntity entity = existingReg.getEntities()
- .stream()
- .filter(e -> e.getId().equalsIgnoreCase(entityId))
- .findFirst()
- .orElse(null);
-
- if (attributes.isEmpty()) {
- // Just remove this entity from the registration
- existingReg.getEntities().remove(entity);
- } else {
- // Check if attrs all match if so there is nothing to do otherwise
- // We have to remove from this registration and either add to another
- // or create a new one to match these attrs
- boolean allMatch = attributes
- .stream()
- .allMatch(attr -> existingReg.getAttributes()
- .stream()
- .anyMatch(regAttr ->
- regAttr.getName().equalsIgnoreCase(attr.getName()) &&
- regAttr.getType().equalsIgnoreCase(attr.getType().getName())));
-
- if (allMatch) {
- // Nothing to do here
- return;
- }
-
- existingReg.getEntities().remove(entity);
- }
-
- // Check there is at least one entity in the reg otherwise remove it
- if (existingReg.getEntities().isEmpty()) {
- providerRegistration.getRegistrations().remove(existingReg);
- }
- }
-
- if (!attributes.isEmpty()) {
- EntityAttributeListV1 newReg = providerRegistration.getRegistrations()
- .stream()
- .filter(reg ->
- attributes
- .stream()
- .allMatch(attr -> reg.getAttributes()
- .stream()
- .anyMatch(regAttr ->
- regAttr.getName().equalsIgnoreCase(attr.getName()) &&
- regAttr.getType().equalsIgnoreCase(attr.getType().getName()))))
- .findFirst()
- .orElse(null);
-
- ContextEntity entity = new ContextEntity(entityType, entityId, false);
-
- if (newReg != null) {
- newReg.getEntities().add(entity);
- } else {
- List<ContextEntity> entities = new ArrayList<>();
- List<ContextAttribute> attrs = new ArrayList<>();
- entities.add(entity);
- attributes.forEach(attr -> attrs.add(new ContextAttribute(attr.getName(), attr.getType().getName(), false)));
- newReg = new EntityAttributeListV1(entities, attrs, getRegistrationCallbackUri());
- providerRegistration.getRegistrations().add(newReg);
- }
- }
-
- // NOTE: There is no documented way to remove a registration just have to set it to expire now
- // but it lingers in the DB but it does mean we can reuse it at a later stage
- String duration = providerRegistration.getRegistrations().isEmpty() ? "PT0S" : "PT" + getRefreshInterval() + "S";
- providerRegistration.setDuration(duration);
-
-// try {
-// String str = mapper.writeValueAsString(providerRegistration);
-// System.out.print(str);
-// } catch (JsonProcessingException e) {
-// e.printStackTrace();
-// }
-
- refreshRegistration();
- }
-
- private synchronized void refreshRegistration() {
- // If registration is set to 0s then we need to provide a dummy entity - WTF?
- RegistrationRequestV1 reg = providerRegistration;
-
- if (reg.getDuration().equalsIgnoreCase("PT0S")) {
- reg = new RegistrationRequestV1(new ArrayList<>(), reg.getDuration(), reg.getRegistrationId());
- List<ContextEntity> dummyEntities = new ArrayList<>();
- dummyEntities.add(new ContextEntity("##############","##############", false));
- reg.getRegistrations().add(new EntityAttributeListV1(dummyEntities, null, getRegistrationCallbackUri()));
- }
-
- RegistrationResponseV1 response = getContextBrokerV1().registerContext(reg);
- boolean success = false;
-
- if (response == null) {
- LOG.severe("Context Broker context registration returned null");
- } else if (response.getErrorCode() != null) {
- LOG.severe("Context registration error: " + response.getErrorCode().getCode() + " (" + response.getErrorCode().getMessage() + ")");
- } else {
- // Store the reg ID for later reuse
- providerRegistration.setRegistrationId(response.getRegistrationId());
- success = true;
- }
-
- if (updateTimer != null) {
- updateTimer.cancel();
- }
-
- if (!providerRegistration.getRegistrations().isEmpty()) {
- updateTimer = new Timer();
- // TODO: Handle the reg update failure more gracefully
- int period = success ? (getRefreshInterval()-10)*1000 : 20000;
- updateTimer.scheduleAtFixedRate(new TimerTask() {
- @Override
- public void run() {
- refreshRegistration();
- }
- }, period, period);
- }
- }
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV2Resource.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV2Resource.java
deleted file mode 100644
index 89bf2619f..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV2Resource.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.openremote.manager.shared.http.PATCH;
-import org.openremote.manager.shared.http.SuccessStatusCode;
-import org.openremote.manager.shared.ngsi.*;
-import org.openremote.manager.shared.ngsi.params.EntityListParams;
-import org.openremote.manager.shared.ngsi.params.EntityParams;
-import org.openremote.manager.shared.ngsi.params.SubscriptionParams;
-
-import javax.ws.rs.*;
-import javax.ws.rs.core.Response;
-
-import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
-
-/**
- * http://telefonicaid.github.io/fiware-orion/api/v2/stable/
- */
-@Path("v2")
-public interface ContextBrokerV2Resource {
- /*
- * ***************************************
- * NGSI10
- * ***************************************
- */
-
- @GET
- @Produces(APPLICATION_JSON)
- EntryPoint getEntryPoint();
-
- @GET
- @Path("entities")
- @Produces(APPLICATION_JSON)
- Entity[] getEntities(@BeanParam EntityListParams entityListParams);
-
- @POST
- @Path("entities")
- @Consumes(APPLICATION_JSON)
- Response postEntity(Entity entity);
-
- @GET
- @Path("entities/{entityId}")
- @Produces(APPLICATION_JSON)
- Entity getEntity(@PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
-
- @DELETE
- @Path("entities/{entityId}")
- Response deleteEntity(@PathParam("entityId") String entityId);
-
- @PUT
- @Path("entities/{entityId}/attrs")
- @Consumes(APPLICATION_JSON)
- Response putEntityAttributes(@PathParam("entityId") String entityId, Entity entity);
-
- @PATCH
- @Path("entities/{entityId}/attrs")
- @Consumes(APPLICATION_JSON)
- Response patchEntityAttributes(@PathParam("entityId") String entityId, Entity entity);
-
- @GET
- @Path("subscriptions")
- @Produces(APPLICATION_JSON)
- SubscribeRequestV2[] getSubscriptions();
-
- @GET
- @Path("subscriptions/{subscriptionId}")
- @Produces(APPLICATION_JSON)
- SubscribeRequestV2 getSubscription(@PathParam("subscriptionId")String subscriptionId);
-
- @POST
- @Path("subscriptions")
- @Consumes(APPLICATION_JSON)
- Response createSubscription(SubscribeRequestV2 subscription);
-
- @PATCH
- @Path("subscriptions/{subscriptionId}")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(204)
- Response updateSubscription(@PathParam("subscriptionId")String subscriptionId, SubscribeRequestV2 subscription);
-
- @DELETE
- @Path("subscriptions/{subscriptionId}")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(204)
- Response deleteSubscription(@PathParam("subscriptionId")String subscriptionId);
-
- /*
- * ***************************************
- * NGSI9
- * ***************************************
- */
-
- @POST
- @Path("registrations")
- @Consumes(APPLICATION_JSON)
- Response createRegistration(RegistrationRequestV2 registration);
-
- @PATCH
- @Path("registrations/{registrationId}")
- @Consumes(APPLICATION_JSON)
- Response updateRegistration(@PathParam("registrationId") String registrationId, Duration duration);
-
- @DELETE
- @Path("registrations/{registrationId}")
- Response deleteRegistration(@PathParam("registrationId") String registrationId);
-
- @POST
- @Path("op/registerSubscriber")
- @Consumes(APPLICATION_JSON)
- Response batchRegistration(BatchRegistrationRequestV2 registrations);
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV2ResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV2ResourceImpl.java
deleted file mode 100644
index c151841d9..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/ContextBrokerV2ResourceImpl.java
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.jgroups.util.Tuple;
-import org.openremote.container.Container;
-import org.openremote.container.web.WebService;
-import org.openremote.manager.shared.ngsi.*;
-import org.openremote.manager.shared.ngsi.params.EntityListParams;
-import org.openremote.manager.shared.ngsi.params.EntityParams;
-
-import javax.ws.rs.BeanParam;
-import javax.ws.rs.NotSupportedException;
-import javax.ws.rs.Path;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import java.net.URI;
-import java.util.*;
-import java.util.logging.Logger;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.Stream;
-
-import static org.openremote.container.web.WebClient.getTarget;
-import static org.openremote.manager.server.ngsi.ContextBrokerV2ResourceImpl.CONTEXT_PROVIDER_V2_ENDPOINT_PATH;
-import static org.openremote.model.Constants.MASTER_REALM;
-
-/**
- * This implementation only needs to support queryContext for resolving context provider requests
- */
-@Path(CONTEXT_PROVIDER_V2_ENDPOINT_PATH)
-public class ContextBrokerV2ResourceImpl extends AbstractContextBrokerResourceImpl implements ContextBrokerV2Resource {
- public static final String CONTEXT_PROVIDER_V2_ENDPOINT_PATH = "ngsi/v2";
- protected static final Logger LOG = Logger.getLogger(ContextBrokerV2ResourceImpl.class.getName());
- protected UriBuilder contextBrokerHostUri;
- protected URI hostUri;
- protected ObjectMapper mapper;
- protected Client httpClient;
- protected Timer updateTimer;
- protected BatchRegistrationRequestV2 providerRegistration;
-
- ContextBrokerV2ResourceImpl(Client httpClient, UriBuilder contextBrokerHostUri) {
- this.httpClient = httpClient;
- this.contextBrokerHostUri = contextBrokerHostUri;
- }
-
- @Override
- public void configure(Container container) throws Exception {
- hostUri = container.getService(WebService.class).getHostUri();
- mapper = container.JSON;
- container.getService(WebService.class).getApiSingletons().add(this);
- }
-
- @Override
- public void stop() {
- if (updateTimer != null) {
- updateTimer.cancel();
- }
- }
-
- @Override
- public Entity[] getEntities(@BeanParam EntityListParams entityListParams) {
- String[] matchedIds = resolveIds(entityListParams);
- EntityParams params = new EntityParams();
- params.attributes(entityListParams.attributes);
- return Arrays
- .stream(matchedIds)
- .map(id -> getEntity(id, params))
- .filter(e -> e != null)
- .toArray(size -> new Entity[size]);
- }
-
- @Override
- public Entity getEntity(String entityId, @BeanParam EntityParams entityParams) {
- return getEntityResponse(entityId, Arrays.asList(entityParams.attributes));
- }
-
- /*
- *
- * BELOW METHODS ARE NOT IMPLEMENTED AS THEY SHOULD NEVER BE NEEDED FOR CONTEXT PROVIDER
- *
- */
-
- @Override
- public EntryPoint getEntryPoint() {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response postEntity(Entity entity) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response deleteEntity(String entityId) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response putEntityAttributes(String entityId, Entity entity) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response patchEntityAttributes(String entityId, Entity entity) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public SubscribeRequestV2[] getSubscriptions() {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response createSubscription(SubscribeRequestV2 subscription) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response updateSubscription(String subscriptionId, SubscribeRequestV2 subscription) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response deleteSubscription(String subscriptionId) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response createRegistration(RegistrationRequestV2 registration) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public SubscribeRequestV2 getSubscription(String subscriptionId) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response updateRegistration(String registrationId, Duration duration) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response deleteRegistration(String registrationId) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public Response batchRegistration(BatchRegistrationRequestV2 registrations) {
- throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
- }
-
- @Override
- public String getRegistrationCallbackUri() {
- return UriBuilder.fromUri(hostUri)
- .path(MASTER_REALM)
- .path(CONTEXT_PROVIDER_V2_ENDPOINT_PATH)
- .build()
- .toString();
- }
-
- public ContextBrokerV2Resource getContextBroker() {
- return getContextBroker(getTarget(httpClient, contextBrokerHostUri.build()));
- }
-
- public ContextBrokerV2Resource getContextBroker(ResteasyWebTarget target) {
- return target.proxy(ContextBrokerV2Resource.class);
- }
-
- protected synchronized String[] resolveIds(EntityListParams entityListParams) {
- // TODO: Add support for non entity ID/type based queries
- Stream<Map.Entry<Tuple<String, String>, Map<Attribute, EntityProvider>>> filteredProviders = providers
- .entrySet()
- .stream();
-
- if (entityListParams.id != null && entityListParams.id.length > 0) {
- // Filter by ID (exact)
- filteredProviders
- .filter(
- es -> Arrays
- .stream(entityListParams.id)
- .anyMatch(id -> id.equalsIgnoreCase(es.getKey().getVal1())));
- } else if (entityListParams.idPattern != null) {
- // Filter by ID (regex)
- Pattern idRegex = Pattern.compile(entityListParams.idPattern);
- filteredProviders = filteredProviders
- .filter(
- es -> idRegex.matcher(es.getKey().getVal1()).matches()
- );
- }
-
- if (entityListParams.type != null && entityListParams.type.length > 0) {
- // Further filter by type (exact)
- filteredProviders = filteredProviders
- .filter(
- es -> Arrays
- .stream(entityListParams.type)
- .anyMatch(type -> type.equalsIgnoreCase(es.getKey().getVal2())));
- } else if (entityListParams.typePattern != null) {
- // Further filter by type (regex)
- Pattern typeRegex = Pattern.compile(entityListParams.typePattern);
- filteredProviders = filteredProviders.filter(
- es -> typeRegex.matcher(es.getKey().getVal2()).matches()
- );
- }
-
- return filteredProviders.map(es -> es.getKey().getVal1()).toArray(size -> new String[size]);
- }
-
- protected synchronized Entity getEntityResponse(String entityId, List<String> attributeNames) {
- Map<EntityProvider, List<String>> attributeProviders = null;
-
- Map.Entry<Tuple<String, String>, Map<Attribute, EntityProvider>> providerEntry = providers
- .entrySet()
- .stream()
- .filter(es -> es.getKey().getVal1().equalsIgnoreCase(entityId))
- .findFirst()
- .orElse(null);
-
- if (providerEntry != null) {
- if (attributeNames == null || attributeNames.isEmpty()) {
- // Get all attribute providers
- attributeProviders = providerEntry
- .getValue()
- .entrySet()
- .stream()
- .collect(Collectors.groupingBy(es -> es.getValue(), Collectors.mapping(es -> es.getKey().getName(), Collectors.toList())));
- } else {
- attributeProviders = attributeNames
- .stream()
- .map(attr -> {
- Map.Entry<Attribute, EntityProvider> entry = providerEntry
- .getValue()
- .entrySet()
- .stream()
- .filter(es -> es.getKey().getName().equals(attr))
- .findFirst()
- .orElse(null);
- return new Tuple<>(entry.getValue(), attr);
- })
- .filter(p -> p.getVal1() != null)
- .collect(Collectors.groupingBy(Tuple::getVal1, Collectors.mapping(Tuple::getVal2, Collectors.toList())));
- }
- }
-
- if (attributeProviders == null || attributeProviders.isEmpty()) {
- LOG.info("No entity providers found");
- return null;
- }
-
- List<Attribute> attributes = attributeProviders.entrySet()
- .stream()
- .filter(es -> !es.getValue().isEmpty())
- .flatMap(es -> es.getKey().getAttributeValues(entityId, es.getValue()).stream())
- .collect(Collectors.toList());
-
- if (attributes.isEmpty()) {
- LOG.info("EntityProvider returned no attrs when asked for the value of one or more attrs");
- return null;
- }
-
- // Construct the entity object
- Entity entity = new Entity();
- entity.setType(providerEntry.getKey().getVal2());
- entity.setId(providerEntry.getKey().getVal1());
- attributes.forEach(entity::addAttribute);
-
- return entity;
- }
-
- @Override
- // TODO: Update registration code once NGSI9 v2 is finalised
- protected synchronized void updateRegistration(String entityType, String entityId, List<Attribute> attributes) {
- // Check if this entity ID is already registered
- RegistrationRequestV2 existingReg = providerRegistration.getRegistrations()
- .stream()
- .filter(reg ->
- reg.getSubject().getEntities()
- .stream()
- .anyMatch(e -> e.getId().equalsIgnoreCase(entityId)))
- .findFirst()
- .orElse(null);
-
- if (existingReg != null) {
- ContextEntity entity = existingReg.getSubject().getEntities()
- .stream()
- .filter(e -> e.getId().equalsIgnoreCase(entityId))
- .findFirst()
- .orElse(null);
-
- if (attributes.isEmpty()) {
- // Just remove this entity from the registration
- existingReg.getSubject().getEntities().remove(entity);
- } else {
- // Check if attrs all match if so there is nothing to do otherwise
- // We have to remove from this registration and either add to another
- // or create a new one to match these attrs
- boolean allMatch = attributes
- .stream()
- .allMatch(attr -> existingReg.getSubject().getAttributes()
- .stream()
- .anyMatch(regAttr ->
- regAttr.getName().equalsIgnoreCase(attr.getName())));
-
- if (allMatch) {
- // Nothing to do here
- return;
- }
-
- existingReg.getSubject().getEntities().remove(entity);
- }
-
- // Check there is at least one entity in the reg otherwise remove it
- if (existingReg.getSubject().getEntities().isEmpty()) {
- providerRegistration.getRegistrations().remove(existingReg);
- }
- }
-
- RegistrationRequestV2 newReg = providerRegistration.getRegistrations()
- .stream()
- .filter(reg ->
- attributes
- .stream()
- .allMatch(attr -> reg.getSubject().getAttributes()
- .stream()
- .anyMatch(regAttr ->
- regAttr.getName().equalsIgnoreCase(attr.getName()))))
- .findFirst()
- .orElse(null);
-
- ContextEntity entity = new ContextEntity(entityType, entityId, false);
-
- if (newReg != null) {
- newReg.getSubject().getEntities().add(entity);
- } else {
- List<ContextEntity> entities = new ArrayList<>();
- List<ContextAttribute> attrs = new ArrayList<>();
- entities.add(entity);
- attributes.forEach(attr -> attrs.add(new ContextAttribute(attr.getName())));
- EntityAttributeListV2 subject = new EntityAttributeListV2(entities,attrs);
- newReg = new RegistrationRequestV2(subject, getRegistrationCallbackUri(), null, null);
- newReg.setDuration("PT" + getRefreshInterval() + "S");
- providerRegistration.getRegistrations().add(newReg);
- }
-
- if (providerRegistration.getRegistrations().isEmpty()) {
- // Remove the entire registration
- providerRegistration.setActionType(ActionType.DELETE);
- } else {
- // Is this an update or create - docs not clear at this time
- providerRegistration.setActionType(ActionType.UPDATE);
- }
-
- try {
- String str = mapper.writeValueAsString(providerRegistration);
- System.out.print(str);
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
-
- refreshRegistration();
- }
-
- // TODO: Update registration code once NGSI9 v2 is finalised
- private synchronized void refreshRegistration() {
- Response response = getContextBroker().batchRegistration(providerRegistration);
- boolean success = false;
-
- if (response == null) {
- LOG.severe("Context Broker context registration returned null");
- } else if (response.getStatus() != 200) {
- LOG.severe("Context registration error: " + response.getStatus() + " (" + response.getEntity() + ")");
- } else {
- // Store the reg IDs for later reuse
- String[] ids = (String[])response.getEntity();
- IntStream.range(0, ids.length)
- .forEach(index -> providerRegistration.getRegistrations().get(index).setRegistrationId(ids[index]));
- success = true;
- }
-
- if (updateTimer != null) {
- updateTimer.cancel();
- }
-
- if (!providerRegistration.getRegistrations().isEmpty()) {
- updateTimer = new Timer();
- // TODO: Handle the reg update failure more gracefully
- int period = success ? (getRefreshInterval()-10)*1000 : 20000;
- updateTimer.scheduleAtFixedRate(new TimerTask() {
- @Override
- public void run() {
- refreshRegistration();
- }
- }, period, period);
- }
- }
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityArrayMessageBodyConverter.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityArrayMessageBodyConverter.java
deleted file mode 100644
index ebe2c635c..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityArrayMessageBodyConverter.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import elemental.json.Json;
-import elemental.json.JsonArray;
-import elemental.json.JsonObject;
-import elemental.json.impl.JsonUtil;
-import org.jboss.resteasy.plugins.providers.ProviderHelper;
-import org.openremote.manager.shared.ngsi.AbstractEntity;
-import org.openremote.manager.shared.ngsi.Entity;
-import org.openremote.manager.shared.ngsi.KeyValueEntity;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Logger;
-
-@Provider
-public class EntityArrayMessageBodyConverter
- implements MessageBodyReader<AbstractEntity[]>, MessageBodyWriter<AbstractEntity[]> {
-
- private static final Logger LOG = Logger.getLogger(EntityArrayMessageBodyConverter.class.getName());
-
- @Override
- public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return AbstractEntity[].class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);
- }
-
- @Override
- public AbstractEntity[] readFrom(Class<AbstractEntity[]> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
- String str = ProviderHelper.readString(entityStream, mediaType);
- JsonArray jsonArray = JsonUtil.parse(str);
- if (type.equals(Entity[].class)) {
- List<Entity> list = new ArrayList<>();
- for (int i = 0; i < jsonArray.length(); i++) {
- JsonObject jsonObject = jsonArray.get(i);
- list.add(new Entity(jsonObject));
- }
- return list.toArray(new Entity[list.size()]);
- } else if (type.equals(KeyValueEntity[].class)) {
- List<KeyValueEntity> list = new ArrayList<>();
- for (int i = 0; i < jsonArray.length(); i++) {
- JsonObject jsonObject = jsonArray.get(i);
- list.add(new KeyValueEntity(jsonObject));
- }
- return list.toArray(new KeyValueEntity[list.size()]);
- } else {
- throw new IOException("Unsupported type: " + type);
- }
- }
-
- @Override
- public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return AbstractEntity[].class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);
- }
-
- @Override
- public long getSize(AbstractEntity[] value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(AbstractEntity[] value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
- JsonArray jsonArray = Json.createArray();
- for (int i = 0; i < value.length; i++) {
- JsonObject jsonObject = value[i].getJsonObject();
- jsonArray.set(i, jsonObject);
- }
- String str = jsonArray.toJson();
- String charset = mediaType.getParameters().get("charset");
- if (charset == null) entityStream.write(str.getBytes("UTF-8"));
- else entityStream.write(str.getBytes(charset));
- }
-}
\ No newline at end of file
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityMessageBodyConverter.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityMessageBodyConverter.java
deleted file mode 100644
index d992a4f33..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityMessageBodyConverter.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import elemental.json.Json;
-import elemental.json.JsonObject;
-import org.jboss.resteasy.plugins.providers.ProviderHelper;
-import org.openremote.manager.shared.ngsi.AbstractEntity;
-import org.openremote.manager.shared.ngsi.Entity;
-import org.openremote.manager.shared.ngsi.KeyValueEntity;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import java.util.logging.Logger;
-
-@Provider
-public class EntityMessageBodyConverter
- implements MessageBodyReader<AbstractEntity>, MessageBodyWriter<AbstractEntity> {
-
- private static final Logger LOG = Logger.getLogger(EntityMessageBodyConverter.class.getName());
-
- @Override
- public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return AbstractEntity.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);
- }
-
- @Override
- public AbstractEntity readFrom(Class<AbstractEntity> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
- String str = ProviderHelper.readString(entityStream, mediaType);
- JsonObject jsonObject = Json.parse(str);
- if (type.equals(Entity.class)) {
- return new Entity(jsonObject);
- } else if (type.equals(KeyValueEntity.class)) {
- return new KeyValueEntity(jsonObject);
- } else {
- throw new IOException("Unsupported type: " + type);
- }
- }
-
- @Override
- public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return AbstractEntity.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);
- }
-
- @Override
- public long getSize(AbstractEntity value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(AbstractEntity value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
- String str = value.getJsonObject().toJson();
- String charset = mediaType.getParameters().get("charset");
- if (charset == null) entityStream.write(str.getBytes("UTF-8"));
- else entityStream.write(str.getBytes(charset));
- }
-}
\ No newline at end of file
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityProvider.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityProvider.java
deleted file mode 100644
index 10163001f..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityProvider.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.openremote.manager.shared.ngsi.Attribute;
-
-import java.util.List;
-
-public interface EntityProvider {
-
- List<Attribute> getAttributeValues(String entityId, List<String> attributes);
-
- boolean setAttributeValues(String entityId, List<Attribute> attributes);
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityResourceImpl.java
deleted file mode 100644
index 20939ac0e..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityResourceImpl.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import elemental.json.Json;
-import elemental.json.JsonObject;
-import org.openremote.container.Container;
-import org.openremote.container.util.IdentifierUtil;
-import org.openremote.container.web.WebResource;
-import org.openremote.container.web.WebService;
-import org.openremote.model.Consumer;
-import org.openremote.manager.shared.http.RequestParams;
-import org.openremote.manager.shared.ngsi.*;
-import org.openremote.manager.shared.ngsi.params.*;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import java.net.URI;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-import static org.openremote.model.Constants.MASTER_REALM;
-
-
-public class EntityResourceImpl extends WebResource implements EntityResource, SubscriptionProvider {
-
- public static final String SUBSCRIBER_ENDPOINT_PATH = "entity/subscriber";
- public static final int SUBSCRIPTION_REFRESH_INTERVAL = 180;
-
- protected URI hostUri;
- protected ObjectMapper mapper;
- protected final Map<Consumer<Entity[]>, SubscribeRequestV2> subscribers = new HashMap<>();
- protected final Calendar calendar = Calendar.getInstance();
- protected int refreshInterval = SUBSCRIPTION_REFRESH_INTERVAL;
- protected final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
- protected final Map<SubscribeRequestV2, ScheduledFuture<?>> refreshTasks = new HashMap<>();
- protected final EntityService entityService;
-
- public EntityResourceImpl(EntityService entityService) {
- this.entityService = entityService;
- }
-
- public void configure(Container container) {
- hostUri = container.getService(WebService.class).getHostUri();
- mapper = container.JSON;
- }
-
- @Override
- public synchronized void stop() {
- // Cancel all scheduled subscriber refreshes
- refreshTasks.entrySet()
- .stream()
- .forEach(es -> es.getValue().cancel(true));
- }
-
- @Override
- public Entity[] getEntities(RequestParams requestParams, EntityListParams entityListParams) {
- return entityService.getContextBroker().getEntities(entityListParams);
- }
-
- @Override
- public void postEntity(RequestParams requestParams, Entity entity) {
- if (entity.getId() == null) {
- entity.setId(IdentifierUtil.generateGlobalUniqueId());
- }
- checkSuccessResponse(entityService.getContextBroker().postEntity(entity));
- }
-
- @Override
- public Entity getEntity(RequestParams requestParams, String entityId, EntityParams entityParams) {
- return entityService.getContextBroker().getEntity(entityId, entityParams);
- }
-
- @Override
- public void deleteEntity(RequestParams requestParams, String entityId) {
- checkSuccessResponse(entityService.getContextBroker().deleteEntity(entityId));
- }
-
- @Override
- public void putEntityAttributes(RequestParams requestParams, String entityId, Entity entity) {
- entity = new Entity(fixForUpdate(entity.getJsonObject()));
- checkSuccessResponse(entityService.getContextBroker().putEntityAttributes(entityId, entity));
- }
-
- @Override
- public void patchEntityAttributes(RequestParams requestParams, String entityId, Entity entity) {
- entity = new Entity(fixForUpdate(entity.getJsonObject()));
- checkSuccessResponse(entityService.getContextBroker().patchEntityAttributes(entityId, entity));
- }
-
- @Override
- public synchronized void subscriberCallback(NotificationFormat format, JsonObject notification) {
- // We get here when Orion detects a change to a currently subscribed entity
- // TODO: Notify the listeners interested in this entity
- switch(format) {
- case NORMALIZED:
- Entity[] entities = Entity.from(notification.getArray("data"));
- String id = notification.getString("subscriptionId");
- Map.Entry<Consumer<Entity[]>, SubscribeRequestV2> subscriber = subscribers.entrySet()
- .stream()
- .filter(es -> es.getValue().getId().equals(id))
- .findFirst()
- .orElse(null);
-
- if (subscriber != null) {
- subscriber.getKey().accept(entities);
- }
-
- break;
- case KEYVALUES:
- // TODO: Implement KeyValue Notification Support
- KeyValueEntity[] entities2 = KeyValueEntity.from(notification.getArray("data"));
- throw new RuntimeException("Unsupported notification format");
- case VALUES:
- // TODO: Implement Value Notification Support
- throw new RuntimeException("Unsupported notification format");
- default:
- throw new RuntimeException("Unsupported notification format");
- }
- }
-
- @Override
- public int getRefreshInterval() {
- return refreshInterval;
- }
-
- @Override
- public void setRefreshInterval(int seconds) {
- seconds = Math.max(30, seconds);
- this.refreshInterval = seconds;
- }
-
- protected Response checkSuccessResponse(Response response) {
- if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL)
- return response;
- throw new WebApplicationException(
- "Failure response from context broker: " + response.getStatusInfo(), response.getStatus()
- );
- }
-
- /**
- * You must strip out id and type attrs of an entity if it's a PATCH or POST.
- * Why doesn't the NGSI server just ignore those fields? FU, that's why.
- */
- protected JsonObject fixForUpdate(JsonObject original) {
- JsonObject copy = Json.parse(original.toJson());
- if (copy.hasKey("id"))
- copy.remove("id");
- if (copy.hasKey("type"))
- copy.remove("type");
- return copy;
- }
-
- @Override
- public synchronized boolean registerSubscriber(Consumer<Entity[]> listener, SubscriptionParams subscription) {
- // Find existing subscription for this listener (if it exists)
- SubscribeRequestV2 storedSubscription = subscribers.get(listener);
-
- if (storedSubscription != null) {
- String id = storedSubscription.getId();
- storedSubscription.setSubject(subscription);
- // TODO: Handle failed subscription update
- int response = refreshSubscription(storedSubscription, ActionType.UPDATE);
- return response == 204;
- }
-
- // Create a new subscription
- storedSubscription = new SubscribeRequestV2();
- storedSubscription.setNotification(createNotificationParams());
- storedSubscription.setSubject(subscription);
-
-// try {
-// String str = mapper.writeValueAsString(storedSubscription);
-// System.out.print(str);
-// } catch (JsonProcessingException e) {
-// e.printStackTrace();
-// }
-
- int response = refreshSubscription(storedSubscription, ActionType.CREATE);
-
- if (response == 201) {
- subscribers.put(listener, storedSubscription);
- return true;
- }
-
- return false;
- }
-
- @Override
- public synchronized SubscriptionParams getSubscription(Consumer<Entity[]> listener) {
- SubscribeRequestV2 subscriber = subscribers.get(listener);
- return subscriber != null ? subscriber.getSubject() : null;
- }
-
- @Override
- public synchronized void unregisterSubscriber(Consumer<Entity[]> listener) {
- SubscribeRequestV2 subscriber = subscribers.get(listener);
-
- if (subscriber != null) {
- int response = refreshSubscription(subscriber, ActionType.DELETE);
- if (response == 204) {
- subscribers.remove(subscriber);
- }
- }
- }
-
- @Override
- public String getSubscriptionCallbackUri() {
- return UriBuilder.fromUri(hostUri)
- .path(MASTER_REALM)
- .path(SUBSCRIBER_ENDPOINT_PATH)
- .build()
- .toString();
- }
-
- protected synchronized int refreshSubscription(SubscribeRequestV2 subscriber, ActionType action) {
- Response response = null;
-
- switch(action) {
- case CREATE:
- subscriber.setExpires(createNewExpiryDate());
- response = entityService.getContextBroker().createSubscription(subscriber);
- if (response.getStatus() == 201) {
- String locationHeader = response.getHeaderString("Location");
- String id = locationHeader.split("/")[3];
- subscriber.setId(id);
- }
- break;
- case UPDATE:
- // Cancel any existing refresh task
- ScheduledFuture<?> task = refreshTasks.get(subscriber);
- if (task != null) {
- task.cancel(true);
- refreshTasks.remove(task);
- }
- subscriber.setExpires(createNewExpiryDate());
- response = entityService.getContextBroker().updateSubscription(subscriber.getId(), subscriber);
- break;
- case DELETE:
- response = entityService.getContextBroker().deleteSubscription(subscriber.getId());
- break;
- }
-
- if (action == ActionType.CREATE || action == ActionType.UPDATE) {
- // Add scheduled task to refresh this subscription
- refreshTasks.put(subscriber, scheduler.schedule(new Runnable() {
- @Override
- public void run() {
- refreshSubscription(subscriber, ActionType.UPDATE);
- }
- }, getRefreshInterval()-10, TimeUnit.SECONDS));
- }
-
- return response != null ? response.getStatus() : 500;
- }
-
- protected Date createNewExpiryDate() {
- calendar.setTime(new Date());
- calendar.add(Calendar.SECOND, getRefreshInterval());
- return calendar.getTime();
- }
-
- protected NotificationParams createNotificationParams() {
- NotificationParams params = new NotificationParams();
- params.setHttp(new HttpParams(getSubscriptionCallbackUri()));
- return params;
- }
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityService.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityService.java
deleted file mode 100644
index 04838e5eb..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntityService.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.openremote.container.Container;
-import org.openremote.container.ContainerService;
-import org.openremote.container.observable.RetryWithDelay;
-import org.openremote.container.web.WebClient;
-import org.openremote.container.web.WebService;
-import org.openremote.model.Consumer;
-import org.openremote.manager.shared.ngsi.Attribute;
-import org.openremote.manager.shared.ngsi.Entity;
-import org.openremote.manager.shared.ngsi.EntryPoint;
-import org.openremote.manager.shared.ngsi.params.SubscriptionParams;
-import rx.Observable;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.core.UriBuilder;
-import java.net.URI;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Logger;
-
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
-import static org.openremote.container.web.WebClient.getTarget;
-
-public class EntityService implements ContainerService {
-
- private static final Logger LOG = Logger.getLogger(EntityService.class.getName());
-
- public static final String CONTEXTBROKER_HOST = "CONTEXTBROKER_HOST";
- public static final String CONTEXTBROKER_HOST_DEFAULT = "192.168.99.100";
- public static final String CONTEXTBROKER_PORT = "CONTEXTBROKER_PORT";
- public static final int CONTEXTBROKER_PORT_DEFAULT = 8082;
- public static final String CONTEXTBROKER_CONNECT_TIMEOUT = "CONTEXTBROKER_CONNECT_TIMEOUT";
- public static final int CONTEXTBROKER_CONNECT_TIMEOUT_DEFAULT = 2000;
- public static final String CONTEXTBROKER_REQUEST_TIMEOUT = "CONTEXTBROKER_REQUEST_TIMEOUT";
- public static final int CONTEXTBROKER_REQUEST_TIMEOUT_DEFAULT = 10000;
- public static final String CONTEXTBROKER_CLIENT_POOL_SIZE = "CONTEXTBROKER_CLIENT_POOL_SIZE";
- public static final int CONTEXTBROKER_CLIENT_POOL_SIZE_DEFAULT = 20;
-
- protected UriBuilder contextBrokerHostUri;
- protected Client httpClient;
- protected URI hostUri;
- protected RegistrationProvider registrationProvider;
- protected SubscriptionProvider subscriptionProvider;
-
- @Override
- public void init(Container container) throws Exception {
- contextBrokerHostUri =
- UriBuilder.fromPath("/")
- .scheme("http")
- .host(getString(container.getConfig(), CONTEXTBROKER_HOST, CONTEXTBROKER_HOST_DEFAULT))
- .port(getInteger(container.getConfig(), CONTEXTBROKER_PORT, CONTEXTBROKER_PORT_DEFAULT));
-
- LOG.info("Preparing entity service for broker host: " + contextBrokerHostUri.build());
-
- ResteasyClientBuilder clientBuilder =
- new ResteasyClientBuilder()
- .establishConnectionTimeout(
- getInteger(container.getConfig(), CONTEXTBROKER_CONNECT_TIMEOUT, CONTEXTBROKER_CONNECT_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .socketTimeout(
- getInteger(container.getConfig(), CONTEXTBROKER_REQUEST_TIMEOUT, CONTEXTBROKER_REQUEST_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .connectionPoolSize(
- getInteger(container.getConfig(), CONTEXTBROKER_CLIENT_POOL_SIZE, CONTEXTBROKER_CLIENT_POOL_SIZE_DEFAULT)
- );
-
- this.httpClient = WebClient
- .registerDefaults(container, clientBuilder)
- .register(EntryPointMessageBodyConverter.class)
- .register(EntityMessageBodyConverter.class)
- .register(EntityArrayMessageBodyConverter.class)
- .build();
-
- hostUri = container.getService(WebService.class).getHostUri();
-
- EntityResourceImpl entityResource = new EntityResourceImpl(this);
-
- container.getService(WebService.class).getApiSingletons().add(new EntryPointMessageBodyConverter());
- container.getService(WebService.class).getApiSingletons().add(new EntityMessageBodyConverter());
- container.getService(WebService.class).getApiSingletons().add(new EntityArrayMessageBodyConverter());
- container.getService(WebService.class).getApiSingletons().add(entityResource);
-
- subscriptionProvider = entityResource;
- registrationProvider = new ContextBrokerV1ResourceImpl(httpClient, contextBrokerHostUri);
-
- // Configure the providers
- subscriptionProvider.configure(container);
- registrationProvider.configure(container);
- }
-
- @Override
- public void start(Container container) throws Exception {
- // TODO Not a great way to block startup while we wait for other services (Hystrix?)
- pingContextBroker();
- LOG.info("Context broker provider available: " + contextBrokerHostUri.build());
- }
-
- @Override
- public void stop(Container container) throws Exception {
- if (httpClient != null)
- httpClient.close();
-
- if (registrationProvider != null)
- registrationProvider.stop();
- }
-
- public Client getHttpClient() {
- return httpClient;
- }
-
- public RegistrationProvider getRegistrationProvider() { return registrationProvider; }
-
- public SubscriptionProvider getSubscriptionProvider() { return subscriptionProvider; }
-
- public ContextBrokerV2Resource getContextBroker() {
- return getContextBroker(getTarget(httpClient, contextBrokerHostUri.build()));
- }
-
- public ContextBrokerV2Resource getContextBroker(ResteasyWebTarget target) {
- return target.proxy(ContextBrokerV2Resource.class);
- }
-
- public ContextBrokerV1Resource getContextBrokerV1() {
- return getContextBrokerV1(getTarget(httpClient, contextBrokerHostUri.build()));
- }
-
- public ContextBrokerV1Resource getContextBrokerV1(ResteasyWebTarget target) {
- return target.proxy(ContextBrokerV1Resource.class);
- }
-
- public void pingContextBroker() {
- Observable.fromCallable(() -> {
- EntryPoint response = getContextBroker().getEntryPoint();
- if (response != null)
- return true;
- throw new WebApplicationException("Context broker not available");
- }).retryWhen(
- new RetryWithDelay("Connecting to context broker: " + contextBrokerHostUri.build(), 10, 3000)
- ).toBlocking().singleOrDefault(false);
- }
-
- public boolean registerEntityProvider(String entityType, String entityId, List<Attribute> attributes, EntityProvider provider) {
- return registrationProvider.registerEntityProvider(entityType, entityId, attributes, provider);
- }
-
- public void unregisterEntityProvider(String entityType, String entityId, EntityProvider provider) {
- registrationProvider.unregisterEntityProvider(entityType, entityId, provider);
- }
-
- public void unregisterEntityProvider(EntityProvider provider) {
- registrationProvider.unregisterEntityProvider(provider);
- }
-
- public boolean registerEntityListener(Consumer<Entity[]> listener, SubscriptionParams subscription) {
- return subscriptionProvider.registerSubscriber(listener, subscription);
- }
-
- public SubscriptionParams getEntityListerSubscriptionParams(Consumer<Entity[]> listener) {
- return subscriptionProvider.getSubscription(listener);
- }
-
- public void unregisterEntityListener(Consumer<Entity[]> listener) {
- subscriptionProvider.unregisterSubscriber(listener);
- }
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntryPointMessageBodyConverter.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntryPointMessageBodyConverter.java
deleted file mode 100644
index 747cccd03..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/EntryPointMessageBodyConverter.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import elemental.json.Json;
-import elemental.json.JsonObject;
-import org.jboss.resteasy.plugins.providers.ProviderHelper;
-import org.openremote.manager.shared.ngsi.EntryPoint;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-
-@Provider
-public class EntryPointMessageBodyConverter implements MessageBodyReader<EntryPoint>, MessageBodyWriter<EntryPoint> {
-
- @Override
- public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return EntryPoint.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);
- }
-
- @Override
- public EntryPoint readFrom(Class<EntryPoint> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
- String str = ProviderHelper.readString(entityStream, mediaType);
- JsonObject jsonObject = Json.parse(str);
- return new EntryPoint(jsonObject);
- }
-
- @Override
- public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return EntryPoint.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);
- }
-
- @Override
- public long getSize(EntryPoint value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- return -1;
- }
-
- @Override
- public void writeTo(EntryPoint value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
- String str = value.getJsonObject().toJson();
- String charset = mediaType.getParameters().get("charset");
- if (charset == null) entityStream.write(str.getBytes("UTF-8"));
- else entityStream.write(str.getBytes(charset));
- }
-}
\ No newline at end of file
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/RegistrationProvider.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/RegistrationProvider.java
deleted file mode 100644
index 2b1d2550e..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/RegistrationProvider.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.openremote.container.Container;
-import org.openremote.manager.shared.ngsi.Attribute;
-
-import java.util.List;
-
-public interface RegistrationProvider {
-
- void configure(Container container) throws Exception;
-
- void stop();
-
- String getRegistrationCallbackUri();
-
- boolean registerEntityProvider(String entityType, String entityId, List<Attribute> attributes, EntityProvider provider);
-
- void unregisterEntityProvider(String entityType, String entityId, EntityProvider provider);
-
- void unregisterEntityProvider(EntityProvider provider);
-
- /**
- * Get the refresh interval duration of this context providers registrations
- * @return Registration refresh interval in seconds
- */
- int getRefreshInterval();
-
- /**
- * Set the refresh interval of this context providers registrations
- */
- void setRefreshInterval(int seconds);
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/ngsi/SubscriptionProvider.java b/manager/server/src/main/java/org/openremote/manager/server/ngsi/SubscriptionProvider.java
deleted file mode 100644
index 27a393efe..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/ngsi/SubscriptionProvider.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2016, 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.manager.server.ngsi;
-
-import org.openremote.container.Container;
-import org.openremote.model.Consumer;
-import org.openremote.manager.shared.ngsi.Entity;
-import org.openremote.manager.shared.ngsi.params.SubscriptionParams;
-
-public interface SubscriptionProvider {
- void configure(Container container) throws Exception;
-
- void stop();
-
- boolean registerSubscriber(Consumer<Entity[]> listener, SubscriptionParams subscription);
-
- SubscriptionParams getSubscription(Consumer<Entity[]> listener);
-
- void unregisterSubscriber(Consumer<Entity[]> listener);
-
- String getSubscriptionCallbackUri();
-
- int getRefreshInterval();
-
- void setRefreshInterval(int seconds);
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index c7dfe03cc..a5cd4ba84 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
@@ -29,10 +29,12 @@ import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.setup.AbstractManagerSetup;
import org.openremote.model.*;
import org.openremote.model.asset.*;
+import org.openremote.model.units.AttributeUnits;
+import org.openremote.model.units.ColorRGB;
import static org.openremote.model.Constants.*;
import static org.openremote.model.AttributeType.*;
-import static org.openremote.model.asset.AssetAttributeMeta.*;
+import static org.openremote.model.asset.AssetMeta.*;
import static org.openremote.model.asset.AssetType.RESIDENCE;
import static org.openremote.model.asset.AssetType.BUILDING;
import static org.openremote.model.asset.AssetType.ROOM;
@@ -70,24 +72,24 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
Attributes smartOfficeAttributes = new Attributes();
smartOfficeAttributes.put(
new Attribute("geoStreet", STRING, Json.create("Torenallee 20"))
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Street")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Street")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet")))
),
new Attribute("geoPostalCode", AttributeType.INTEGER, Json.create(5617))
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Postal Code")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Postal Code")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode")))
),
new Attribute("geoCity", STRING, Json.create("Eindhoven"))
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("City")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("City")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity")))
),
new Attribute("geoCountry", STRING, Json.create("Netherlands"))
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Country")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Country")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))
)
);
smartOffice.setAttributes(smartOfficeAttributes.getJsonObject());
@@ -127,82 +129,82 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
ThingAttributes thingAttributes = new ThingAttributes(thing);
thingAttributes.put(
new Attribute("light1Toggle", BOOLEAN, Json.create(true))
- .setMetadata(new Metadata()
- .add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION,
+ .setMeta(new Meta()
+ .add(new MetaItem(
+ AssetMeta.DESCRIPTION,
Json.create("The switch for the light in the living room"))
)
- .add(new MetadataItem(
- AssetAttributeMeta.AGENT_LINK,
+ .add(new MetaItem(
+ AssetMeta.AGENT_LINK,
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
- .add(new MetadataItem(
+ .add(new MetaItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("switch")
))
),
new Attribute("light1Dimmer", INTEGER) // No initial value!
- .setMetadata(new Metadata()
- .add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION,
+ .setMeta(new Meta()
+ .add(new MetaItem(
+ AssetMeta.DESCRIPTION,
Json.create("The dimmer for the light in the living room"))
)
- .add(new MetadataItem(
- AssetAttributeMeta.RANGE_MIN,
+ .add(new MetaItem(
+ AssetMeta.RANGE_MIN,
Json.create(0))
)
- .add(new MetadataItem(
- AssetAttributeMeta.RANGE_MAX,
+ .add(new MetaItem(
+ AssetMeta.RANGE_MAX,
Json.create(100))
)
- .add(new MetadataItem(
- AssetAttributeMeta.AGENT_LINK,
+ .add(new MetaItem(
+ AssetMeta.AGENT_LINK,
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
- .add(new MetadataItem(
+ .add(new MetaItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("range")
))
),
- new Attribute("light1Color", OBJECT, new ColorRGB(88, 123, 88).asJsonValue())
- .setMetadata(new Metadata()
- .add(new MetadataItem(
- AssetAttributeMeta.UNITS,
+ new Attribute("light1Color", INTEGER_ARRAY, new ColorRGB(88, 123, 88).asJsonValue())
+ .setMeta(new Meta()
+ .add(new MetaItem(
+ AssetMeta.UNITS,
Json.create(AttributeUnits.COLOR_RGB.toString())
))
- .add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION,
+ .add(new MetaItem(
+ AssetMeta.DESCRIPTION,
Json.create("The color of the living room light"))
)
- .add(new MetadataItem(
- AssetAttributeMeta.AGENT_LINK,
+ .add(new MetaItem(
+ AssetMeta.AGENT_LINK,
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
- .add(new MetadataItem(
+ .add(new MetaItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("color")
))
),
new Attribute("light1PowerConsumption", DECIMAL, Json.create(12.345))
- .setMetadata(new Metadata()
- .add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION,
+ .setMeta(new Meta()
+ .add(new MetaItem(
+ AssetMeta.DESCRIPTION,
Json.create("The total power consumption of the living room light"))
)
- .add(new MetadataItem(
- AssetAttributeMeta.READ_ONLY,
+ .add(new MetaItem(
+ AssetMeta.READ_ONLY,
Json.create(true))
)
- .add(new MetadataItem(
- AssetAttributeMeta.FORMAT,
+ .add(new MetaItem(
+ AssetMeta.FORMAT,
Json.create("%3d kWh"))
)
- .add(new MetadataItem(
- AssetAttributeMeta.AGENT_LINK,
+ .add(new MetaItem(
+ AssetMeta.AGENT_LINK,
new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
- .add(new MetadataItem(
+ .add(new MetaItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("decimal")
))
- .add(new MetadataItem(
- AssetAttributeMeta.STORE_DATA_POINTS.getName(), Json.create(true)
+ .add(new MetaItem(
+ AssetMeta.STORE_DATA_POINTS.getName(), Json.create(true)
))
)
);
@@ -240,30 +242,33 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment1LivingroomThermostat.setType(AssetType.THING);
ThingAttributes apartment1LivingroomThermostatAttributes = new ThingAttributes(apartment1LivingroomThermostat);
apartment1LivingroomThermostatAttributes.put(
- new Attribute("currentTemperature", DECIMAL, Json.create("19.2"))
- .setMetadata(new Metadata()
- .add(new MetadataItem(
- AssetAttributeMeta.LABEL,
+ new Attribute("currentTemperature", DECIMAL, Json.create(19.2))
+ .setMeta(new Meta()
+ .add(new MetaItem(
+ AssetMeta.LABEL,
Json.create("Current Temp"))
)
- .add(new MetadataItem(
- AssetAttributeMeta.PROTECTED,
+ .add(new MetaItem(
+ AssetMeta.PROTECTED,
Json.create(true))
)
- .add(new MetadataItem(
- AssetAttributeMeta.READ_ONLY,
+ .add(new MetaItem(
+ AssetMeta.READ_ONLY,
Json.create(true))
)
- .add(new MetadataItem(
+ .add(new MetaItem(
Constants.NAMESPACE + ":foo:bar", Json.create("FOO")
))
- .add(new MetadataItem(
+ .add(new MetaItem(
"urn:thirdparty:bar", Json.create("BAR")
))
)
);
apartment1LivingroomThermostatAttributes.put(
- new Attribute("somethingPrivate", INTEGER, Json.create("123"))
+ new Attribute("somethingPrivate", INTEGER, Json.create(123))
+ );
+ apartment1LivingroomThermostatAttributes.put(
+ new Attribute("somethingEmpty", DECIMAL, Json.createNull())
);
apartment1LivingroomThermostat.setAttributes(apartment1LivingroomThermostatAttributes.getJsonObject());
apartment1LivingroomThermostat = assetService.merge(apartment1LivingroomThermostat);
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java
index 93c1c1405..6f84f9d03 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java
@@ -78,7 +78,7 @@ public class Agent {
public Agent setEnabled(boolean enabled) {
if (attributes.hasAttribute("enabled")) {
- attributes.get("enabled").setValue(enabled);
+ attributes.get("enabled").setValueAsBoolean(enabled);
} else {
attributes.put(new Attribute("enabled", AttributeType.BOOLEAN, Json.create(enabled)));
}
@@ -100,7 +100,7 @@ public class Agent {
}
public Agent setConnectorType(String connectorType) {
- getOrCreateConnectorTypeAttribute().setValue(connectorType);
+ getOrCreateConnectorTypeAttribute().setValueAsString(connectorType);
return this;
}
@@ -125,11 +125,11 @@ public class Agent {
Attribute attribute = attributes.get(setting.getName());
// If the connector setting still has the same type as the agent's attribute, only update metadata
if (attribute != null && attribute.getType().equals(setting.getType())) {
- attribute.setMetadata(setting.getMetadata().copy());
+ attribute.setMeta(setting.getMeta().copy());
} else {
// The agent does not have the connector setting or it's now a different type, replace/create attribute
attribute = new Attribute(setting.getName(), setting.getType());
- attribute.setMetadata(setting.getMetadata().copy());
+ attribute.setMeta(setting.getMeta().copy());
attributes.put(attribute);
}
}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AbstractAttribute.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AbstractAttribute.java
deleted file mode 100644
index f4ef6b774..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AbstractAttribute.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonValue;
-
-public abstract class AbstractAttribute {
-
- final protected String name;
-
- public AbstractAttribute(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public abstract JsonValue getValue();
-
- public abstract AbstractAttribute setValue(JsonValue value);
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AbstractEntity.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AbstractEntity.java
deleted file mode 100644
index b506f62c0..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AbstractEntity.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonObject;
-import elemental.json.impl.JsonUtil;
-
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-public abstract class AbstractEntity<A extends AbstractAttribute> {
-
- final protected JsonObject jsonObject;
-
- public AbstractEntity(JsonObject jsonObject) {
- this.jsonObject = jsonObject;
- }
-
- public JsonObject getJsonObject() {
- return jsonObject;
- }
-
-
- public String getId() {
- return jsonObject.hasKey("id") ? jsonObject.get("id").asString() : null;
- }
-
- public AbstractEntity<A> setId(String id) {
- if (id == null)
- jsonObject.remove("id");
- else
- jsonObject.put("id", id);
- return this;
- }
-
- public String getType() {
- return jsonObject.hasKey("type") ? jsonObject.get("type").asString() : null;
- }
-
- public AbstractEntity<A> setType(String type) {
- if (type == null)
- jsonObject.remove("type");
- else
- jsonObject.put("type", type);
- return this;
- }
-
- public boolean hasAttribute(String name) {
- return !name.equals("id") && !name.equals("type") && jsonObject.hasKey(name);
- }
-
- public ModelValidationError[] validate() {
- return validate(true, true);
- }
-
- public ModelValidationError[] validate(boolean validateId, boolean validateType) {
- Set<ModelValidationError> errors = new LinkedHashSet<>();
- if (validateId)
- validateId(errors);
- if (validateType)
- validateType(errors);
- validateAttributes(errors);
- return errors.toArray(new ModelValidationError[errors.size()]);
- }
-
- public abstract A[] getAttributes();
-
- public abstract A getAttribute(String name);
-
- public abstract AbstractEntity<A> addAttribute(A attribute);
-
- public abstract AbstractEntity<A> removeAttribute(String name);
-
- public abstract void clearAttributes();
-
- protected abstract void validateAttributes(Set<ModelValidationError> errors);
-
- protected void validateId(Set<ModelValidationError> errors) {
- ModelProblem[] problems = Model.validateField(getId());
- for (ModelProblem problem : problems) {
- errors.add(new ModelValidationError("id", problem));
- }
- }
-
- protected void validateType(Set<ModelValidationError> errors) {
- ModelProblem[] problems = Model.validateField(getType());
- for (ModelProblem problem : problems) {
- errors.add(new ModelValidationError("type", problem));
- }
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- AbstractEntity that = (AbstractEntity) o;
-
- return jsonObject.equals(that.jsonObject);
-
- }
-
- @Override
- public int hashCode() {
- return jsonObject.hashCode();
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + ": " + jsonObject.toJson();
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ActionType.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ActionType.java
deleted file mode 100644
index 2c64c7b3a..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ActionType.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-public enum ActionType {
- CREATE,
- UPDATE,
- DELETE
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Attribute.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Attribute.java
deleted file mode 100644
index 6e673a475..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Attribute.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import elemental.json.JsonObject;
-import elemental.json.JsonValue;
-
-public class Attribute extends AbstractAttribute {
-
- @JsonIgnore
- final protected JsonObject jsonObject;
-
- public Attribute(String name, JsonObject jsonObject) {
- super(name);
- this.jsonObject = jsonObject;
- }
-
- public Attribute(@JsonProperty("name") String name, @JsonProperty("type") AttributeType type, @JsonProperty("value") JsonValue value) {
- super(name);
- jsonObject = elemental.json.Json.createObject();
- setType(type);
- setValue(value);
- }
-
- public JsonObject getJsonObject() {
- return jsonObject;
- }
-
- @JsonProperty("value")
- @Override
- public JsonValue getValue() {
- return jsonObject.hasKey("value") ? jsonObject.get("value") : null;
- }
-
- public JsonObject getValueAsObject() {
- return jsonObject.hasKey("value") ? jsonObject.getObject("value") : null;
- }
-
- @Override
- public Attribute setValue(JsonValue value) {
- jsonObject.put("value", value);
- return this;
- }
-
- @JsonProperty("type")
- public AttributeType getType() {
- String keyValue = jsonObject.hasKey("type") ? jsonObject.get("type").asString() : null;
- return keyValue != null ? AttributeType.fromName(keyValue) : null;
- }
-
- public Attribute setType(AttributeType type) {
- jsonObject.put("type", type.getName());
- return this;
- }
-
- public Metadata getMetadata() {
- return jsonObject.hasKey("metadata") ? new Metadata(jsonObject.getObject("metadata")) : null;
- }
-
- public Attribute setMetadata(Metadata metadata) {
- jsonObject.put("metadata", metadata.getJsonObject());
- return this;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Attribute attribute = (Attribute) o;
-
- return jsonObject.equals(attribute.jsonObject);
- }
-
- @Override
- public int hashCode() {
- return jsonObject.hashCode();
- }
-
- @Override
- public String toString() {
- return getName() + " => " + jsonObject.toJson();
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AttributeType.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AttributeType.java
deleted file mode 100644
index eb49c592d..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AttributeType.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import elemental.json.JsonType;
-
-public enum AttributeType {
- OBJECT("Object", JsonType.OBJECT),
- STRING("String", JsonType.STRING),
- INTEGER("Integer", JsonType.NUMBER),
- FLOAT("Float", JsonType.NUMBER),
- BOOLEAN("Boolean", JsonType.BOOLEAN),
- OBJECT_ARRAY("Object[]", JsonType.ARRAY),
- STRING_ARRAY("String[]", JsonType.ARRAY),
- INTEGER_ARRAY("Integer[]", JsonType.ARRAY),
- FLOAT_ARRAY("Float[]", JsonType.ARRAY),
- BOOLEAN_ARRAY("Boolean[]", JsonType.ARRAY),
- DATETIME("DateTime", JsonType.STRING);
-
- @JsonProperty("type")
- private String name;
- private JsonType jsonType;
-
- private AttributeType(@JsonProperty("name") String name, @JsonProperty("jsonType") JsonType jsonType) {
- this.name = name;
- this.jsonType = jsonType;
- }
-
- public String getName() {
- return name;
- }
-
- public JsonType getJsonType() {
- return jsonType;
- }
-
- @JsonCreator
- public static AttributeType fromString(@JsonProperty("type") String str) {
- return fromName(str);
- }
-
- public static AttributeType fromName(String name) {
- AttributeType[] vals = AttributeType.values();
- for (int i = 0; i < vals.length; i++) {
- if (vals[i].getName().equalsIgnoreCase(name))
- return vals[i];
- }
- return null;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/BatchRegistrationRequestV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/BatchRegistrationRequestV2.java
deleted file mode 100644
index fc73d8ebc..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/BatchRegistrationRequestV2.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import java.util.List;
-
-public class BatchRegistrationRequestV2 {
- protected List<RegistrationRequestV2> registrations;
- protected ActionType actionType;
-
- public BatchRegistrationRequestV2(List<RegistrationRequestV2> registrations, ActionType actionType) {
- this.registrations = registrations;
- this.actionType = actionType;
- }
-
- public List<RegistrationRequestV2> getRegistrations() {
- return registrations;
- }
-
- public ActionType getActionType() {
- return actionType;
- }
-
- public void setActionType(ActionType actionType) {
- this.actionType = actionType;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextAttribute.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextAttribute.java
deleted file mode 100644
index 0aaea1486..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextAttribute.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class ContextAttribute {
- @JsonInclude
- protected String name;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String type;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String isDomain;
-
- public ContextAttribute(String name) {
- this.name = name;
- }
-
- public ContextAttribute(@JsonProperty("name") String name, @JsonProperty("type") String type, @JsonProperty("domain") boolean domain) {
- this.isDomain = Boolean.toString(domain);
- this.name = name;
- this.type = type;
- }
-
- public String getName() {
- return name;
- }
-
- public String getType() {
- return type;
- }
-
- public boolean isDomain() {
- return isDomain == null ? false : Boolean.parseBoolean(isDomain);
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextDiscovery.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextDiscovery.java
deleted file mode 100644
index 05fd8cddf..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextDiscovery.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.List;
-
-public class ContextDiscovery {
- @JsonInclude
- protected List<ContextEntity> entities;
- @JsonInclude
- protected List<ContextAttribute> attributes;
-
- public ContextDiscovery(List<ContextEntity> entities) {
- this.entities = entities;
- }
-
- public ContextDiscovery(@JsonProperty("entities") List<ContextEntity> entities, @JsonProperty("attrs") List<ContextAttribute> attributes) {
- this.entities = entities;
- this.attributes = attributes;
- }
-
- public List<ContextEntity> getEntities() {
- return entities;
- }
-
- public List<ContextAttribute> getAttributes() {
- return attributes;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextElement.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextElement.java
deleted file mode 100644
index 27707eb69..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextElement.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.List;
-
-public class ContextElement extends ContextEntity {
- @JsonInclude
- protected List<Attribute> attributes;
-
- public ContextElement(@JsonProperty("type") String type, @JsonProperty("id") String id, @JsonProperty("pattern") boolean pattern, @JsonProperty("attrs") List<Attribute> attributes) {
- super(type, id, pattern);
- this.attributes = attributes;
- }
-
- public List<Attribute> getAttributes() {
- return attributes;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextEntity.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextEntity.java
deleted file mode 100644
index c7664d608..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextEntity.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class ContextEntity {
- @JsonInclude
- protected String type;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String isPattern = null;
- @JsonInclude
- protected String id;
-
- public ContextEntity(String type, String id) {
- this.type = type;
- this.id = id;
- }
-
- public ContextEntity(@JsonProperty("type") String type, @JsonProperty("id") String id, @JsonProperty("isPattern") boolean pattern) {
- this.isPattern = Boolean.toString(pattern);
- this.type = type;
- this.id = id;
- }
-
- public String getType() {
- return type;
- }
-
- public String getId() {
- return id;
- }
-
- public boolean isPattern() {
- return isPattern == null ? false : Boolean.parseBoolean(isPattern);
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Duration.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Duration.java
deleted file mode 100644
index e0c688f72..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Duration.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-public class Duration {
- @JsonInclude
- protected String duration;
-
- public Duration(String duration) {
- this.duration = duration;
- }
-
- public String getDuration() {
- return duration;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Entity.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Entity.java
deleted file mode 100644
index adc66bc55..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Entity.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonArray;
-import elemental.json.JsonObject;
-
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-public class Entity extends AbstractEntity<Attribute> {
-
- public static Entity[] from(JsonArray jsonArray) {
- Entity[] array = new Entity[jsonArray.length()];
- for (int i = 0; i < array.length; i++) {
- array[i] = new Entity(jsonArray.get(i));
- }
- return array;
- }
-
- public static Entity from(JsonObject jsonObject) {
- return new Entity(jsonObject);
- }
-
- public Entity(JsonObject jsonObject) {
- super(jsonObject);
- }
-
- public Entity() {
- super(elemental.json.Json.createObject());
- }
-
- @Override
- public Attribute[] getAttributes() {
- Set<Attribute> attributes = new LinkedHashSet<>();
- String[] keys = jsonObject.keys();
- for (String key : keys) {
- if (hasAttribute(key)) {
- Attribute attribute = new Attribute(key, jsonObject.getObject(key));
- attributes.add(attribute);
- }
- }
- return attributes.toArray(new Attribute[attributes.size()]);
- }
-
- @Override
- public Attribute getAttribute(String name) {
- return hasAttribute(name) ? new Attribute(name, jsonObject.getObject(name)) : null;
- }
-
- @Override
- public Entity addAttribute(Attribute attribute) {
- jsonObject.put(attribute.getName(), attribute.getJsonObject());
- return this;
- }
-
- @Override
- public Entity removeAttribute(String name) {
- if (hasAttribute(name)) {
- jsonObject.remove(name);
- }
- return this;
- }
-
- @Override
- public void clearAttributes() {
- for (Attribute attribute : getAttributes()) {
- removeAttribute(attribute.getName());
- }
- }
-
- @Override
- protected void validateAttributes(Set<ModelValidationError> errors) {
- for (Attribute attribute : getAttributes()) {
- ModelProblem[] problems = Model.validateField(attribute.getName());
- for (ModelProblem problem : problems) {
- errors.add(new ModelValidationError("attributeName", problem));
- }
- }
- }
-
- public String getAttributeValueAsString(String name) {
- Attribute attr = getAttribute(name);
- return attr != null ? attr.getValue().asString() : null;
- }
-
- public boolean getAttributeValueAsBoolean(String name) {
- Attribute attr = getAttribute(name);
- return attr != null && attr.getValue().asBoolean();
- }
-
- public JsonObject getAttributeValueAsObject(String name) {
- Attribute attr = getAttribute(name);
- return attr != null ? attr.getValueAsObject () : null;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeListV1.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeListV1.java
deleted file mode 100644
index 645ad92e2..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeListV1.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.List;
-
-public class EntityAttributeListV1 {
- @JsonInclude
- protected List<ContextEntity> entities;
- @JsonInclude
- protected List<ContextAttribute> attributes;
- @JsonProperty(value = "providingApplication")
- protected String providerUri;
-
- public EntityAttributeListV1(@JsonProperty("entities") List<ContextEntity> entities, @JsonProperty("attrs") List<ContextAttribute> attributes, @JsonProperty("providingApplication") String providerUri) {
- this.entities = entities;
- this.attributes = attributes;
- this.providerUri = providerUri;
- }
-
- public List<ContextEntity> getEntities() {
- return entities;
- }
-
- public List<ContextAttribute> getAttributes() {
- return attributes;
- }
-
- public String getProviderUri() {
- return providerUri;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeListV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeListV2.java
deleted file mode 100644
index 293d42fb8..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeListV2.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import elemental.json.JsonObject;
-
-import java.util.List;
-
-public class EntityAttributeListV2 {
- @JsonInclude
- protected List<ContextEntity> entities;
- @JsonInclude
- protected List<ContextAttribute> attributes;
-
-
- public EntityAttributeListV2(@JsonProperty("entities") List<ContextEntity> entities, @JsonProperty("attrs") List<ContextAttribute> attributes) {
- this.entities = entities;
- this.attributes = attributes;
- }
-
- public List<ContextEntity> getEntities() {
- return entities;
- }
-
- public List<ContextAttribute> getAttributes() {
- return attributes;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeQuery.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeQuery.java
deleted file mode 100644
index 1d213bd97..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeQuery.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.List;
-
-public class EntityAttributeQuery {
- @JsonInclude
- protected List<ContextEntity> entities;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected List<String> attributes;
-
- public EntityAttributeQuery(@JsonProperty("entities")List<ContextEntity> entities, @JsonProperty("attrs")List<String> attributes) {
- this.entities = entities;
- this.attributes = attributes;
- }
-
- public List<ContextEntity> getEntities() {
- return entities;
- }
-
- public List<String> getAttributes() {
- return attributes;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityResource.java
deleted file mode 100644
index ea2098afd..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityResource.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonObject;
-import jsinterop.annotations.JsType;
-import org.openremote.manager.shared.http.PATCH;
-import org.openremote.manager.shared.http.RequestParams;
-import org.openremote.manager.shared.http.SuccessStatusCode;
-import org.openremote.manager.shared.ngsi.params.EntityListParams;
-import org.openremote.manager.shared.ngsi.params.EntityParams;
-
-import javax.annotation.security.RolesAllowed;
-import javax.ws.rs.*;
-
-import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
-
-/**
- * http://telefonicaid.github.io/fiware-orion/api/v2/
- */
-@Path("entity")
-@JsType(isNative = true)
-public interface EntityResource {
-
- @GET
- @Path("entities")
- @Produces(APPLICATION_JSON)
- @SuccessStatusCode(200)
- @RolesAllowed({"read:assets"})
- Entity[] getEntities(@BeanParam RequestParams requestParams, @BeanParam EntityListParams entityListParams);
-
- @POST
- @Path("entities")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(201)
- @RolesAllowed({"write:assets"})
- void postEntity(@BeanParam RequestParams requestParams, Entity entity);
-
- @GET
- @Path("entities/{entityId}")
- @Produces(APPLICATION_JSON)
- @SuccessStatusCode(200)
- @RolesAllowed({"read:assets"})
- Entity getEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
-
- @DELETE
- @Path("entities/{entityId}")
- @SuccessStatusCode(204)
- @RolesAllowed({"write:assets"})
- void deleteEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId);
-
- @PUT
- @Path("entities/{entityId}/attrs")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(204)
- @RolesAllowed({"write:assets"})
- void putEntityAttributes(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, Entity entity);
-
- @PATCH
- @Path("entities/{entityId}/attrs")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(204)
- @RolesAllowed({"write:assets"})
- void patchEntityAttributes(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, Entity entity);
-
- @POST
- @Path("subscriber")
- @Consumes(APPLICATION_JSON)
- void subscriberCallback(@HeaderParam("Ngsiv2-AttrsFormat") NotificationFormat format, JsonObject notification);
-
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntryPoint.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntryPoint.java
deleted file mode 100644
index ff8e61695..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntryPoint.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonObject;
-
-public class EntryPoint {
-
- final protected JsonObject jsonObject;
-
- public EntryPoint(JsonObject jsonObject) {
- this.jsonObject = jsonObject;
- }
-
- public JsonObject getJsonObject() {
- return jsonObject;
- }
-
- public String getEntitiesLocation() {
- return jsonObject.hasKey("entities_url") ? jsonObject.get("entities_url").asString() : null;
- }
-
- public void setEntitiesLocation(String entitiesLocation) {
- jsonObject.put("entities_url", entitiesLocation);
- }
-
- public String getTypesLocation() {
- return jsonObject.hasKey("types_url") ? jsonObject.get("types_url").asString() : null;
- }
-
- public void setTypesLocation(String typesLocation) {
- jsonObject.put("types_url", typesLocation);
- }
-
- public String getSubscriptionsLocation() {
- return jsonObject.hasKey("subscriptions_url") ? jsonObject.get("subscriptions_url").asString() : null;
- }
-
- public void setSubscriptionsLocation(String subscriptionsLocation) {
- jsonObject.put("subscriptions_url", subscriptionsLocation);
- }
-
- public String getRegistrationsLocation() {
- return jsonObject.hasKey("registrations_url") ? jsonObject.get("registrations_url").asString() : null;
- }
-
- public void setRegistrationsLocation(String registrationsLocation) {
- jsonObject.put("registrations_url", registrationsLocation);
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + ": " + jsonObject.toJson();
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Error.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Error.java
deleted file mode 100644
index 049c1bfbd..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Error.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class Error {
- @JsonProperty(value = "errorCode")
- protected StatusCode statusCode;
-
- public Error(@JsonProperty("errorCode") StatusCode statusCode) {
- this.statusCode = statusCode;
- }
-
- public StatusCode getStatusCode() {
- return statusCode;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/KeyValueAttribute.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/KeyValueAttribute.java
deleted file mode 100644
index e0ef306cb..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/KeyValueAttribute.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonValue;
-
-public class KeyValueAttribute extends AbstractAttribute {
-
- protected JsonValue value;
-
- public KeyValueAttribute(String name, JsonValue value) {
- super(name);
- this.value = value;
- }
-
- @Override
- public JsonValue getValue() {
- return value;
- }
-
- @Override
- public KeyValueAttribute setValue(JsonValue value) {
- this.value = value;
- return this;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- KeyValueAttribute that = (KeyValueAttribute) o;
-
- return getName().equals(that.getName());
- }
-
- @Override
- public int hashCode() {
- return getName().hashCode();
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + ": " + getName() + ":" + getValue().toJson();
- }
-
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/KeyValueEntity.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/KeyValueEntity.java
deleted file mode 100644
index 489576e17..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/KeyValueEntity.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonArray;
-import elemental.json.JsonObject;
-
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-public class KeyValueEntity extends AbstractEntity<KeyValueAttribute> {
-
- public static KeyValueEntity[] from(JsonArray jsonArray) {
- KeyValueEntity[] array = new KeyValueEntity[jsonArray.length()];
- for (int i = 0; i < array.length; i++) {
- array[i] = new KeyValueEntity(jsonArray.get(i));
- }
- return array;
- }
-
- public static KeyValueEntity from(JsonObject jsonObject) {
- return new KeyValueEntity(jsonObject);
- }
-
- public KeyValueEntity(JsonObject jsonObject) {
- super(jsonObject);
- }
-
- @Override
- public KeyValueAttribute[] getAttributes() {
- Set<KeyValueAttribute> attributes = new LinkedHashSet<>();
- String[] keys = jsonObject.keys();
- for (String key : keys) {
- if (hasAttribute(key)) {
- KeyValueAttribute attribute = new KeyValueAttribute(key, jsonObject.get(key));
- attributes.add(attribute);
- }
- }
- return attributes.toArray(new KeyValueAttribute[attributes.size()]);
- }
-
- @Override
- public KeyValueAttribute getAttribute(String name) {
- return hasAttribute(name) ? new KeyValueAttribute(name, jsonObject.get(name)) : null;
- }
-
- @Override
- public KeyValueEntity addAttribute(KeyValueAttribute attribute) {
- jsonObject.put(attribute.getName(), attribute.getValue());
- return this;
- }
-
- @Override
- public KeyValueEntity removeAttribute(String name) {
- if (hasAttribute(name)) {
- jsonObject.remove(name);
- }
- return this;
- }
-
- @Override
- public void clearAttributes() {
- for (KeyValueAttribute attribute : getAttributes()) {
- removeAttribute(attribute.getName());
- }
- }
-
- @Override
- protected void validateAttributes(Set<ModelValidationError> errors) {
- for (KeyValueAttribute attribute : getAttributes()) {
- ModelProblem[] problems = Model.validateField(attribute.getName());
- for (ModelProblem problem : problems) {
- errors.add(new ModelValidationError("attributeName", problem));
- }
- }
- }
-
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Metadata.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Metadata.java
deleted file mode 100644
index c094c0b1f..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Metadata.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonObject;
-
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-public class Metadata {
-
- final protected JsonObject jsonObject;
-
- public Metadata(JsonObject jsonObject) {
- this.jsonObject = jsonObject;
- }
-
- public JsonObject getJsonObject() {
- return jsonObject;
- }
-
- public MetadataElement[] getElements() {
- Set<MetadataElement> elements = new LinkedHashSet<>();
-
- String[] keys = jsonObject.keys();
- for (String key : keys) {
- MetadataElement element = new MetadataElement(key, jsonObject.getObject(key));
- elements.add(element);
- }
-
- return elements.toArray(new MetadataElement[elements.size()]);
- }
-
- public MetadataElement getElement(String name) {
- return hasElement(name) ? new MetadataElement(name, jsonObject.getObject(name)) : null;
- }
-
- public boolean hasElement(String name) {
- return jsonObject.hasKey(name);
- }
-
- public Metadata addElement(MetadataElement element) {
- jsonObject.put(element.getName(), element.getJsonObject());
- return this;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Metadata metadata = (Metadata) o;
-
- return jsonObject.equals(metadata.jsonObject);
- }
-
- @Override
- public int hashCode() {
- return jsonObject.hashCode();
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + ": " + jsonObject.toJson();
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/MetadataElement.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/MetadataElement.java
deleted file mode 100644
index 07a2c267c..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/MetadataElement.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import elemental.json.JsonObject;
-import elemental.json.JsonValue;
-
-public class MetadataElement {
-
- final protected String name;
- final protected JsonObject jsonObject;
-
- public MetadataElement(String name, JsonObject jsonObject) {
- this.name = name;
- this.jsonObject = jsonObject;
- }
-
- public JsonObject getJsonObject() {
- return jsonObject;
- }
-
- public String getName() {
- return name;
- }
-
- public JsonValue getValue() {
- return jsonObject.hasKey("value") ? jsonObject.get("value") : null;
- }
-
- public MetadataElement setValue(JsonValue value) {
- jsonObject.put("value", value);
- return this;
- }
-
- public String getType() {
- return jsonObject.hasKey("type") ? jsonObject.get("type").asString() : null;
- }
-
- public MetadataElement setType(String type) {
- jsonObject.put("type", type);
- return this;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- MetadataElement metadata = (MetadataElement) o;
-
- return jsonObject.equals(metadata.jsonObject);
- }
-
- @Override
- public int hashCode() {
- return jsonObject.hashCode();
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Model.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Model.java
deleted file mode 100644
index 8f6a32e89..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Model.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-/**
- * http://telefonicaid.github.io/fiware-orion/api/v2/
- */
-public class Model {
-
- public static char[] FIELD_CHARS = new char[]{
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- '%', '!', '"', '$', '\'', '`', '(', ')', '*', '+', '.', ',', '-', ':', ';', '<', '=', '>', '@', '[', '\\', ']', '^', '_', '{', '|', '}', '~'
- };
-
- public static final int FIELD_MAX_LENGTH = 256;
-
- static {
- Arrays.sort(FIELD_CHARS);
- }
-
- public static ModelProblem[] validateField(String value) {
- Set<ModelProblem> problems = new LinkedHashSet<>();
- if (value == null || value.length() ==0) {
- problems.add(ModelProblem.FIELD_EMPTY);
- } else {
- char[] chars = value.toCharArray();
- if (chars.length > FIELD_MAX_LENGTH) {
- problems.add(ModelProblem.FIELD_TOO_LONG);
-
- }
- for (char c : chars) {
- if (Arrays.binarySearch(FIELD_CHARS, c) < 0) {
- problems.add(ModelProblem.FIELD_INVALID_CHARS);
- break;
- }
- }
- }
- return problems.toArray(new ModelProblem[problems.size()]);
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ModelProblem.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ModelProblem.java
deleted file mode 100644
index bb1bb14ce..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ModelProblem.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-public enum ModelProblem {
-
- FIELD_EMPTY("Field can not be empty"),
- FIELD_INVALID_CHARS("Field contains invalid characters"),
- FIELD_TOO_LONG("Field too long");
-
- protected String message;
-
- ModelProblem(String message) {
- this.message = message;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ModelValidationError.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ModelValidationError.java
deleted file mode 100644
index db383e853..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ModelValidationError.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-public class ModelValidationError {
-
- protected final String affectedItem;
- protected final ModelProblem problem;
-
- public ModelValidationError(String affectedItem, ModelProblem problem) {
- this.affectedItem = affectedItem;
- this.problem = problem;
- }
-
- public String getAffectedItem() {
- return affectedItem;
- }
-
- public ModelProblem getProblem() {
- return problem;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "affectedItem='" + affectedItem + '\'' +
- ", problem=" + problem +
- '}';
- }
-}
\ No newline at end of file
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Notification.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Notification.java
deleted file mode 100644
index 6cfe5de58..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Notification.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class Notification<T extends AbstractAttribute> {
- @JsonInclude
- protected String subscriptionId;
- @JsonInclude
- protected AbstractEntity<T> data;
-
- public Notification(@JsonProperty String subscriptionId, @JsonProperty AbstractEntity<T> data) {
- this.subscriptionId = subscriptionId;
- this.data = data;
- }
-
- public String getSubscriptionId() {
- return subscriptionId;
- }
-
- public AbstractEntity<T> getData() {
- return data;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/NotificationFormat.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/NotificationFormat.java
deleted file mode 100644
index ac7d3612b..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/NotificationFormat.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-
-public enum NotificationFormat {
- NORMALIZED,
- KEYVALUES,
- VALUES;
-
- @JsonCreator
- public static NotificationFormat fromString(String key) {
- return key == null
- ? null
- : NotificationFormat.valueOf(key.toUpperCase());
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/QueryResponse.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/QueryResponse.java
deleted file mode 100644
index 70cab88ba..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/QueryResponse.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class QueryResponse {
- @JsonInclude
- protected ContextElement contextElement;
- @JsonInclude
- protected StatusCode statusCode;
-
- public QueryResponse(@JsonProperty("contextElement") ContextElement contextElement, @JsonProperty("statusCode") StatusCode statusCode) {
- this.contextElement = contextElement;
- this.statusCode = statusCode;
- }
-
- public ContextElement getContextElement() {
- return contextElement;
- }
-
- public StatusCode getStatusCode() {
- return statusCode;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/QueryResponseWrapper.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/QueryResponseWrapper.java
deleted file mode 100644
index 14e4322f9..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/QueryResponseWrapper.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.List;
-
-public class QueryResponseWrapper {
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected List<QueryResponse> contextResponses;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected StatusCode errorCode;
-
- public QueryResponseWrapper(@JsonProperty("contextResponses") List<QueryResponse> contextResponses, @JsonProperty("errorCode") StatusCode errorCode) {
- this.contextResponses = contextResponses;
- this.errorCode = errorCode;
- }
-
- public QueryResponseWrapper(List<QueryResponse> contextResponses) {
- this.contextResponses = contextResponses;
- }
-
- public QueryResponseWrapper(StatusCode errorCode) {
- this.errorCode = errorCode;
- }
-
- public List<QueryResponse> getContextResponses() {
- return contextResponses;
- }
-
- public StatusCode getErrorCode() {
- return errorCode;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationRequestV1.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationRequestV1.java
deleted file mode 100644
index 7de8df1c6..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationRequestV1.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.List;
-
-public class RegistrationRequestV1 {
- @JsonProperty(value = "contextRegistrations")
- protected List<EntityAttributeListV1> registrations;
- @JsonInclude
- protected String duration;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String registrationId;
-
- public RegistrationRequestV1(List<EntityAttributeListV1> registrations, String duration) {
- this.registrations = registrations;
- this.duration = duration;
- }
-
- public RegistrationRequestV1(@JsonProperty("registrations") List<EntityAttributeListV1> registrations, @JsonProperty("duration") String duration, @JsonProperty("registrationId") String registrationId) {
- this.registrations = registrations;
- this.duration = duration;
- this.registrationId = registrationId;
- }
-
- public List<EntityAttributeListV1> getRegistrations() {
- return registrations;
- }
-
- public String getDuration() {
- return duration;
- }
-
- public void setDuration(String duration) {
- this.duration = duration;
- }
-
- public String getRegistrationId() {
- return registrationId;
- }
-
- public void setRegistrationId(String registrationId) {
- this.registrationId = registrationId;
- }
-
- public void setRegistrations(List<EntityAttributeListV1> registrations) {
- this.registrations = registrations;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationRequestV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationRequestV2.java
deleted file mode 100644
index 7d98828db..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationRequestV2.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import elemental.json.JsonObject;
-
-public class RegistrationRequestV2 {
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected EntityAttributeListV2 subject;
- @JsonProperty(value = "callback")
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String providerUri;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected JsonObject metadata;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String duration;
- @JsonIgnore
- protected String registrationId;
-
- public RegistrationRequestV2(EntityAttributeListV2 subject, String providerUri, JsonObject metadata, String duration) {
- this.subject = subject;
- this.providerUri = providerUri;
- this.metadata = metadata;
- this.duration = duration;
- }
-
- public RegistrationRequestV2(String duration) {
- this.duration = duration;
- }
-
- public EntityAttributeListV2 getSubject() {
- return subject;
- }
-
- public String getProviderUri() {
- return providerUri;
- }
-
- public JsonObject getMetadata() {
- return metadata;
- }
-
- public String getDuration() {
- return duration;
- }
-
- public void setDuration(String duration) {
- this.duration = duration;
- }
-
- public String getRegistrationId() {
- return registrationId;
- }
-
- public void setRegistrationId(String registrationId) {
- this.registrationId = registrationId;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationResponseV1.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationResponseV1.java
deleted file mode 100644
index b08648151..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/RegistrationResponseV1.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class RegistrationResponseV1 {
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String duration;
- @JsonInclude
- protected String registrationId;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected StatusCode errorCode;
-
- public RegistrationResponseV1(@JsonProperty("duration")String duration, @JsonProperty("registrationId")String registrationId, @JsonProperty("errorCode")StatusCode errorCode) {
- this.duration = duration;
- this.errorCode = errorCode;
- this.registrationId = registrationId;
- }
-
- public String getDuration() {
- return duration;
- }
-
- public String getRegistrationId() {
- return registrationId;
- }
-
- public StatusCode getErrorCode() {
- return errorCode;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/StatusCode.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/StatusCode.java
deleted file mode 100644
index d6538f69a..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/StatusCode.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class StatusCode {
- @JsonInclude
- protected String code;
- @JsonProperty(value = "reasonPhrase")
- protected String message;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String details;
-
- public StatusCode(String code, String message) {
- this.code = code;
- this.message = message;
- }
-
- public StatusCode(@JsonProperty("code") String code, @JsonProperty("reasonPhrase") String message, @JsonProperty("details") String details) {
- this.code = code;
- this.message = message;
- this.details = details;
- }
-
- public String getCode() {
- return code;
- }
-
- public String getMessage() {
- return message;
- }
-
- public String getDetails() {
- return details;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/SubscribeRequestV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/SubscribeRequestV2.java
deleted file mode 100644
index 45cf913ea..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/SubscribeRequestV2.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonFormat;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import org.openremote.manager.shared.ngsi.params.NotificationParams;
-import org.openremote.manager.shared.ngsi.params.SubscriptionParams;
-
-import java.util.Date;
-
-public class SubscribeRequestV2 {
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String id;
- @JsonInclude
- protected SubscriptionParams subject;
- @JsonInclude
- protected NotificationParams notification;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.S'Z'", timezone = "UTC")
- protected Date expires;
-
- public SubscribeRequestV2() {
- }
-
- public SubscribeRequestV2(@JsonProperty String id, @JsonProperty SubscriptionParams subject, @JsonProperty NotificationParams notification, @JsonProperty Date expires) {
- this.id = id;
- this.subject = subject;
- this.notification = notification;
- this.expires = expires;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public SubscriptionParams getSubject() {
- return subject;
- }
-
- public void setSubject(SubscriptionParams subject) {
- this.subject = subject;
- }
-
- public NotificationParams getNotification() {
- return notification;
- }
-
- public void setNotification(NotificationParams notification) {
- this.notification = notification;
- }
-
- public Date getExpires() {
- return expires;
- }
-
- public void setExpires(Date expires) {
- this.expires = expires;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/UpdateRequestV1.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/UpdateRequestV1.java
deleted file mode 100644
index 341f919a7..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/UpdateRequestV1.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-import java.util.List;
-
-public class UpdateRequestV1 {
- @JsonInclude
- protected List<ContextElement> contextElements;
-
- @JsonInclude
- protected ActionType updateAction;
-
- public UpdateRequestV1(List<ContextElement> contextElements, ActionType updateAction) {
- this.contextElements = contextElements;
- this.updateAction = updateAction;
- }
-
- public List<ContextElement> getContextElements() {
- return contextElements;
- }
-
- public ActionType getUpdateAction() {
- return updateAction;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/BasicEntityParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/BasicEntityParams.java
deleted file mode 100644
index e688eee89..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/BasicEntityParams.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-public class BasicEntityParams {
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String id;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String idPattern;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String type;
-
- public BasicEntityParams(String idParam, boolean isPattern) {
- if (isPattern) {
- this.idPattern = idParam;
- } else {
- this.id = idParam;
- }
- }
-
- public BasicEntityParams(String idParam, boolean isPattern, String type) {
- this(idParam, isPattern);
- this.type = type;
- }
-
- public String getId() {
- return id;
- }
-
- public String getIdPattern() {
- return idPattern;
- }
-
- public String getType() {
- return type;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/Condition.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/Condition.java
deleted file mode 100644
index d5693018b..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/Condition.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.databind.SerializerProvider;
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import com.fasterxml.jackson.databind.ser.std.StdSerializer;
-import org.openremote.manager.shared.ngsi.simplequery.Query;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-@JsonSerialize(using = Condition.ConditionSerialiser.class)
-public class Condition {
- public static class ConditionSerialiser extends StdSerializer<Condition> {
- public ConditionSerialiser() {
- this(null);
- }
-
- public ConditionSerialiser(Class<Condition> t) {
- super(t);
- }
-
- @Override
- public void serialize(Condition value, JsonGenerator gen, SerializerProvider provider) throws IOException {
- gen.writeStartObject();
- if (value.query != null) {
- gen.writeObjectFieldStart("expression");
- gen.writeObject(value.query);
- gen.writeEndObject();
- }
- gen.writeArrayFieldStart("attrs");
- for(String attr : value.attrs) {
- gen.writeString(attr);
- }
- gen.writeEndArray();
- gen.writeEndObject();
- }
- }
-
- // Unfortunately Jackson doesn't honour the always include for empty list (bug in Jackson https://github.com/FasterXML/jackson-databind/issues/1327)
- @JsonInclude(JsonInclude.Include.ALWAYS)
- protected List<String> attrs;
- @JsonProperty("expression")
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected Query query;
-
- public Condition() {
- attrs = new ArrayList<>();
- }
-
- public Condition(List<String> attributes) {
- this.attrs = attributes;
- }
-
- public Condition(Query query) {
- this.query = query;
- }
-
- public Condition(List<String> attributes, Query query) {
- this.attrs = attributes;
- this.query = query;
- }
-
- public List<String> getAttributes() {
- return attrs;
- }
-
- public Query getQuery() {
- return query;
- }
-
-
-// protected String[] getAttributesArr() { return attrs == null ? new String[0] : attrs.toArray(new String[0]); }
-//
-// @JsonProperty("attrs")
-// protected void setAttributesArr(String[] attrs) {
-// this.attrs = Arrays.asList(attrs);
-// }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityListParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityListParams.java
deleted file mode 100644
index f205e4489..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityListParams.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import org.openremote.manager.shared.ngsi.simplequery.Query;
-
-import javax.ws.rs.QueryParam;
-
-/**
- * A given entity have to match all the criteria to be retrieved (i.e. criteria are combined
- * in a logical AND way). Note that id and idPattern parameters are incompatible in the
- * same request.
- */
-public class EntityListParams {
-
- @QueryParam("id")
- public String[] id;
-
- @QueryParam("type")
- public String[] type;
-
- @QueryParam("idPattern")
- public String idPattern;
-
- @QueryParam("typePattern")
- public String typePattern;
-
- @QueryParam("q")
- public Query query;
-
- @QueryParam("georel")
- public String geoRel;
-
- @QueryParam("geometry")
- public String geometry;
-
- @QueryParam("coords")
- public String coords;
-
- @QueryParam("limit")
- public Long limit;
-
- @QueryParam("offset")
- public Long offset;
-
- @QueryParam("attrs")
- public String[] attributes;
-
- @QueryParam("orderBy")
- public String orderBy;
-
- @QueryParam("options")
- public EntityRepresentation options;
-
- public EntityListParams() {
- }
-
- public EntityListParams id(String... id) {
- idPattern = null;
- this.id = id;
- return this;
- }
-
- public EntityListParams type(String... type) {
- this.type = type;
- return this;
- }
-
- public EntityListParams idPattern(String idPattern) {
- this.id = null;
- this.idPattern = idPattern;
- return this;
- }
-
- public EntityListParams typePattern(String typePattern) {
- this.type = null;
- this.typePattern = typePattern;
- return this;
- }
-
- public EntityListParams query(Query query) {
- this.query = query;
- return this;
- }
-
- public EntityListParams geoRel(String geoRel) {
- this.geoRel = geoRel;
- return this;
- }
-
- public EntityListParams geometry(String geometry) {
- this.geometry = geometry;
- return this;
- }
-
- public EntityListParams coords(String coords) {
- this.coords = coords;
- return this;
- }
-
- public EntityListParams limit(Long limit) {
- this.limit = limit;
- return this;
- }
-
- public EntityListParams offset(Long offset) {
- this.offset = offset;
- return this;
- }
-
- public EntityListParams attributes(String... attributes) {
- this.attributes = attributes;
- return this;
- }
-
- public EntityListParams orderBy(String orderBy) {
- this.orderBy = orderBy;
- return this;
- }
-
- public EntityListParams options(EntityRepresentation options) {
- this.options = options;
- return this;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityParams.java
deleted file mode 100644
index 53d05997b..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityParams.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import javax.ws.rs.QueryParam;
-
-public class EntityParams {
-
- @QueryParam("type")
- public String type;
-
- @QueryParam("attrs")
- public String[] attributes;
-
- @QueryParam("options")
- public EntityRepresentation options;
-
- public EntityParams() {
- }
-
- public EntityParams type(String type) {
- this.type = type;
- return this;
- }
-
- public EntityParams attributes(String[] attributes) {
- this.attributes = attributes;
- return this;
- }
-
- public EntityParams options(EntityRepresentation options) {
- this.options = options;
- return this;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityRepresentation.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityRepresentation.java
deleted file mode 100644
index dd24b468e..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityRepresentation.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-public enum EntityRepresentation {
- keyValues,
- values,
- unique
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/HttpCustomParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/HttpCustomParams.java
deleted file mode 100644
index 579557c64..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/HttpCustomParams.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import javax.ws.rs.HttpMethod;
-import java.util.Map;
-
-public class HttpCustomParams extends HttpParams {
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected Map<String, String> headers;
- @JsonProperty("qs")
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected Map<String, String> parameters;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected HttpMethod method;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected String payload;
-
- public HttpCustomParams(@JsonProperty String url, @JsonProperty Map<String, String> headers, @JsonProperty("qs") Map<String, String> parameters, @JsonProperty HttpMethod method, @JsonProperty String payload) {
- super(url);
- this.headers = headers;
- this.parameters = parameters;
- this.method = method;
- this.payload = payload;
- }
-
- public HttpCustomParams(String url) {
- super(url);
- }
-
- public Map<String, String> getHeaders() {
- return headers;
- }
-
- public void setHeaders(Map<String, String> headers) {
- this.headers = headers;
- }
-
- public Map<String, String> getParameters() {
- return parameters;
- }
-
- public void setParameters(Map<String, String> parameters) {
- this.parameters = parameters;
- }
-
- public HttpMethod getMethod() {
- return method;
- }
-
- public void setMethod(HttpMethod method) {
- this.method = method;
- }
-
- public String getPayload() {
- return payload;
- }
-
- public void setPayload(String payload) {
- this.payload = payload;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/HttpParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/HttpParams.java
deleted file mode 100644
index 8ecf206a0..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/HttpParams.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-public class HttpParams {
- @JsonInclude
- protected String url;
-
- public HttpParams(String url) {
- this.url = url;
- }
-
- public String getUrl() {
- return url;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/NotificationParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/NotificationParams.java
deleted file mode 100644
index c1fd73688..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/NotificationParams.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.Date;
-import java.util.List;
-
-public class NotificationParams {
- @JsonProperty("attrs")
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected List<String> includeAttributes;
- @JsonProperty("exceptAttrs")
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected List<String> excludeAttributes;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected HttpParams http;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected HttpCustomParams httpCustom;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected Date lastNotification;
- @JsonInclude(JsonInclude.Include.NON_NULL)
- protected Integer timesSent;
-
- public NotificationParams() {
- }
-
- public void setIncludeAttributes(List<String> includeAttributes) {
- this.includeAttributes = includeAttributes;
- }
-
- public void setExcludeAttributes(List<String> excludeAttributes) {
- this.excludeAttributes = excludeAttributes;
- }
-
- public void setHttp(HttpParams http) {
- this.http = http;
- }
-
- public void setHttpCustom(HttpCustomParams httpCustom) {
- this.httpCustom = httpCustom;
- }
-
- public List<String> getIncludeAttributes() {
- return includeAttributes;
- }
-
- public List<String> getExcludeAttributes() {
- return excludeAttributes;
- }
-
- public HttpParams getHttp() {
- return http;
- }
-
- public HttpCustomParams getHttpCustom() {
- return httpCustom;
- }
-
- public Date getLastNotification() {
- return lastNotification;
- }
-
- public int getTimesSent() {
- return timesSent;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/SubscriptionParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/SubscriptionParams.java
deleted file mode 100644
index 1542fb382..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/SubscriptionParams.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.params;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class SubscriptionParams {
- @JsonInclude
- protected List<BasicEntityParams> entities;
- @JsonInclude
- protected Condition condition;
-
- public SubscriptionParams() {
- this.condition = new Condition();
- }
-
- public SubscriptionParams(BasicEntityParams entity) {
- this(entity, new Condition());
- }
-
- public SubscriptionParams(BasicEntityParams entity, Condition condition) {
- entities = new ArrayList<>();
- entities.add(entity);
- this.condition = condition;
- }
-
- public SubscriptionParams(List<BasicEntityParams> entities, Condition condition) {
- this.entities = entities;
- this.condition = condition;
- }
-
- public List<BasicEntityParams> getEntities() {
- return entities;
- }
-
- public void setEntities(List<BasicEntityParams> entities) {
- this.entities = entities;
- }
-
- public Condition getCondition() {
- return condition;
- }
-
- public void setCondition(Condition condition) {
- this.condition = condition;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/BinaryStatement.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/BinaryStatement.java
deleted file mode 100644
index a5c4645a9..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/BinaryStatement.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.simplequery;
-
-public class BinaryStatement extends Statement {
-
- public enum Operator {
- EQUAL("=="),
- UNEQUAL("!="),
- GREATER_THAN(">"),
- LESS_THAN("<"),
- GREATER_OR_EQUAL_THAN(">="),
- LESS_OR_EQUAL_THAN("<=");
-
- String op;
-
- Operator(String op) {
- this.op = op;
- }
-
- @Override
- public String toString() {
- return op;
- }
- }
-
- public BinaryStatement(String statement) {
- super(statement);
- }
-
- public BinaryStatement(String attributeName, Operator operator, QueryValue queryValue) {
- this(attributeName + operator + queryValue);
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/Query.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/Query.java
deleted file mode 100644
index 2bcbb1ed6..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/Query.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.simplequery;
-
-public class Query {
-
- public static final String STATEMENT_SEPARATOR = ";";
-
- public Statement[] statements;
-
- public Query() {
- }
-
- public Query(Statement... statements) {
- this.statements = statements;
- }
-
- public Query statements(Statement... statements) {
- this.statements = statements;
- return this;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- if (statements != null) {
- for (Statement statement : statements) {
- sb.append(statement).append(STATEMENT_SEPARATOR);
- }
- }
- if (sb.length()>0) {
- sb.deleteCharAt(sb.length()-1);
- }
- return sb.toString();
- }
-
- public static Query valueOf(String query) {
- if (query == null)
- return null;
- String[] split = query.split(STATEMENT_SEPARATOR);
- Statement[] statements = new Statement[split.length];
- for (int i = 0; i < statements.length; i++) {
- statements[i] = new Statement(split[i]);
- }
- return new Query(statements);
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/QueryValue.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/QueryValue.java
deleted file mode 100644
index 558f6201c..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/QueryValue.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.simplequery;
-
-public interface QueryValue {
-
- String SEPARATOR = ",";
- String SEPARATOR_QUOTE = "'";
- String RANGE = "..";
-
- @Override
- String toString();
-
- static QueryValue exact(Object value) {
- return new QueryValue() {
- @Override
- public String toString() {
- return quote(value.toString());
- }
- };
- }
-
- static QueryValue values(Object[] values) {
- String value = "";
- if (values != null) {
- StringBuilder sb = new StringBuilder();
- for (Object v : values) {
- sb.append(quote(v.toString()));
- sb.append(SEPARATOR);
- }
- if (sb.length() > 0)
- sb.deleteCharAt(sb.length() - 1);
- value = sb.toString();
- }
- final String finalValue = value;
- return new QueryValue() {
- @Override
- public String toString() {
- return finalValue;
- }
- };
- }
-
- static QueryValue range(Number min, Number max) {
- final String value = min + RANGE + max;
- return new QueryValue() {
- @Override
- public String toString() {
- return value;
- }
- };
- }
-
- // TODO Java8 Instant not supported on GWT, also no Dateformatter...
- static QueryValue rangeISO8601(String minTimestamp, String maxTimestamp) {
- final String value = minTimestamp+ RANGE + maxTimestamp;
- return new QueryValue() {
- @Override
- public String toString() {
- return value;
- }
- };
- }
-
- static String quote(String value) {
- if (value.contains(SEPARATOR_QUOTE))
- throw new UnsupportedOperationException(
- "Can't express query values containing " + SEPARATOR_QUOTE + ". No escape character has been specified in NGSIv2."
- );
-
- if (value.contains(SEPARATOR)) {
- return SEPARATOR_QUOTE + value + SEPARATOR_QUOTE;
- }
- return value;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/Statement.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/Statement.java
deleted file mode 100644
index b88cac8e1..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/Statement.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.simplequery;
-
-public class Statement {
-
- final protected String statement;
-
- public Statement(String statement) {
- this.statement = statement;
- }
-
- @Override
- public String toString() {
- return statement;
- }
-}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/UnaryStatement.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/UnaryStatement.java
deleted file mode 100644
index 18faf2df8..000000000
--- a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/simplequery/UnaryStatement.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2016, 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.manager.shared.ngsi.simplequery;
-
-public class UnaryStatement extends Statement {
-
- enum Operator {
- EXISTS(""),
- NOT_EXISTS("!");
-
- final protected String op;
-
- Operator(String op) {
- this.op = op;
- }
-
- @Override
- public String toString() {
- return op;
- }
- }
-
- public UnaryStatement(String statement) {
- super(statement);
- }
-
- public UnaryStatement(String attributeName, Operator operator) {
- this(operator + attributeName);
- }
-
-}
diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
index 0dcb360af..309982b53 100644
--- a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
@@ -9,9 +9,9 @@ import org.openremote.manager.server.asset.AssetService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.manager.server.setup.SetupService
import org.openremote.model.AttributeRef
-import org.openremote.model.AttributeValueChange
+import org.openremote.model.AttributeState
import org.openremote.model.Attributes
-import org.openremote.model.asset.ColorRGB
+import org.openremote.model.units.ColorRGB
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -46,20 +46,20 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
Proposal:
- 1. Receive AttributeValueChange on client API
+ 1. Receive AttributeState on client API
2. Handle security and verify the message is for a linked agent/thing/attribute in the asset database
- 3. Send the AttributeValueChange to the Protocol through ACTUATOR_TOPIC and trigger device/service call
+ 3. Send the AttributeState to the Protocol through ACTUATOR_TOPIC and trigger device/service call
4a. We assume that most protocol implementations are not using fire-and-forget but request/reply
- communication. Thus, an AttributeValueChange has no further consequences besides triggering an
+ communication. Thus, an AttributeState has no further consequences besides triggering an
actuator. We expect that a sensor "response" will let us know "soon" if the call was successful.
Only a sensor value change will result in an update of the asset database state. The window of
inconsistency we can accept depends on how "soon" a protocol typically responds.
4b. Alternatively, if the updated attribute is configured with the "forceUpdate" meta item, we write
- the new attribute value directly into the asset database after triggering the actuator. This flag
+ the new attribute state directly into the asset database after triggering the actuator. This flag
is useful if the protocol does not reflect actuator changes "immediately". For example, if we
send a value to a light dimmer actuator, does the light dimmer also have a sensor that responds
quickly with the new value? If the device/service does not reply to value changes, we can force
@@ -68,7 +68,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
4c. Should "forceUpdate" be the default behavior?
*/
- def light1DimmerChange = new AttributeValueChange(
+ def light1DimmerChange = new AttributeState(
new AttributeRef(managerDemoSetup.thingId, "light1Dimmer"), Json.create(66)
)
container.getService(MessageBrokerService.class).getProducerTemplate().sendBody(
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index c689eec37..d78b77d0b 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -4,12 +4,11 @@ import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.shared.asset.AssetResource
import org.openremote.model.Attributes
-import org.openremote.model.Metadata
+import org.openremote.model.Meta
import org.openremote.model.asset.Asset
import org.openremote.model.asset.ProtectedAssetInfo
import org.openremote.model.AttributeType
-import org.openremote.model.AttributeUnits
-import org.openremote.model.asset.AssetAttributeMeta
+import org.openremote.model.asset.AssetMeta
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import org.openremote.model.asset.AssetType
@@ -465,10 +464,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
protectedAttributes.get("currentTemperature")
protectedAttributes.get("currentTemperature").getType() == AttributeType.DECIMAL
protectedAttributes.get("currentTemperature").getValueAsDecimal() == 19.2d
- Metadata protectedMetadata = protectedAttributes.get("currentTemperature").getMetadata()
- protectedMetadata.all().length == 2
- protectedMetadata.first(AssetAttributeMeta.LABEL).getValueAsString() == "Current Temp"
- protectedMetadata.first(AssetAttributeMeta.READ_ONLY).getValueAsBoolean()
+ Meta protectedMeta = protectedAttributes.get("currentTemperature").getMeta()
+ protectedMeta.all().length == 2
+ protectedMeta.first(AssetMeta.LABEL).getValueAsString() == "Current Temp"
+ protectedMeta.first(AssetMeta.READ_ONLY).getValueAsBoolean()
ProtectedAssetInfo apartment2 = assetInfos[3]
apartment2.id == managerDemoSetup.apartment2Id
diff --git a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityModelTest.groovy b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityModelTest.groovy
deleted file mode 100644
index 8bba3b6f6..000000000
--- a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityModelTest.groovy
+++ /dev/null
@@ -1,134 +0,0 @@
-package org.openremote.test.ngsi
-
-import elemental.json.Json
-import elemental.json.JsonObject
-import org.openremote.manager.shared.ngsi.Entity
-import org.openremote.manager.shared.ngsi.KeyValueEntity
-import org.openremote.manager.shared.ngsi.Metadata
-import org.openremote.manager.shared.ngsi.Model
-import org.openremote.manager.shared.ngsi.ModelValidationError
-import spock.lang.Ignore
-import spock.lang.Specification
-
-// TODO We don't use NGSI anymore
-@Ignore
-class EntityModelTest extends Specification {
-
- def "Invalid characters in NGSI fields"() {
- expect: "number of validation errors"
- Model.validateField(fieldLabel).length == expectedNumberOfErrors;
- where: "field labels are"
- fieldLabel || expectedNumberOfErrors
- "SomeField" || 0
- "!@%^*()[]{}<>-=+.,;:|\\~_'`" || 0
- " " || 1
- "&" || 1
- "?" || 1
- "/" || 1
- }
-
- def "Parse NGSI entity roundtrip"() {
- given: "an NGSI entity JSON string"
- String jsonString = '''
- {
- "id": "Room1",
- "type": "Room",
- "pressure":{
- "type": "integer",
- "value": "720",
- "metadata":{}
- },
- "temperature":{
- "type": "float",
- "value": "26.5",
- "metadata":{
- "accuracy":{
- "type": "float",
- "value": "0.8"
- }
- }
- }
- }
- ''';
- when: "is parsed into JsonObject"
- JsonObject jsonEntity = Json.parse(jsonString);
- and: "is wrapped as an Entity"
- Entity entity = new Entity(jsonEntity);
- then: "it should be valid"
- validateEntity(entity);
-
- when: "Entity is serialized into JSON string"
- jsonString = entity.getJsonObject().toJson();
- and: "is parsed again into a JsonObject"
- jsonEntity = Json.parse(jsonString);
- and: "is wrapped again as an Entity"
- entity = new Entity(jsonEntity);
- then: "it should still be valid"
- validateEntity(entity);
- }
-
- void validateEntity(entity) {
- ModelValidationError[] errors = entity.validate();
- assert errors.length == 0;
- assert "Room1" == entity.getId();
- assert "Room" == entity.getType();
- assert entity.getAttributes().length == 2;
- assert entity.hasAttribute("pressure");
- assert entity.hasAttribute("temperature");
-
- def pressure = entity.getAttribute("pressure");
- assert pressure.getName().asNumber() == 720;
- assert pressure.getMetadata().all().length == 0;
-
- def temperature = entity.getAttribute("temperature");
- assert temperature.getName().asNumber() == new Double(26.5);
-
- Metadata temperatureMetadata = temperature.getMetadata();
- assert temperatureMetadata.getElements().length == 1;
- assert temperatureMetadata.getElement("accuracy").getType() == "float";
- assert temperatureMetadata.getElement("accuracy").getValue().asNumber() == new Double(0.8);
- }
-
- def "Parse NGSI key-value entity roundtrip"() {
- given: "an NGSI key-value entity JSON string"
- String jsonString = '''
- {
- "id": "Room1",
- "type": "Room",
- "pressure": "720",
- "temperature": "26.5"
- }
- ''';
- when: "is parsed into JsonObject"
- JsonObject jsonEntity = Json.parse(jsonString);
- and: "is wrapped as an KeyValueEntity"
- KeyValueEntity entity = new KeyValueEntity(jsonEntity);
- then: "it should be valid"
- validateKeyValueEntity(entity);
-
- when: "KeyValueEntity is serialized into JSON string"
- jsonString = entity.getJsonObject().toJson();
- and: "is parsed again into a JsonObject"
- jsonEntity = Json.parse(jsonString);
- and: "is wrapped again as an KeyValueEntity"
- entity = new KeyValueEntity(jsonEntity);
- then: "it should still be valid"
- validateKeyValueEntity(entity);
- }
-
- void validateKeyValueEntity(entity) {
- ModelValidationError[] errors = entity.validate();
- assert errors.length == 0;
- assert "Room1" == entity.getId();
- assert "Room" == entity.getType();
- assert entity.getAttributes().length == 2;
- assert entity.hasAttribute("pressure");
- assert entity.hasAttribute("temperature");
-
- def pressure = entity.getAttribute("pressure");
- assert pressure.getName().asNumber() == 720;
-
- def temperature = entity.getAttribute("temperature");
- assert temperature.getName().asNumber() == new Double(26.5);
- }
-}
\ No newline at end of file
diff --git a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovy
deleted file mode 100644
index ab6951906..000000000
--- a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovy
+++ /dev/null
@@ -1,213 +0,0 @@
-package org.openremote.test.ngsi
-
-import elemental.json.Json
-import org.openremote.manager.server.ngsi.EntityArrayMessageBodyConverter
-import org.openremote.manager.server.ngsi.EntityMessageBodyConverter
-import org.openremote.manager.server.ngsi.EntryPointMessageBodyConverter
-import org.openremote.manager.shared.ngsi.EntityResource
-import org.openremote.manager.shared.ngsi.Attribute
-import org.openremote.manager.shared.ngsi.Entity
-import org.openremote.manager.shared.ngsi.params.EntityListParams
-import org.openremote.manager.shared.ngsi.simplequery.BinaryStatement
-import org.openremote.manager.shared.ngsi.simplequery.Query
-import org.openremote.manager.shared.ngsi.simplequery.QueryValue
-import org.openremote.manager.shared.ngsi.AttributeType;
-import org.openremote.test.ContainerTrait
-import spock.lang.Ignore
-import spock.lang.Specification
-
-import javax.ws.rs.NotFoundException
-
-import static org.openremote.container.util.MapAccess.getString
-import static org.openremote.manager.server.setup.SetupService.DEMO_ADMIN_PASSWORD
-import static org.openremote.manager.server.setup.SetupService.DEMO_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.model.Constants.*;
-
-@Ignore
-class EntityResourceTest extends Specification implements ContainerTrait {
-
- def "Retrieve sample rooms"() {
- given: "the server container is started"
- def serverPort = findEphemeralPort();
- def container = startContainer(defaultConfig(serverPort), defaultServices())
-
- and: "an authenticated user"
- def realm = MASTER_REALM;
- def accessToken = authenticate(
- container,
- realm,
- KEYCLOAK_CLIENT_ID,
- MASTER_REALM_ADMIN_USER,
- getString(container.getConfig(), DEMO_ADMIN_PASSWORD, DEMO_ADMIN_PASSWORD_DEFAULT)
- ).token
-
- and: "a test client target"
- def client = createClient(container)
- .register(EntryPointMessageBodyConverter.class)
- .register(EntityMessageBodyConverter.class)
- .register(EntityArrayMessageBodyConverter.class)
- .build();
- def serverUri = serverUri(serverPort);
- def clientTarget = getClientTarget(client, serverUri, realm, accessToken);
-
- and: "the entity resource"
- def entityResource = clientTarget.proxy(EntityResource.class);
-
- when: "query with no restrictions"
- def entities = entityResource.getEntities(null, null);
- then: "there should be some result (we don't now how many entities total are in test data, at least 2)"
- entities.length >= 2
-
- when: "query with id restriction"
- entities = entityResource.getEntities(
- null,
- new EntityListParams().id("Room1")
- );
- then: "the result should match"
- entities.length == 1
- assertRoom(entities[0], "Room1", 21.3, "Office 123")
-
- when: "query with id pattern restriction"
- entities = entityResource.getEntities(
- null,
- new EntityListParams().idPattern("Room1.*")
- );
- then: "the result should match"
- assertRoom(entities[0], "Room1", 21.3, "Office 123")
-
- when: "query with type restrictions"
- entities = entityResource.getEntities(
- null,
- new EntityListParams().type("Room")
- );
- then: "the result should match"
- entities.length == 2
- assertRoom(entities[0], null, null, null);
- assertRoom(entities[1], null, null, null);
-
- when: "query with type restrictions"
- entities = entityResource.getEntities(
- null,
- new EntityListParams().type("Room")
- );
- then: "the result should match"
- entities.length == 2
- assertRoom(entities[0], null, null, null);
- assertRoom(entities[1], null, null, null);
-
- when: "query with query restrictions"
- entities = entityResource.getEntities(
- null,
- new EntityListParams().query(
- new Query(
- new BinaryStatement("label", BinaryStatement.Operator.EQUAL, QueryValue.exact("Office 123"))
- )
- )
- );
- then: "the result should match"
- entities.length == 1
- assertRoom(entities[0], "Room1", 21.3, "Office 123")
-
- and: "the server should be stopped"
- stopContainer(container);
- }
-
- boolean assertRoom(Entity room, String expectedId, Double expectedTemperature, String expectedLabel) {
- if (expectedId != null)
- assert room.getId() == expectedId;
- assert room.getType() == "Room"
-
- def temperature = room.getAttribute("temperature");
- assert temperature.getType() == AttributeType.FLOAT
- assert temperature.getMetadata() != null
- assert temperature.getMetadata().getElements().length == 0
- if (expectedTemperature)
- assert temperature.getValue().asNumber() == expectedTemperature
-
- def label = room.getAttribute("label")
- assert label.getType() == AttributeType.STRING
- assert label.getMetadata() != null
- assert label.getMetadata().getElements().length == 0
- if (expectedLabel)
- assert label.getValue().asString() == expectedLabel
- true
- }
-
- def "Create, update, and delete entity"() {
- given: "the server container is started"
- def serverPort = findEphemeralPort();
- def container = startContainer(defaultConfig(serverPort), defaultServices())
-
- and: "an authenticated user"
- def realm = MASTER_REALM;
- def accessToken = authenticate(
- container,
- realm,
- KEYCLOAK_CLIENT_ID,
- MASTER_REALM_ADMIN_USER,
- getString(container.getConfig(), DEMO_ADMIN_PASSWORD, DEMO_ADMIN_PASSWORD_DEFAULT)
- ).token
-
- and: "a test client target"
- def client = createClient(container)
- .register(EntryPointMessageBodyConverter.class)
- .register(EntityMessageBodyConverter.class)
- .register(EntityArrayMessageBodyConverter.class)
- .build();
- def serverUri = serverUri(serverPort);
- def clientTarget = getClientTarget(client, serverUri, realm, accessToken);
-
- and: "the entity resource"
- def entityResource = clientTarget.proxy(EntityResource.class);
-
- and: "a sample room"
- Entity room = new Entity(Json.createObject());
- room.setId("Room123");
- room.setType("Room");
- room.addAttribute(
- new Attribute("label", Json.createObject())
- .setType(AttributeType.STRING)
- .setValue(Json.create("Office 123"))
- )
- room.addAttribute(
- new Attribute("temperature", Json.createObject())
- .setType(AttributeType.FLOAT)
- .setValue(Json.create(20.5))
- );
-
- when: "the room is posted"
- entityResource.postEntity(null, room);
- and: "the new room has been retrieved"
- def createdRoom = entityResource.getEntity(null, room.getId(), null);
- Attribute temperature = createdRoom.getAttribute("temperature");
- then: "the room details should match"
- createdRoom.getId() == room.getId()
- createdRoom.getType() == room.getType()
- temperature.getValue().asNumber() == new Double(20.5)
-
- when: "the temperature is changed"
- temperature.setValue(Json.create(20.6))
- def roomPatch = new Entity(Json.createObject())
- roomPatch.addAttribute(temperature)
- and: "the room is updated"
- entityResource.patchEntityAttributes(null, createdRoom.getId(), roomPatch);
- and: "the updated room has been retrieved"
- def updatedRoom = entityResource.getEntity(null, room.getId(), null);
- def updatedTemperature = updatedRoom.getAttribute("temperature");
- then: "the room details should match"
- updatedRoom.getId() == room.getId()
- updatedRoom.getType() == room.getType()
- updatedRoom.getAttribute("label").getValue().asString() == "Office 123"
- updatedTemperature.getValue().asNumber() == new Double(20.6)
-
- when: "the room is deleted"
- entityResource.deleteEntity(null, room.getId());
- and: "the deleted room has been retrieved"
- entityResource.getEntity(null, room.getId(), null);
- then: "the room shouldn't exist"
- thrown NotFoundException
-
- and: "the server should be stopped"
- stopContainer(container);
- }
-}
diff --git a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovy
deleted file mode 100644
index f1135385b..000000000
--- a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovy
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright 2016, 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.test.ngsi
-
-import elemental.json.Json
-import org.openremote.manager.server.ngsi.EntityArrayMessageBodyConverter
-import org.openremote.manager.server.ngsi.EntityMessageBodyConverter
-import org.openremote.manager.server.ngsi.EntityProvider
-import org.openremote.manager.server.ngsi.EntityService
-import org.openremote.manager.server.ngsi.EntryPointMessageBodyConverter
-import org.openremote.model.Consumer
-import org.openremote.manager.shared.ngsi.Attribute
-import org.openremote.manager.shared.ngsi.AttributeType
-import org.openremote.manager.shared.ngsi.ContextEntity
-import org.openremote.manager.shared.ngsi.Entity
-import org.openremote.manager.shared.ngsi.EntityAttributeQuery
-import org.openremote.manager.shared.ngsi.params.BasicEntityParams
-import org.openremote.manager.shared.ngsi.EntityResource
-import org.openremote.manager.shared.ngsi.params.SubscriptionParams
-import org.openremote.test.ContainerTrait
-import spock.lang.Ignore
-import spock.lang.Specification
-import spock.util.concurrent.PollingConditions
-
-import javax.ws.rs.NotFoundException
-
-import static org.openremote.container.util.MapAccess.getString
-import static org.openremote.model.Constants.*;
-
-@Ignore
-class EntityServiceTest extends Specification implements ContainerTrait {
-
- def "Register Entity Provider"() {
- def requestedAttributes = [];
-
- given: "the server container is started"
- def serverPort = findEphemeralPort();
- def container = startContainer(defaultConfig(serverPort), defaultServices())
-
- and: "the entity service is retrieved"
- def entityService = container.getService(EntityService.class);
-
- when: "a mock entity provider with fake attrs is created"
- def fakeAttributes = [
- new Attribute("temperature", AttributeType.FLOAT, Json.create(10.1)),
- new Attribute("speed", AttributeType.INTEGER, Json.create(50))
- ];
-
- def entityProvider = new EntityProvider() {
- @Override
- List<Attribute> getAttributeValues(String entityId, List<String> attributes) {
- if (attributes.size() != 2 || !attributes.contains("temperature") || !attributes.contains("speed")) {
- return null;
- }
-
- requestedAttributes.addAll(attributes);
-
- return fakeAttributes;
- }
-
- @Override
- boolean setAttributeValues(String entityId, List<Attribute> attributes) {
- return false
- }
- }
-
- and: "the mock provider registers as a provider of a fake entity with the entity service"
- def result = entityService.registerEntityProvider("Car", "Car1", fakeAttributes, entityProvider);
-
- then: "the mock provider is registered"
- result == true;
-
- when: "an entity registered with the mock provider is requested"
- def entity = entityService.getContextBroker().getEntity("Car1", null);
-
- then: "the mock entity provider should have resolved the request"
- def conditions = new PollingConditions(timeout: 10)
-
- conditions.eventually {
- assert entity != null;
- }
-
- requestedAttributes.size() == 2;
- entity.getId() == "Car1";
- entity.getType() == "Car";
- entity.getAttributes().length == 2;
- Attribute tempAttr = Arrays.stream(entity.getAttributes())
- .filter({ a -> a.getName().equals("temperature") })
- .findFirst()
- .get();
- Attribute speedAttr = Arrays.stream(entity.getAttributes())
- .filter({ a -> a.getName().equals("speed") })
- .findFirst()
- .get();
- tempAttr != null;
- tempAttr.getType() == AttributeType.FLOAT;
- tempAttr.getValue().asString() == fakeAttributes[0].getValue().asString();
- speedAttr != null;
- speedAttr.getType() == AttributeType.INTEGER;
- speedAttr.getValue().asString() == fakeAttributes[1].getValue().asString();
-
- when: "provider is unregistered and previously registered entity is requested"
- entityService.unregisterEntityProvider("Car", "Car1", entityProvider);
- entity = entityService.getContextBroker().getEntity("Car1", null);
-
- then: "a 404 response should be received"
- thrown(NotFoundException)
-
- cleanup: "ensure mock provider is unregistered"
- entityService.unregisterEntityProvider("Car", "Car1", entityProvider);
-
- and: "the server should be stopped"
- stopContainer(container);
- }
-
- def "Auto Refresh Entity Provider"() {
- def requestedAttributes = [];
-
- given: "the server container is started"
- def serverPort = findEphemeralPort();
- def container = startContainer(defaultConfig(serverPort), defaultServices())
-
- and: "the entity service is retrieved"
- def entityService = container.getService(EntityService.class);
-
- when: "a mock entity provider with fake attrs is created"
- def fakeAttributes = [
- new Attribute("temperature", AttributeType.FLOAT, Json.create(10.1)),
- new Attribute("speed", AttributeType.INTEGER, Json.create(50))
- ];
-
- def entityProvider = new EntityProvider() {
- @Override
- List<Attribute> getAttributeValues(String entityId, List<String> attributes) {
- if (attributes.size() != 2 || !attributes.contains("temperature") || !attributes.contains("speed")) {
- return null;
- }
-
- requestedAttributes.addAll(attributes);
-
- return fakeAttributes;
- }
-
- @Override
- boolean setAttributeValues(String entityId, List<Attribute> attributes) {
- return false
- }
- }
-
- and: "the context provider refresh interval is set to 30s (minimum)"
- entityService.getRegistrationProvider().setRefreshInterval(30);
-
- and: "the mock provider registers as a provider of a fake entity with the entity service"
- def result = entityService.registerEntityProvider("Car", "Car1", fakeAttributes, entityProvider);
-
- then: "the mock provider is registered"
- result == true;
-
- when: "enough time passes that auto refresh would have occurred"
- Thread.sleep(35000);
-
- and: "an entity registered with the mock provider is requested"
- def response = entityService.getContextBrokerV1().queryContext(
- new EntityAttributeQuery([new ContextEntity("Car", "Car1", false)], null)
- );
-
- then: "the mock entity provider should have resolved the request"
- def conditions = new PollingConditions(timeout: 10)
-
- conditions.eventually {
- assert response.contextResponses != null;
- }
-
- requestedAttributes.size() == 2;
- response.contextResponses.size() == 1;
- response.contextResponses.get(0).getContextElement().getId() == "Car1";
- response.contextResponses.get(0).getContextElement().getType() == "Car";
- response.contextResponses.get(0).getContextElement().getAttributes().size() == 2;
- Attribute tempAttr = response.contextResponses.get(0).getContextElement().getAttributes()
- .stream()
- .filter({ a -> a.getName().equals("temperature") })
- .findFirst()
- .get();
- Attribute speedAttr = response.contextResponses.get(0).getContextElement().getAttributes()
- .stream()
- .filter({ a -> a.getName().equals("speed") })
- .findFirst()
- .get();
- tempAttr != null;
- tempAttr.getType() == AttributeType.FLOAT;
- tempAttr.getValue().asString() == fakeAttributes[0].getValue().asString();
- speedAttr != null;
- speedAttr.getType() == AttributeType.INTEGER;
- speedAttr.getValue().asString() == fakeAttributes[1].getValue().asString();
-
- cleanup: "ensure mock provider is unregistered"
- entityService.unregisterEntityProvider("Car", "Car1", entityProvider);
-
- and: "the server should be stopped"
- stopContainer(container);
- }
-
- def "Register Entity Listener"() {
- def receivedEntities = [];
-
- given: "the server container is started"
- def serverPort = findEphemeralPort();
- def container = startContainer(defaultConfig(serverPort), defaultServices())
-
- and: "an authenticated user"
- def realm = MASTER_REALM;
- def accessToken = authenticate(
- container,
- realm,
- KEYCLOAK_CLIENT_ID,
- MASTER_REALM_ADMIN_USER,
- getString(container.getConfig(), DEMO_ADMIN_PASSWORD, DEMO_ADMIN_PASSWORD_DEFAULT)
- ).token
-
- and: "a test client target"
- def client = createClient(container)
- .register(EntryPointMessageBodyConverter.class)
- .register(EntityMessageBodyConverter.class)
- .register(EntityArrayMessageBodyConverter.class)
- .build();
- def serverUri = serverUri(serverPort);
- def clientTarget = getClientTarget(client, serverUri, realm, accessToken);
-
- and: "the entity resource"
- def entityResource = clientTarget.proxy(EntityResource.class);
-
- and: "the entity service"
- def entityService = container.getService(EntityService.class);
-
- and: "a sample entity"
- Entity car = new Entity(Json.createObject());
- car.setId("Car123");
- car.setType("Car");
- car.addAttribute(
- new Attribute("make", Json.createObject())
- .setType(AttributeType.STRING)
- .setValue(Json.create("AUDI"))
- )
- car.addAttribute(
- new Attribute("model", Json.createObject())
- .setType(AttributeType.STRING)
- .setValue(Json.create("RS6"))
- );
- car.addAttribute(
- new Attribute("speed", Json.createObject())
- .setType(AttributeType.INTEGER)
- .setValue(Json.create(250))
- );
-
- when: "the entity is posted"
- entityResource.postEntity(null, car);
-
- and: "a mock entity listener is created"
- def listener = new Consumer<Entity[]>() {
- @Override
- void accept(Entity[] entities) throws Exception {
- receivedEntities.addAll(entities);
- }
- }
-
- and: "the mock listener registers with the entity service for all IDs starting with Car"
- def subscription = new SubscriptionParams();
- subscription.setEntities(
- [new BasicEntityParams("Car.*", true)]
- );
- def result = entityService.registerEntityListener(listener, subscription);
-
- then: "the mock listener is registered"
- result == true;
-
- and: "the mock listener should have been notified"
- def conditions = new PollingConditions(timeout: 10)
-
- conditions.eventually {
- assert receivedEntities.size() == 1;
- }
-
- when: "the car speed is modified"
- def speed = car.getAttribute("speed");
- speed.setValue(Json.create(0))
- def carPatch = new Entity(Json.createObject())
- carPatch.addAttribute(speed)
-
- and: "the car is updated"
- entityResource.patchEntityAttributes(null, car.getId(), carPatch);
-
- then: "the mock listener should have been notified"
- conditions.eventually {
- assert receivedEntities.size() == 2;
- }
-
- when: "the mock listener is unregistered"
- entityService.unregisterEntityListener(listener);
-
- and: "the car speed is modified"
- speed.setValue(Json.create(60))
- carPatch = new Entity(Json.createObject())
- carPatch.addAttribute(speed)
-
- and: "the car is updated"
- entityResource.patchEntityAttributes(null, car.getId(), carPatch);
-
- then: "the mock listener should not have been notified"
- Thread.sleep(5000);
- receivedEntities.size() == 2;
-
- cleanup: "ensure mock listener is unregistered"
- if (entityService != null)
- entityService.unregisterEntityListener(listener);
- if (entityResource != null && car != null)
- entityResource.deleteEntity(null, car.getId());
-
- and: "the server should be stopped"
- stopContainer(container);
- }
-
- def "Auto Refresh Entity Listener"() {
- def receivedEntities = [];
-
- given: "the server container is started"
- def serverPort = findEphemeralPort();
- def container = startContainer(defaultConfig(serverPort), defaultServices())
-
- and: "an authenticated user"
- def realm = MASTER_REALM;
- def accessToken = authenticate(
- container,
- realm,
- KEYCLOAK_CLIENT_ID,
- MASTER_REALM_ADMIN_USER,
- getString(container.getConfig(), DEMO_ADMIN_PASSWORD, DEMO_ADMIN_PASSWORD_DEFAULT)
- ).token
-
- and: "a test client target"
- def client = createClient(container)
- .register(EntryPointMessageBodyConverter.class)
- .register(EntityMessageBodyConverter.class)
- .register(EntityArrayMessageBodyConverter.class)
- .build();
- def serverUri = serverUri(serverPort);
- def clientTarget = getClientTarget(client, serverUri, realm, accessToken);
-
- and: "the entity resource"
- def entityResource = clientTarget.proxy(EntityResource.class);
-
- and: "the entity service"
- def entityService = container.getService(EntityService.class);
-
- and: "a sample entity"
- Entity car = new Entity(Json.createObject());
- car.setId("Car123");
- car.setType("Car");
- car.addAttribute(
- new Attribute("make", Json.createObject())
- .setType(AttributeType.STRING)
- .setValue(Json.create("AUDI"))
- )
- car.addAttribute(
- new Attribute("model", Json.createObject())
- .setType(AttributeType.STRING)
- .setValue(Json.create("RS6"))
- );
- car.addAttribute(
- new Attribute("speed", Json.createObject())
- .setType(AttributeType.INTEGER)
- .setValue(Json.create(250))
- );
-
- when: "the entity is posted"
- entityResource.postEntity(null, car);
-
- and: "a mock entity listener is created"
- def listener = new Consumer<Entity[]>() {
- @Override
- void accept(Entity[] entities) throws Exception {
- receivedEntities.addAll(entities);
- }
- }
-
- and: "the entity listener refresh interval is set to 30s (minimum)"
- entityService.getSubscriptionProvider().setRefreshInterval(30);
-
- and: "the mock listener registers with the entity service for all IDs starting with Car"
- def subscription = new SubscriptionParams();
- subscription.setEntities(
- [new BasicEntityParams("Car.*", true)]
- );
- def result = entityService.registerEntityListener(listener, subscription);
-
- then: "the mock listener is registered"
- result == true;
-
- and: "the mock listener should have been notified"
- def conditions = new PollingConditions(timeout: 15)
-
- conditions.eventually {
- assert receivedEntities.size() == 1;
- }
-
- when: "enough time passes that auto refresh would have occurred"
- Thread.sleep(35000);
-
- and: "the car speed is modified"
- def speed = car.getAttribute("speed");
- speed.setValue(Json.create(0))
- def carPatch = new Entity(Json.createObject())
- carPatch.addAttribute(speed)
-
- and: "the car is updated"
- entityResource.patchEntityAttributes(null, car.getId(), carPatch);
-
- then: "the mock listener should have been notified"
- conditions.eventually {
- assert receivedEntities.size() == 2;
- }
-
- cleanup: "ensure mock listener is unregistered"
- if (entityService != null)
- entityService.unregisterEntityListener(listener);
- if (entityResource != null && car != null)
- entityResource.deleteEntity(null, car.getId());
-
- and: "the server should be stopped"
- stopContainer(container);
- }
-}
diff --git a/model/src/main/java/org/openremote/model/AbstractValueHolder.java b/model/src/main/java/org/openremote/model/AbstractValueHolder.java
index 315f5b300..b31985b32 100644
--- a/model/src/main/java/org/openremote/model/AbstractValueHolder.java
+++ b/model/src/main/java/org/openremote/model/AbstractValueHolder.java
@@ -21,6 +21,11 @@ package org.openremote.model;
import elemental.json.*;
+/**
+ * Base class for all model classes which have to internally store data in a
+ * {@link JsonObject} that has a <code>value</code> field that accepts any
+ * {@link JsonValue}.
+ */
public abstract class AbstractValueHolder<T extends AbstractValueHolder> {
final protected JsonObject jsonObject;
@@ -38,7 +43,7 @@ public abstract class AbstractValueHolder<T extends AbstractValueHolder> {
}
public Integer getValueAsInteger() {
- return hasValue()? Integer.valueOf(getValue_TODO_BUG_IN_JAVASCRIPT().asString()) : null;
+ return hasValue() ? Integer.valueOf(getValue_TODO_BUG_IN_JAVASCRIPT().asString()) : null;
}
public Double getValueAsDecimal() {
@@ -71,34 +76,67 @@ public abstract class AbstractValueHolder<T extends AbstractValueHolder> {
jsonObject.remove("value");
}
- public T setValue(String value) {
- return setValue(Json.create(value));
+ public T setValueAsString(String value) {
+ return setValue(value == null ? Json.createNull() : Json.create(value));
+ }
+
+ public T setValueAsInteger(Integer value) {
+ return setValue(value == null ? Json.createNull() : Json.create(value));
}
- public T setValue(int value) {
- return setValue(Json.create(value));
+ public T setValueAsDecimal(Double value) {
+ return setValue(value == null ? Json.createNull() : Json.create(value));
}
- public T setValue(double value) {
- return setValue(Json.create(value));
+ public T setValueAsBoolean(Boolean value) {
+ return setValue(value == null ? Json.createNull() : Json.create(value));
}
- public T setValue(boolean value) {
- return setValue(Json.create(value));
+ public T setValueAsObject(JsonObject value) {
+ return setValue(value == null ? Json.createNull() : value);
}
- // You can NOT perform null-checks on whatever is returned here!
- // TODO https://github.com/gwtproject/gwt/issues/9484
+ public T setValueAsArray(JsonArray value) {
+ return setValue(value == null ? Json.createNull() : value);
+ }
+
+ /**
+ * You can NOT perform null-checks on whatever is returned here!
+ * <p>
+ * TODO https://github.com/gwtproject/gwt/issues/9484
+ */
public JsonValue getValue_TODO_BUG_IN_JAVASCRIPT() {
return hasValue() ? jsonObject.get("value") : Json.createNull();
}
@SuppressWarnings("unchecked")
public T setValue(JsonValue value) {
+
+ if (value == null) {
+ value = Json.createNull();
+ } else if (value.getType() != JsonType.NULL){
+ // TODO Avoid unboxing problems by parsing again https://github.com/gwtproject/gwt/issues/9484
+ value = Json.instance().parse(value.toJson());
+ }
+
+ if (!isValidValue(value)) {
+ String typeString = value != null ? value.getType().name() : "null";
+ String valueString = value != null ? value.toJson() : "null";
+ throw new IllegalArgumentException("Invalid value of type " + typeString + ": " + valueString);
+ }
+
jsonObject.put("value", value);
+
return (T) this;
}
+ /**
+ * Override to implement constraints.
+ */
+ protected boolean isValidValue(JsonValue value) {
+ return true;
+ }
+
@Override
public String toString() {
return jsonObject.toJson();
diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.java
index 381909977..b806c2a55 100644
--- a/model/src/main/java/org/openremote/model/Attribute.java
+++ b/model/src/main/java/org/openremote/model/Attribute.java
@@ -20,10 +20,15 @@
package org.openremote.model;
import elemental.json.*;
-import org.openremote.model.asset.AssetAttributeMeta;
+import org.openremote.model.asset.AssetMeta;
import java.util.NoSuchElementException;
+/**
+ * Convenience overlay API for {@link JsonObject}.
+ * <p>
+ * Modifies the given or an empty object.
+ */
public class Attribute extends AbstractValueHolder<Attribute> {
protected String name;
@@ -52,6 +57,13 @@ public class Attribute extends AbstractValueHolder<Attribute> {
setValue(value);
}
+ @Override
+ protected boolean isValidValue(JsonValue value) {
+ return getType() != null
+ ? getType().isValid(value)
+ : super.isValidValue(value);
+ }
+
public void setName(String name) {
this.name = name;
}
@@ -78,40 +90,40 @@ public class Attribute extends AbstractValueHolder<Attribute> {
return this;
}
- public boolean hasMetadata() {
- return jsonObject.hasKey("metadata");
+ public boolean hasMeta() {
+ return jsonObject.hasKey("meta");
}
- public Metadata getMetadata() {
- return hasMetadata() ? new Metadata(jsonObject.getArray("metadata")) : null;
+ public Meta getMeta() {
+ return hasMeta() ? new Meta(jsonObject.getArray("meta")) : null;
}
- public Attribute setMetadata(Metadata metadata) {
- if (metadata != null) {
- jsonObject.put("metadata", metadata.getJsonArray());
- } else if (jsonObject.hasKey("metadata")) {
- jsonObject.remove("metadata");
+ public Attribute setMeta(Meta meta) {
+ if (meta != null) {
+ jsonObject.put("meta", meta.getJsonArray());
+ } else if (jsonObject.hasKey("meta")) {
+ jsonObject.remove("meta");
}
return this;
}
- public boolean hasMetaItem(AssetAttributeMeta assetAttributeMeta) {
- return hasMetaItem(assetAttributeMeta.getName());
+ public boolean hasMetaItem(AssetMeta assetMeta) {
+ return hasMetaItem(assetMeta.getName());
}
public boolean hasMetaItem(String name) {
- return hasMetadata() && getMetadata().contains(name);
+ return hasMeta() && getMeta().contains(name);
}
- public MetadataItem firstMetaItem(AssetAttributeMeta assetAttributeMeta) {
- return firstMetaItem(assetAttributeMeta.getName());
+ public MetaItem firstMetaItem(AssetMeta assetMeta) {
+ return firstMetaItem(assetMeta.getName());
}
- public MetadataItem firstMetaItem(String name) {
- return hasMetaItem(name) ? getMetadata().first(name) : null;
+ public MetaItem firstMetaItem(String name) {
+ return hasMetaItem(name) ? getMeta().first(name) : null;
}
- public MetadataItem firstMetaItemOrThrow(String name) throws NoSuchElementException {
+ public MetaItem firstMetaItemOrThrow(String name) throws NoSuchElementException {
if (!hasMetaItem(name))
throw new NoSuchElementException("Missing item: " + name);
return firstMetaItem(name);
diff --git a/model/src/main/java/org/openremote/model/AttributeRef.java b/model/src/main/java/org/openremote/model/AttributeRef.java
index 5c7ab68d2..5fb503697 100644
--- a/model/src/main/java/org/openremote/model/AttributeRef.java
+++ b/model/src/main/java/org/openremote/model/AttributeRef.java
@@ -22,6 +22,10 @@ package org.openremote.model;
import elemental.json.Json;
import elemental.json.JsonArray;
+/**
+ * A reference to an entity (using only its identifier value) and an {@link Attribute}
+ * (using the attribute name) of that entity.
+ */
public class AttributeRef {
final protected String entityId;
diff --git a/model/src/main/java/org/openremote/model/AttributeValueChange.java b/model/src/main/java/org/openremote/model/AttributeState.java
similarity index 88%
rename from model/src/main/java/org/openremote/model/AttributeValueChange.java
rename to model/src/main/java/org/openremote/model/AttributeState.java
index a294fc0a0..f2ded6479 100644
--- a/model/src/main/java/org/openremote/model/AttributeValueChange.java
+++ b/model/src/main/java/org/openremote/model/AttributeState.java
@@ -21,12 +21,15 @@ package org.openremote.model;
import elemental.json.JsonValue;
-public class AttributeValueChange {
+/**
+ * The desired or current or past state of an {@link AttributeRef}.
+ */
+public class AttributeState {
final protected AttributeRef attributeRef;
final protected JsonValue value;
- public AttributeValueChange(AttributeRef attributeRef, JsonValue value) {
+ public AttributeState(AttributeRef attributeRef, JsonValue value) {
this.attributeRef = attributeRef;
this.value = value;
}
diff --git a/model/src/main/java/org/openremote/model/AttributeSchedule.java b/model/src/main/java/org/openremote/model/AttributeStates.java
similarity index 61%
rename from model/src/main/java/org/openremote/model/AttributeSchedule.java
rename to model/src/main/java/org/openremote/model/AttributeStates.java
index f83b75d5c..110fc1cd3 100644
--- a/model/src/main/java/org/openremote/model/AttributeSchedule.java
+++ b/model/src/main/java/org/openremote/model/AttributeStates.java
@@ -22,23 +22,23 @@ package org.openremote.model;
import java.util.LinkedList;
/**
- * Apply a sequence of <code>[AttributeValueChange, Seconds]</code> items, each lasting for the given duration.
+ * A sequence of <code>[{@link AttributeState}, Seconds]</code> items, each lasting for the given duration.
* <p>
- * Optionally, repeat the schedule when the last item has expired.
+ * Optionally, repeat the states when the last item has expired.
*/
-public class AttributeSchedule extends LinkedList<AttributeSchedule.Item> {
+public class AttributeStates extends LinkedList<AttributeStates.Item> {
public class Item {
- final AttributeValueChange attributeValueChange;
+ final AttributeState attributeState;
final int delayNextSeconds;
- public Item(AttributeValueChange attributeValueChange, int delayNextSeconds) {
- this.attributeValueChange = attributeValueChange;
+ public Item(AttributeState attributeState, int delayNextSeconds) {
+ this.attributeState = attributeState;
this.delayNextSeconds = delayNextSeconds;
}
- public AttributeValueChange getAttributeValueChange() {
- return attributeValueChange;
+ public AttributeState getAttributeState() {
+ return attributeState;
}
public int getDelayNextSeconds() {
@@ -48,18 +48,11 @@ public class AttributeSchedule extends LinkedList<AttributeSchedule.Item> {
final protected boolean repeat;
- public AttributeSchedule(boolean repeat) {
+ public AttributeStates(boolean repeat) {
this.repeat = repeat;
}
public boolean isRepeat() {
return repeat;
}
-
- /**
- * TODO
- */
- public void apply(Function<AttributeRef, Attribute> attributeResolver) {
- throw new UnsupportedOperationException("TODO Implement this");
- }
}
diff --git a/model/src/main/java/org/openremote/model/AttributeType.java b/model/src/main/java/org/openremote/model/AttributeType.java
index f14443ee9..69e9e8802 100644
--- a/model/src/main/java/org/openremote/model/AttributeType.java
+++ b/model/src/main/java/org/openremote/model/AttributeType.java
@@ -20,8 +20,18 @@
package org.openremote.model;
import elemental.json.JsonType;
+import elemental.json.JsonValue;
+/**
+ * The base type of an {@link Attribute}, how its {@link elemental.json.JsonValue} should be
+ * interpreted when working with an attribute (e.g. when testing, rendering, or editing
+ * the value).
+ *
+ * Additional constraints and integrity rules upon attribute values can be declared by
+ * adding arbitrary {@link Meta} to an {@link Attribute}.
+ */
public enum AttributeType {
+
STRING("String", JsonType.STRING),
OBJECT("Object", JsonType.OBJECT),
INTEGER("Integer", JsonType.NUMBER),
@@ -49,6 +59,10 @@ public enum AttributeType {
return jsonType;
}
+ public boolean isValid(JsonValue value) {
+ return value == null || value.getType().equals(JsonType.NULL) || value.getType().equals(getJsonType());
+ }
+
public static AttributeType fromValue(String value) {
if (value != null && !"".equals(value)) {
AttributeType[] values = AttributeType.values();
diff --git a/model/src/main/java/org/openremote/model/Metadata.java b/model/src/main/java/org/openremote/model/Meta.java
similarity index 63%
rename from model/src/main/java/org/openremote/model/Metadata.java
rename to model/src/main/java/org/openremote/model/Meta.java
index 332409d96..ddf4260d7 100644
--- a/model/src/main/java/org/openremote/model/Metadata.java
+++ b/model/src/main/java/org/openremote/model/Meta.java
@@ -22,25 +22,25 @@ package org.openremote.model;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
-import org.openremote.model.asset.AssetAttributeMeta;
+import org.openremote.model.asset.AssetMeta;
import java.util.ArrayList;
import java.util.List;
/**
- * An array of {@link MetadataItem} elements.
+ * An array of {@link MetaItem} elements.
*
* Note that duplicate item names are allowed for multi-valued elements.
*/
-public class Metadata {
+public class Meta {
final protected JsonArray jsonArray;
- public Metadata() {
+ public Meta() {
this(Json.createArray());
}
- public Metadata(JsonArray jsonArray) {
+ public Meta(JsonArray jsonArray) {
this.jsonArray = jsonArray;
}
@@ -48,47 +48,51 @@ public class Metadata {
return jsonArray;
}
- public MetadataItem[] all() {
- List<MetadataItem> list = asList();
- return list.toArray(new MetadataItem[list.size()]);
+ public int size() {
+ return getJsonArray().length();
}
- public MetadataItem[] get(String name) {
- List<MetadataItem> list = asList(
+ public MetaItem[] all() {
+ List<MetaItem> list = asList();
+ return list.toArray(new MetaItem[list.size()]);
+ }
+
+ public MetaItem[] get(String name) {
+ List<MetaItem> list = asList(
item -> item.getName().equals(name)
);
- return list.toArray(new MetadataItem[list.size()]);
+ return list.toArray(new MetaItem[list.size()]);
}
- public MetadataItem get(int index) {
+ public MetaItem get(int index) {
return index > 0 && index < jsonArray.length()
- ? new MetadataItem(jsonArray.getObject(index))
+ ? new MetaItem(jsonArray.getObject(index))
: null;
}
- public MetadataItem first(AssetAttributeMeta assetAttributeMeta) {
- return first(assetAttributeMeta.getName());
+ public MetaItem first(AssetMeta assetMeta) {
+ return first(assetMeta.getName());
}
- public MetadataItem first(String name) {
- List<MetadataItem> list = asList();
- for (MetadataItem item : list) {
+ public MetaItem first(String name) {
+ List<MetaItem> list = asList();
+ for (MetaItem item : list) {
if (item.getName().equals(name))
return item;
}
return null;
}
- public boolean contains(AssetAttributeMeta assetAttributeMeta) {
- return contains(assetAttributeMeta.getName());
+ public boolean contains(AssetMeta assetMeta) {
+ return contains(assetMeta.getName());
}
public boolean contains(String name) {
return first(name) != null;
}
- public int indexOf(MetadataItem item) {
- List<MetadataItem> list = asList();
+ public int indexOf(MetaItem item) {
+ List<MetaItem> list = asList();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(item.getName()))
return i;
@@ -96,40 +100,40 @@ public class Metadata {
return -1;
}
- public Metadata add(MetadataItem item) {
+ public Meta add(MetaItem item) {
jsonArray.set(jsonArray.length(), item.getJsonObject());
return this;
}
- public Metadata removeAll(String name) {
+ public Meta removeAll(String name) {
for (int i = 0; i < jsonArray.length(); i++) {
JsonObject jsonObject = jsonArray.getObject(i);
- MetadataItem item = new MetadataItem(jsonObject);
+ MetaItem item = new MetaItem(jsonObject);
if (name.equals(item.getName()))
jsonArray.remove(i);
}
return this;
}
- public Metadata remove(int index) {
+ public Meta remove(int index) {
if (index >= 0 && index < jsonArray.length())
jsonArray.remove(index);
return this;
}
- public Metadata copy() {
- return new Metadata((JsonArray) Json.parse(getJsonArray().toJson()));
+ public Meta copy() {
+ return new Meta((JsonArray) Json.parse(getJsonArray().toJson()));
}
- protected List<MetadataItem> asList() {
+ protected List<MetaItem> asList() {
return asList(null);
}
- protected List<MetadataItem> asList(Function<MetadataItem, Boolean> filter) {
- List<MetadataItem> list = new ArrayList<>();
+ protected List<MetaItem> asList(Function<MetaItem, Boolean> filter) {
+ List<MetaItem> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JsonObject jsonObject = jsonArray.getObject(i);
- MetadataItem item = new MetadataItem(jsonObject);
+ MetaItem item = new MetaItem(jsonObject);
if (filter == null) {
list.add(item);
} else if (filter.apply(item)) {
diff --git a/model/src/main/java/org/openremote/model/MetadataItem.java b/model/src/main/java/org/openremote/model/MetaItem.java
similarity index 67%
rename from model/src/main/java/org/openremote/model/MetadataItem.java
rename to model/src/main/java/org/openremote/model/MetaItem.java
index 5de2ad341..53604c10d 100644
--- a/model/src/main/java/org/openremote/model/MetadataItem.java
+++ b/model/src/main/java/org/openremote/model/MetaItem.java
@@ -22,31 +22,36 @@ package org.openremote.model;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
-import org.openremote.model.asset.AssetAttributeMeta;
+import org.openremote.model.asset.AssetMeta;
-public class MetadataItem extends AbstractValueHolder<MetadataItem> {
+/**
+ * A named arbitrary {@link JsonValue}.
+ * <p>
+ * Name should be a URI, thus avoiding collisions and representing "ownership" of the meta item.
+ */
+public class MetaItem extends AbstractValueHolder<MetaItem> {
- public MetadataItem() {
+ public MetaItem() {
this(Json.createObject());
}
- public MetadataItem(JsonObject jsonObject) {
+ public MetaItem(JsonObject jsonObject) {
super(jsonObject);
}
- public MetadataItem(AssetAttributeMeta assetAttributeMeta) {
- this(assetAttributeMeta, null);
+ public MetaItem(AssetMeta assetMeta) {
+ this(assetMeta, null);
}
- public MetadataItem(String name) {
+ public MetaItem(String name) {
this(name, null);
}
- public MetadataItem(AssetAttributeMeta assetAttributeMeta, JsonValue value) {
- this(assetAttributeMeta.getName(), value);
+ public MetaItem(AssetMeta assetMeta, JsonValue value) {
+ this(assetMeta.getName(), value);
}
- public MetadataItem(String name, JsonValue value) {
+ public MetaItem(String name, JsonValue value) {
super(Json.createObject());
setName(name);
setValue(value);
@@ -60,13 +65,13 @@ public class MetadataItem extends AbstractValueHolder<MetadataItem> {
return jsonObject.hasKey("name") ? jsonObject.get("name").asString() : null;
}
- public MetadataItem setName(String name) {
+ public MetaItem setName(String name) {
jsonObject.put("name", name);
return this;
}
- public MetadataItem copy() {
- return new MetadataItem(Json.parse(getJsonObject().toJson()));
+ public MetaItem copy() {
+ return new MetaItem(Json.parse(getJsonObject().toJson()));
}
public boolean isValid() {
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index 605c2509d..c54f72fab 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -29,19 +29,144 @@ import java.util.Date;
import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;
import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;
+// @formatter:off
/**
* The main model class of this software.
* <p>
* An asset is an identifiable item in a composite relationship with other assets. This tree
* of assets can be managed through a <code>null</code> {@link #parentId} property for root
- * items, and a valid parent identifier for sub-items.
+ * assets, and a valid parent identifier for sub-assets.
* <p>
- * Each asset has dynamically typed optional attributes with an underlying
- * {@link elemental.json.Json} object model. Use the {@link org.openremote.model.Attributes}
+ * An asset is stored in and therefore access-controlled through a {@link #realm}.
+ * <p>
+ * The {@link #createdOn} value is Unix time.
+ * <p>
+ * The {@link #type} of the asset is an arbitrary string, it should be a URI, thus avoiding
+ * collisions and representing "ownership" of asset type. Well-known asset types handled by
+ * the core platform are defined in {@link AssetType}, third-party extensions can defined
+ * their own asset types.
+ * <p>
+ * An asset may have dynamically-typed {@link #attributes} with an underlying
+ * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.Attributes}
* class to work with this API.
* <p>
- * The location of an asset is stored as a pair of LNG/LAT coordinates.
+ * The {@link #path} is a list of parent asset identifiers, starting with the root of the
+ * asset tree.
+ * <p>
+ * The {@link #coordinates} are a pair of LNG/LAT values with the location of the asset.
+ * <p>
+ * Example JSON representation of an asset tree:
+ * <pre>{@code
+ * {
+ "id": "0oI7Gf_kTh6WyRJFUTr8Lg",
+ "version": 0,
+ "realm": "customerA",
+ "createdOn": 1489042784142,
+ "name": "Smart Home",
+ "type": "urn:openremote:asset:building",
+ "path": [
+ "0oI7Gf_kTh6WyRJFUTr8Lg"
+ ],
+ "coordinates": [
+ 5.469751699216005,
+ 51.44760787406028
+ ]
+}
+ * }</pre>
+ * <pre>{@code
+{
+ "id": "B0x8ZOqZQHGjq_l0RxAJBA",
+ "version": 0,
+ "realm": "customerA",
+ "createdOn": 1489042784148,
+ "name": "Apartment 1",
+ "type": "urn:openremote:asset:residence",
+ "parentId": "0oI7Gf_kTh6WyRJFUTr8Lg",
+ "path": [
+ "0oI7Gf_kTh6WyRJFUTr8Lg",
+ "B0x8ZOqZQHGjq_l0RxAJBA"
+ ],
+ "coordinates": [
+ 5.469751699216005,
+ 51.44760787406028
+ ]
+}
+ * }</pre>
+ * <pre>{@code
+{
+ "id": "bzlRiJmSSMCl8HIUt9-lMg",
+ "version": 0,
+ "realm": "customerA",
+ "createdOn": 1489042784157,
+ "name": "Livingroom",
+ "type": "urn:openremote:asset:room",
+ "parentId": "B0x8ZOqZQHGjq_l0RxAJBA",
+ "path": [
+ "0oI7Gf_kTh6WyRJFUTr8Lg",
+ "B0x8ZOqZQHGjq_l0RxAJBA",
+ "bzlRiJmSSMCl8HIUt9-lMg"
+ ],
+ "coordinates": [
+ 5.469751699216005,
+ 51.44760787406028
+ ]
+}
+ * }</pre>
+ * <pre>{@code
+{
+ "id": "W7GV_lFeQVyHLlgHgE3dEQ",
+ "version": 0,
+ "realm": "customerA",
+ "createdOn": 1489042784164,
+ "name": "Livingroom Thermostat",
+ "type": "urn:openremote:asset:thing",
+ "parentId": "bzlRiJmSSMCl8HIUt9-lMg",
+ "path": [
+ "0oI7Gf_kTh6WyRJFUTr8Lg",
+ "B0x8ZOqZQHGjq_l0RxAJBA",
+ "bzlRiJmSSMCl8HIUt9-lMg",
+ "W7GV_lFeQVyHLlgHgE3dEQ"
+ ],
+ "coordinates": [
+ 5.460315214821094,
+ 51.44541688237109
+ ],
+ "attributes": {
+ "currentTemperature": {
+ "meta": [
+ {
+ "name": "urn:openremote:asset:meta:label",
+ "value": "Current Temp"
+ },
+ {
+ "name": "urn:openremote:asset:meta:protected",
+ "value": true
+ },
+ {
+ "name": "urn:openremote:asset:meta:readOnly",
+ "value": true
+ },
+ {
+ "name": "urn:openremote:foo:bar",
+ "value": "FOO"
+ },
+ {
+ "name": "urn:thirdparty:bar",
+ "value": "BAR"
+ }
+ ],
+ "type": "Decimal",
+ "value": 19.2
+ },
+ "somethingPrivate": {
+ "type": "String",
+ "value": "Foobar"
+ }
+ }
+}
+ * }</pre>
*/
+// @formatter:on
@MappedSuperclass
@Table(name = "ASSET")
public class Asset {
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
similarity index 81%
rename from model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java
rename to model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 06b6f2c41..7001ba2d3 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -22,23 +22,21 @@ package org.openremote.model.asset;
import elemental.json.JsonType;
import elemental.json.JsonValue;
import org.openremote.model.Attribute;
-import org.openremote.model.Constants;
-import org.openremote.model.MetadataItem;
+import org.openremote.model.MetaItem;
+import org.openremote.model.units.AttributeUnits;
-import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
-import static org.openremote.model.Constants.NAMESPACE;
/**
* Asset attribute meta item name is an arbitrary string. It should be URI. This enum contains
- * the well-known URIs for functionality we want to depend on in our platform.
+ * the well-known URIs for functionality we can depend on in our platform.
* <p>
* TODO https://people.eecs.berkeley.edu/~arka/papers/buildsys2015_metadatasurvey.pdf
*/
-public enum AssetAttributeMeta {
+public enum AssetMeta {
/**
* Links the attribute to an agent, connecting it to a sensor and/or actuator.
@@ -102,7 +100,7 @@ public enum AssetAttributeMeta {
/**
* Indicates the units (data sub-type) of the attribute value (should be a valid
- * {@link org.openremote.model.AttributeUnits} string representation)
+ * {@link AttributeUnits} string representation).
*/
UNITS(ASSET_META_NAMESPACE + ":units", new Access(true, false, true), JsonType.STRING),
@@ -115,7 +113,7 @@ public enum AssetAttributeMeta {
final protected Access access;
final protected JsonType valueType;
- AssetAttributeMeta(String name, Access access, JsonType valueType) {
+ AssetMeta(String name, Access access, JsonType valueType) {
this.name = name;
this.access = access;
this.valueType = valueType;
@@ -133,38 +131,38 @@ public enum AssetAttributeMeta {
return valueType;
}
- public static AssetAttributeMeta[] editable() {
- List<AssetAttributeMeta> list = new ArrayList<>();
- for (AssetAttributeMeta meta : values()) {
+ public static AssetMeta[] editable() {
+ List<AssetMeta> list = new ArrayList<>();
+ for (AssetMeta meta : values()) {
if (meta.getAccess().editable)
list.add(meta);
}
- return list.toArray(new AssetAttributeMeta[list.size()]);
+ return list.toArray(new AssetMeta[list.size()]);
}
public static Boolean isEditable(String name) {
- for (AssetAttributeMeta assetAttributeMeta : editable()) {
- if (assetAttributeMeta.getName().equals(name))
- return assetAttributeMeta.getAccess().editable;
+ for (AssetMeta assetMeta : editable()) {
+ if (assetMeta.getName().equals(name))
+ return assetMeta.getAccess().editable;
}
return null;
}
- public static AssetAttributeMeta byName(String name) {
- for (AssetAttributeMeta assetAttributeMeta : values()) {
- if (assetAttributeMeta.getName().equals(name))
- return assetAttributeMeta;
+ public static AssetMeta byName(String name) {
+ for (AssetMeta assetMeta : values()) {
+ if (assetMeta.getName().equals(name))
+ return assetMeta;
}
return null;
}
- public static MetadataItem createMetadataItem(AssetAttributeMeta name, JsonValue value) {
- return new MetadataItem(name.getName(), value);
+ public static MetaItem createMetaItem(AssetMeta name, JsonValue value) {
+ return new MetaItem(name.getName(), value);
}
- public static MetadataItem getFirst(Attribute attribute, AssetAttributeMeta meta) {
+ public static MetaItem getFirst(Attribute attribute, AssetMeta meta) {
return attribute.hasMetaItem(meta.getName())
- ? attribute.getMetadata().first(meta.getName())
+ ? attribute.getMeta().first(meta.getName())
: null;
}
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 ed2242e33..924ca12d4 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetType.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java
@@ -27,7 +27,7 @@ import java.util.ArrayList;
import java.util.List;
import static org.openremote.model.Constants.ASSET_NAMESPACE;
-import static org.openremote.model.asset.AssetAttributeMeta.*;
+import static org.openremote.model.asset.AssetMeta.*;
import static org.openremote.model.AttributeType.INTEGER;
import static org.openremote.model.AttributeType.STRING;
@@ -43,35 +43,32 @@ public enum AssetType {
TENANT(ASSET_NAMESPACE + ":tenant", false, null),
- // TODO Arbitrary group of assets? Semantics?
- GROUP(ASSET_NAMESPACE + ":group", true, null),
-
BUILDING(ASSET_NAMESPACE + ":building", true, new Attributes().put(
new Attribute("area", INTEGER)
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Surface area")))
- .add(createMetadataItem(DESCRIPTION, Json.create("Floor area of building measured in m²")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/area")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Surface area")))
+ .add(createMetaItem(DESCRIPTION, Json.create("Floor area of building measured in m²")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/area")))
),
new Attribute("geoStreet", STRING)
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Street")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Street")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet")))
),
new Attribute("geoPostalCode", AttributeType.INTEGER)
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Postal Code")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Postal Code")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode")))
),
new Attribute("geoCity", STRING)
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("City")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("City")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity")))
),
new Attribute("geoCountry", STRING)
- .setMetadata(new Metadata()
- .add(createMetadataItem(LABEL, Json.create("Country")))
- .add(createMetadataItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))
+ .setMeta(new Meta()
+ .add(createMetaItem(LABEL, Json.create("Country")))
+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))
)
).getJsonObject()),
diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java b/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java
index 810e75c0b..216a947de 100644
--- a/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java
+++ b/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java
@@ -22,19 +22,19 @@ package org.openremote.model.asset;
import elemental.json.JsonObject;
import org.openremote.model.Attribute;
import org.openremote.model.Attributes;
-import org.openremote.model.Metadata;
-import org.openremote.model.MetadataItem;
+import org.openremote.model.Meta;
+import org.openremote.model.MetaItem;
import java.util.Date;
import static org.openremote.model.Constants.NAMESPACE;
-import static org.openremote.model.asset.AssetAttributeMeta.PROTECTED;
+import static org.openremote.model.asset.AssetMeta.PROTECTED;
/**
* Contains protected asset properties such as realm, name, creation timestamp, type,
* parent identifier, and location of an {@link Asset}, as well as all protected
- * attributes, and their protected metadata (see {@link AssetAttributeMeta#PROTECTED},
- * {@link AssetAttributeMeta.Access}).
+ * attributes, and their protected metadata (see {@link AssetMeta#PROTECTED},
+ * {@link AssetMeta.Access}).
* <p>
* Note that third-party metadata items (not in the
* {@link org.openremote.model.Constants#NAMESPACE}) are never included on
@@ -48,29 +48,32 @@ public class ProtectedAssetInfo extends AssetInfo {
for (Attribute attribute : attributes.get()) {
// An attribute must have the PROTECTED flag to be included
- MetadataItem protectedItem = attribute.firstMetaItem(PROTECTED);
- if (protectedItem != null && protectedItem.getValueAsBoolean()) {
- Attribute protectedAttribute = new Attribute(attribute.getName(), attribute.getJsonObject());
-
- // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included
- if (protectedAttribute.hasMetadata()) {
- Metadata protectedMetadata = new Metadata();
- for (MetadataItem metadataItem : protectedAttribute.getMetadata().all()) {
- if (metadataItem.getName().startsWith(NAMESPACE)) {
- AssetAttributeMeta wellKnownMeta = AssetAttributeMeta.byName(metadataItem.getName());
- if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {
- protectedMetadata.add(
- new MetadataItem(metadataItem.getName(), metadataItem.getValue_TODO_BUG_IN_JAVASCRIPT())
- );
- }
- }
- }
- if (protectedMetadata.getJsonArray().length() > 0)
- protectedAttribute.setMetadata(protectedMetadata);
- }
+ MetaItem protectedItem = attribute.firstMetaItem(PROTECTED);
+ if (protectedItem == null || !protectedItem.getValueAsBoolean())
+ continue;
+
+ Attribute protectedAttribute = new Attribute(attribute.getName(), attribute.getJsonObject());
+ filteredAttributes.put(protectedAttribute);
+
+ if (!protectedAttribute.hasMeta())
+ continue;
- filteredAttributes.put(protectedAttribute);
+ // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included
+ Meta protectedMeta = new Meta();
+ for (MetaItem metaItem : protectedAttribute.getMeta().all()) {
+ if (!metaItem.getName().startsWith(NAMESPACE))
+ continue;
+
+ AssetMeta wellKnownMeta = AssetMeta.byName(metaItem.getName());
+ if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {
+ protectedMeta.add(
+ new MetaItem(metaItem.getName(), metaItem.getValue_TODO_BUG_IN_JAVASCRIPT())
+ );
+ }
}
+ if (protectedMeta.size() > 0)
+ protectedAttribute.setMeta(protectedMeta);
+
}
return filteredAttributes.getJsonObject();
}
diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java b/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
index d159073dc..61366a98d 100644
--- a/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
+++ b/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
@@ -28,7 +28,7 @@ import static org.openremote.model.Constants.NAMESPACE;
* <p>
* If a user has linked assets, it's a <em>restricted</em> user. Such a user can only
* access its assigned assets and their protected data, and it has a limited
- * set of client operations available, see {@link AssetAttributeMeta.Access}:
+ * set of client operations available, see {@link AssetMeta.Access}:
* <ul>
* <li>
* When a restricted user client loads asset data, only protected asset details are included.
diff --git a/model/src/main/java/org/openremote/model/asset/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/ProtocolConfiguration.java
index 6bb52ab14..82a788710 100644
--- a/model/src/main/java/org/openremote/model/asset/ProtocolConfiguration.java
+++ b/model/src/main/java/org/openremote/model/asset/ProtocolConfiguration.java
@@ -23,13 +23,14 @@ import elemental.json.Json;
import elemental.json.JsonObject;
import org.openremote.model.Attribute;
import org.openremote.model.AttributeType;
+import org.openremote.model.Meta;
import java.util.Locale;
/**
* Agent attributes can be named protocol configurations, the value is a protocol URN.
* <p>
- * Configuration details are managed as {@link org.openremote.model.Metadata} of the attribute.
+ * Configuration details are managed as {@link Meta} of the attribute.
*/
public class ProtocolConfiguration extends Attribute {
diff --git a/model/src/main/java/org/openremote/model/asset/ThingAttribute.java b/model/src/main/java/org/openremote/model/asset/ThingAttribute.java
index 224c646d7..446ca6957 100644
--- a/model/src/main/java/org/openremote/model/asset/ThingAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/ThingAttribute.java
@@ -34,8 +34,8 @@ public class ThingAttribute extends Attribute {
}
static public AttributeRef getAgentLink(Attribute attribute) {
- JsonArray array = attribute.hasMetaItem(AssetAttributeMeta.AGENT_LINK)
- ? attribute.firstMetaItem(AssetAttributeMeta.AGENT_LINK).getValueAsArray()
+ JsonArray array = attribute.hasMetaItem(AssetMeta.AGENT_LINK)
+ ? attribute.firstMetaItem(AssetMeta.AGENT_LINK).getValueAsArray()
: null;
if (array == null || array.length() != 2)
return null;
diff --git a/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java b/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java
index a28137b29..cd81586fe 100644
--- a/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java
+++ b/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java
@@ -2,7 +2,7 @@ package org.openremote.model.datapoint;
import elemental.json.JsonValue;
import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeValueChange;
+import org.openremote.model.AttributeState;
import javax.persistence.Entity;
import javax.persistence.Table;
@@ -14,8 +14,8 @@ public class AssetDatapoint extends Datapoint {
public AssetDatapoint() {
}
- public AssetDatapoint(AttributeValueChange attributeValueChange) {
- super(attributeValueChange);
+ public AssetDatapoint(AttributeState attributeState) {
+ super(attributeState);
}
public AssetDatapoint(AttributeRef attributeRef, JsonValue value) {
diff --git a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
index 6075a5f30..3bbd959a0 100644
--- a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
+++ b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
@@ -19,14 +19,12 @@
*/
package org.openremote.model.datapoint;
-import elemental.json.JsonObject;
import elemental.json.JsonValue;
import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeValueChange;
+import org.openremote.model.AttributeState;
import javax.persistence.Column;
import javax.persistence.Id;
-import javax.persistence.IdClass;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
@@ -60,8 +58,8 @@ public abstract class Datapoint implements Serializable {
public Datapoint() {
}
- public Datapoint(AttributeValueChange attributeValueChange) {
- this(attributeValueChange.getAttributeRef(), attributeValueChange.getValue());
+ public Datapoint(AttributeState attributeState) {
+ this(attributeState.getAttributeRef(), attributeState.getValue());
}
public Datapoint(AttributeRef attributeRef, JsonValue value) {
diff --git a/model/src/main/java/org/openremote/model/AttributeUnits.java b/model/src/main/java/org/openremote/model/units/AttributeUnits.java
similarity index 53%
rename from model/src/main/java/org/openremote/model/AttributeUnits.java
rename to model/src/main/java/org/openremote/model/units/AttributeUnits.java
index 475a1a039..e4c26efd2 100644
--- a/model/src/main/java/org/openremote/model/AttributeUnits.java
+++ b/model/src/main/java/org/openremote/model/units/AttributeUnits.java
@@ -1,55 +1,126 @@
-/*
- * Copyright 2016, 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;
-
-public enum AttributeUnits {
- TIMESTAMP, // Unix epoch timestamp
- DATETIME, // ISO 8601, e.g. "2012-04-23T18:25:43.511Z"
- COLOR_RGB, // RGB integers
- COLOR_ARGB, // ARGB integers
- COLOR_HEX, // Hex value e.g. #FFFFFF
- TEMPERATURE_CELCIUS,
- TEMPERATURE_KELVIN,
- TEMPERATURE_FAHRENHEIT,
- DISTANCE_M,
- DISTANCE_CM,
- DISTANCE_MM,
- DISTANCE_IN,
- DISTANCE_FT,
- DISTANCE_YARD,
- CO2_PPM,
- CO2_PERCENTAGE,
- HUMIDITY_PERCENTAGE,
- HUMIDITY_GPCM, // Grams per cubic metre
- POWER_WATTS,
- POWER_KILOWATT,
- POWER_MEGAWATT,
- CHARGE_PERCENTAGE,
- CHARGE_KWH,
- PERCENTAGE,
- ENERGY_KWH,
- ENERGY_JOULE,
- ENERGY_MEGAJOULE,
- FLOW_LPM, // Litre per minute
- FLOW_CMPS, // Cubic metres per second
- FLOW_SCCM, // Standard cubic centimetres per minute
- FLOW_CFPS, // Cubic feet per second
- FLOW_GPM, // Gallons per minute
-}
+/*
+ * Copyright 2016, 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.units;
+
+/**
+ * The well-known attribute units (attribute sub-type) we can depend on
+ * in our platform. Together with the {@link org.openremote.model.AttributeType}
+ * of an {@link org.openremote.model.Attribute}, you can use units in attribute
+ * metadata to discriminate rendering, testing, and editing of attribute values.
+ */
+public enum AttributeUnits {
+
+ /**
+ * Unix epoch timestamp
+ */
+ TIMESTAMP,
+
+ /**
+ * ISO 8601, e.g. <code>2012-04-23T18:25:43.511Z</code>
+ */
+ DATETIME,
+
+ /**
+ * RGB integers
+ */
+ COLOR_RGB,
+
+ /**
+ * ARGB integers
+ */
+ COLOR_ARGB,
+
+ /**
+ * HTML Hex Value, e.g. <code>#ffffff</code>
+ */
+ COLOR_HEX,
+
+ TEMPERATURE_CELCIUS,
+
+ TEMPERATURE_KELVIN,
+
+ TEMPERATURE_FAHRENHEIT,
+
+ DISTANCE_M,
+
+ DISTANCE_CM,
+
+ DISTANCE_MM,
+
+ DISTANCE_IN,
+
+ DISTANCE_FT,
+
+ DISTANCE_YARD,
+
+ CO2_PPM,
+
+ CO2_PERCENTAGE,
+
+ HUMIDITY_PERCENTAGE,
+
+ /**
+ * Grams per cubic metre
+ */
+ HUMIDITY_GPCM,
+
+ POWER_WATTS,
+
+ POWER_KILOWATT,
+
+ POWER_MEGAWATT,
+
+ CHARGE_PERCENTAGE,
+
+ CHARGE_KWH,
+
+ PERCENTAGE,
+
+ ENERGY_KWH,
+
+ ENERGY_JOULE,
+
+ ENERGY_MEGAJOULE,
+
+ /**
+ * Litre per minute
+ */
+ FLOW_LPM,
+
+ /**
+ * Cubic metres per second
+ */
+ FLOW_CMPS,
+
+ /**
+ * Standard cubic centimetres per minute
+ */
+ FLOW_SCCM,
+
+ /**
+ * Cubic feet per second
+ */
+ FLOW_CFPS,
+
+ /**
+ * Gallons per minute
+ */
+ FLOW_GPM,
+}
diff --git a/model/src/main/java/org/openremote/model/asset/ColorRGB.java b/model/src/main/java/org/openremote/model/units/ColorRGB.java
similarity index 81%
rename from model/src/main/java/org/openremote/model/asset/ColorRGB.java
rename to model/src/main/java/org/openremote/model/units/ColorRGB.java
index ffe72bb99..7ec6d76ee 100644
--- a/model/src/main/java/org/openremote/model/asset/ColorRGB.java
+++ b/model/src/main/java/org/openremote/model/units/ColorRGB.java
@@ -17,10 +17,10 @@
* 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;
+package org.openremote.model.units;
import elemental.json.Json;
-import elemental.json.JsonObject;
+import elemental.json.JsonArray;
public class ColorRGB {
@@ -34,11 +34,11 @@ public class ColorRGB {
this.blue = blue;
}
- public ColorRGB(JsonObject jsonObject) {
+ public ColorRGB(JsonArray jsonArray) {
this(
- (int)jsonObject.get("red").asNumber(),
- (int)jsonObject.get("green").asNumber(),
- (int)jsonObject.get("blue").asNumber()
+ (int)jsonArray.get(0).asNumber(),
+ (int)jsonArray.get(1).asNumber(),
+ (int)jsonArray.get(2).asNumber()
);
}
@@ -54,12 +54,12 @@ public class ColorRGB {
return blue;
}
- public JsonObject asJsonValue() {
- JsonObject object = Json.createObject();
- object.put("red", Json.create(getRed()));
- object.put("green", Json.create(getGreen()));
- object.put("blue", Json.create(getBlue()));
- return object;
+ public JsonArray asJsonValue() {
+ JsonArray array = Json.createArray();
+ array.set(0, Json.create(getRed()));
+ array.set(1, Json.create(getGreen()));
+ array.set(2, Json.create(getBlue()));
+ return array;
}
public ColorRGB red(int red) {