Skip to content

armgit / core

Public Imported from GitHub
0

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

Implemented Context Provider functionality (NGSI9 Orion v1 and proposed v2)

Rich Turner6eaa16f36bc5
diff --git a/agent/src/main/java/org/openremote/agent/Availability.java b/agent/src/main/java/org/openremote/agent/Availability.java
new file mode 100644
index 000000000..6231dc7ac
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/Availability.java
@@ -0,0 +1,26 @@
+/*
+ * 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.agent;
+
+public enum Availability {
+ UNKNOWN,
+ NOT_FOUND,
+ AVAILABLE
+}
diff --git a/agent/src/main/java/org/openremote/agent/ConnectionState.java b/agent/src/main/java/org/openremote/agent/ConnectionState.java
new file mode 100644
index 000000000..9766458db
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/ConnectionState.java
@@ -0,0 +1,27 @@
+/*
+ * 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.agent;
+
+public enum ConnectionState {
+ UNKNOWN,
+ CONNECTING,
+ CONNECTED,
+ DISCONNECTED
+}
diff --git a/agent/src/main/java/org/openremote/agent/Connector.java b/agent/src/main/java/org/openremote/agent/Connector.java
new file mode 100644
index 000000000..ca560394c
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/Connector.java
@@ -0,0 +1,96 @@
+/*
+ * 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.agent;
+
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+
+/**
+ * Interface for agent connectors that is used to connect and communicate with agents
+ * in an agnostic way.
+ */
+public interface Connector {
+ /**
+ * Write a value to a specific device resource
+ * @param deviceUri
+ * @param resourceUri
+ * @param value
+ * @return
+ */
+ CompletableFuture<Boolean> writeValue(String deviceUri, String resourceUri, String value);
+
+ /**
+ * Async read value from a specific device resource
+ * @param deviceUri
+ * @param resourceUri
+ * @return
+ */
+ CompletableFuture<String> readValue(String deviceUri, String resourceUri);
+
+ /**
+ * Async read values of multiple resources from a specific device
+ * @param deviceUri
+ * @param resourceUris
+ * @return
+ */
+ CompletableFuture<Map<String,String>> readValues(String deviceUri, String[] resourceUris);
+
+ /**
+ * Async availability check (doesn't mean that the agent is connected but it is available
+ * @return
+ */
+ CompletableFuture<Boolean> getAvailability();
+
+ /**
+ * Get the current connection state
+ * @return
+ */
+ CompletableFuture<ConnectionState> getConnectionState();
+
+ /**
+ * Add a connection state change listener
+ * @param callback
+ * @return
+ */
+ long addConnectionListener(Consumer<ConnectionState> callback);
+
+ /**
+ * Remove an existing connection listerner
+ * @param listenerId
+ */
+ void removeConnectionListener(long listenerId);
+
+ /**
+ * Add a value listener for a specific device resource; requires the resource to actively push
+ * value changes; support is agent/protocol/resource dependent
+ * @param deviceUri
+ * @param resourceUri
+ * @param callback
+ * @return Handler ID (needed for removing the listener)
+ */
+ long addValueListener(String deviceUri, String resourceUri, Consumer<String> callback);
+
+ /**
+ * Remove an existing value listener
+ * @param handerId
+ */
+ void removeValueListener(long handerId);
+}
diff --git a/agent/src/main/java/org/openremote/agent/ConnectorFactory.java b/agent/src/main/java/org/openremote/agent/ConnectorFactory.java
new file mode 100644
index 000000000..63a78e53e
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/ConnectorFactory.java
@@ -0,0 +1,38 @@
+/*
+ * 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.agent;
+
+import org.jboss.marshalling.Pair;
+import org.openremote.manager.shared.agent.Agent;
+
+/**
+ * Singleton factory for creating instrances of a particular agent connector type
+ */
+public interface ConnectorFactory {
+ Connector createConnector(Agent agent);
+
+ Pair<Boolean, String> validateAgent(Agent agent);
+
+ void disposeConnector(Connector connector);
+
+ String getType();
+
+ String getDisplayName();
+}
diff --git a/agent/src/main/java/org/openremote/agent/controller2/Controller2Connector.java b/agent/src/main/java/org/openremote/agent/controller2/Controller2Connector.java
new file mode 100644
index 000000000..dea01b83f
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/controller2/Controller2Connector.java
@@ -0,0 +1,74 @@
+/*
+ * 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.agent.controller2;
+
+import org.openremote.agent.ConnectionState;
+import org.openremote.agent.Connector;
+
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+
+public class Controller2Connector implements Connector {
+ @Override
+ public CompletableFuture<Boolean> writeValue(String deviceUri, String resourceUri, String value) {
+ return null;
+ }
+
+ @Override
+ public CompletableFuture<String> readValue(String deviceUri, String resourceUri) {
+ return null;
+ }
+
+ @Override
+ public CompletableFuture<Map<String, String>> readValues(String deviceUri, String[] resourceUris) {
+ return null;
+ }
+
+ @Override
+ public CompletableFuture<Boolean> getAvailability() {
+ return null;
+ }
+
+ @Override
+ public CompletableFuture<ConnectionState> getConnectionState() {
+ return null;
+ }
+
+ @Override
+ public long addConnectionListener(Consumer<ConnectionState> callback) {
+ return 0;
+ }
+
+ @Override
+ public void removeConnectionListener(long listenerId) {
+
+ }
+
+ @Override
+ public long addValueListener(String deviceUri, String resourceUri, Consumer<String> callback) {
+ return 0;
+ }
+
+ @Override
+ public void removeValueListener(long handerId) {
+
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/controller2/Controller2ConnectorFactory.java b/agent/src/main/java/org/openremote/agent/controller2/Controller2ConnectorFactory.java
new file mode 100644
index 000000000..6620b06e5
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/controller2/Controller2ConnectorFactory.java
@@ -0,0 +1,52 @@
+/*
+ * 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.agent.controller2;
+
+import org.jboss.marshalling.Pair;
+import org.openremote.agent.Connector;
+import org.openremote.agent.ConnectorFactory;
+import org.openremote.manager.shared.agent.Agent;
+
+public class Controller2ConnectorFactory implements ConnectorFactory {
+ @Override
+ public Connector createConnector(Agent agent) {
+ return new Controller2Connector();
+ }
+
+ @Override
+ public Pair<Boolean, String> validateAgent(Agent agent) {
+ return null;
+ }
+
+ @Override
+ public void disposeConnector(Connector connector) {
+ // No cleanup needed just let it be destroyed
+ }
+
+ @Override
+ public String getType() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayName() {
+ return null;
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java b/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java
index fdfb84b7a..e1d9653f6 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/SampleDataService.java
@@ -29,9 +29,10 @@ import org.openremote.container.ContainerService;
import org.openremote.container.security.AuthForm;
import org.openremote.container.security.IdentityService;
import org.openremote.manager.server.assets.AssetsService;
-import org.openremote.manager.server.assets.ContextBrokerResource;
+import org.openremote.manager.server.assets.ContextBrokerV2Resource;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.ngsi.Attribute;
+import org.openremote.manager.shared.ngsi.AttributeType;
import org.openremote.manager.shared.ngsi.Entity;
import rx.Observable;
@@ -111,32 +112,23 @@ public class SampleDataService implements ContainerService {
room1.setId("Room1");
room1.setType("Room");
room1.addAttribute(
- new Attribute("temperature", Json.createObject())
- .setType("float")
- .setValue(Json.create(21.3))
+ new Attribute("temperature", AttributeType.FLOAT, Json.create(21.3))
).addAttribute(
- new Attribute("label", Json.createObject())
- .setType("string")
- .setValue(Json.create("Office 123"))
+ new Attribute("label", AttributeType.STRING, Json.create("Office 123"))
);
Entity room2 = new Entity(Json.createObject());
room2.setId("Room2");
room2.setType("Room");
room2.addAttribute(
- new Attribute("temperature", Json.createObject())
- .setType("float")
- .setValue(Json.create(22.1))
+ new Attribute("temperature", AttributeType.FLOAT, Json.create(22.1))
).addAttribute(
- new Attribute("label", Json.createObject())
- .setType("string")
- .setValue(Json.create("Office 456"))
+ new Attribute("label", AttributeType.STRING, Json.create("Office 456"))
);
- ContextBrokerResource ngsiService = assetsService.getContextBroker();
+ ContextBrokerV2Resource ngsiService = assetsService.getContextBroker();
fromCallable(() -> ngsiService.getEntities(null))
- .map(Entity::from)
.flatMap(Observable::from)
.flatMap(entity -> fromCallable(() -> ngsiService.deleteEntity(entity.getId())))
.toList().toBlocking().single();
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
new file mode 100644
index 000000000..9c646ed3a
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
@@ -0,0 +1,57 @@
+/*
+ * 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.agent;
+
+import org.openremote.agent.ConnectorFactory;
+import org.openremote.container.Container;
+import org.openremote.container.ContainerService;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class AgentService implements ContainerService {
+ protected static Map<String, ConnectorFactory> connectorFactories = new HashMap<>();
+
+ static {
+ // TODO: Dynamically load supported Agent Connectors
+
+ }
+
+ @Override
+ public void init(Container container) throws Exception {
+
+
+ }
+
+ @Override
+ public void configure(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/AbstractContextBrokerResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/assets/AbstractContextBrokerResourceImpl.java
new file mode 100644
index 000000000..8b0711707
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/AbstractContextBrokerResourceImpl.java
@@ -0,0 +1,119 @@
+/*
+ * 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.assets;
+
+import org.jboss.marshalling.Pair;
+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 ContextProvider {
+ 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<Pair<String,String>, Map<Attribute, AssetProvider>> providers = new HashMap<>();
+ protected int refreshInterval = REFRESH_INTERVAL;
+
+ @Override
+ public synchronized boolean registerAssetProvider(String assetType, String assetId, List<Attribute> attributes, AssetProvider provider) {
+ LOG.fine("Registering Asset Provider for '" + assetId + "'");
+ List<Attribute> regAttributes = new ArrayList<>(attributes);
+ Map.Entry<Pair<String, String>, Map<Attribute, AssetProvider>> providerEntry = providers
+ .entrySet()
+ .stream()
+ .filter(es -> es.getKey().getA().equalsIgnoreCase(assetId))
+ .findFirst()
+ .orElse(null);
+ Map<Attribute, AssetProvider> providerInfo = providerEntry != null ? providerEntry.getValue() : null;
+
+ if (providerInfo != null) {
+ // If any attributes are already registered with another provider then don't proceed
+ Stream<AssetProvider> 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 attributes already registered with another provider");
+ return false;
+ }
+
+ regAttributes = Stream.concat(regAttributes.stream(), providerInfo.keySet().stream()).collect(Collectors.toList());
+ } else {
+ providerInfo = new HashMap<>();
+ }
+
+ // Register all asset attributes with the Context Broker (updates or creates registration)
+ updateRegistration(assetType, assetId, regAttributes);
+
+ for (Attribute attr : attributes) {
+ providerInfo.put(attr, provider);
+ }
+
+ providers.putIfAbsent(new Pair<>(assetId, assetType), providerInfo);
+ return true;
+ }
+
+ @Override
+ public synchronized void unregisterAssetProvider(String assetType, String assetId, AssetProvider provider) {
+ Map.Entry<Pair<String, String>, Map<Attribute, AssetProvider>> providerEntry = providers
+ .entrySet()
+ .stream()
+ .filter(es -> es.getKey().getA().equalsIgnoreCase(assetId))
+ .findFirst()
+ .orElse(null);
+ Map<Attribute, AssetProvider> providerInfo = providerEntry != null ? providerEntry.getValue() : null;
+
+ if (providerInfo == null) {
+ return;
+ }
+
+ // Split attributes into those to be removed and those to remain
+ Map<Boolean, List<Map.Entry<Attribute, AssetProvider>>> splitAttributes = providerInfo.entrySet().stream().collect(Collectors.partitioningBy(es -> es.getValue() == provider));
+
+ // Remove obsolete attributes
+ 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(assetType, assetId, 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 assetType, String assetId, List<Attribute> attributes);
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/AssetProvider.java b/manager/server/src/main/java/org/openremote/manager/server/assets/AssetProvider.java
new file mode 100644
index 000000000..b6e88a3bf
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/AssetProvider.java
@@ -0,0 +1,32 @@
+/*
+ * 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.assets;
+
+import org.openremote.manager.shared.ngsi.Attribute;
+
+import java.util.List;
+
+public interface AssetProvider {
+ Attribute getAssetAttributeValue(String assetId, String attribute);
+
+ List<Attribute> getAssetAttributeValues(String assetId);
+
+ List<Attribute> getAssetAttributeValues(String assetId, List<String> attributes);
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
index 9df9dcd39..5dc44a453 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
@@ -44,7 +44,7 @@ public class AssetsResourceImpl extends WebResource implements AssetsResource {
}
@Override
- public JsonArray getEntities(RequestParams requestParams, EntityListParams entityListParams) {
+ public Entity[] getEntities(RequestParams requestParams, EntityListParams entityListParams) {
return assetsService.getContextBroker().getEntities(entityListParams);
}
@@ -54,7 +54,7 @@ public class AssetsResourceImpl extends WebResource implements AssetsResource {
}
@Override
- public JsonObject getEntity(RequestParams requestParams, String entityId, EntityParams entityParams) {
+ public Entity getEntity(RequestParams requestParams, String entityId, EntityParams entityParams) {
return assetsService.getContextBroker().getEntity(entityId, entityParams);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsService.java b/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsService.java
index 6da5bd8ab..a289c5563 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/AssetsService.java
@@ -26,12 +26,14 @@ 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.manager.shared.ngsi.EntryPoint;
+import org.openremote.manager.shared.ngsi.*;
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.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
@@ -54,6 +56,8 @@ public class AssetsService implements ContainerService {
protected UriBuilder contextBrokerHostUri;
protected Client httpClient;
+ protected URI hostUri;
+ protected ContextProvider contextProvider;
@Override
public void init(Container container) throws Exception {
@@ -85,6 +89,10 @@ public class AssetsService implements ContainerService {
.register(EntityMessageBodyConverter.class)
.register(EntityArrayMessageBodyConverter.class)
.build();
+
+ hostUri = container.getService(WebService.class).getHostUri();
+
+ contextProvider = new ContextBrokerV1ResourceImpl(httpClient, contextBrokerHostUri);
}
@Override
@@ -93,6 +101,9 @@ public class AssetsService implements ContainerService {
container.getService(WebService.class).getApiSingletons().add(new EntityMessageBodyConverter());
container.getService(WebService.class).getApiSingletons().add(new EntityArrayMessageBodyConverter());
container.getService(WebService.class).getApiSingletons().add(new AssetsResourceImpl(this));
+
+ // Configure the context provider
+ contextProvider.configure(container);
}
@Override
@@ -106,18 +117,31 @@ public class AssetsService implements ContainerService {
public void stop(Container container) throws Exception {
if (httpClient != null)
httpClient.close();
+
+ if (contextProvider != null)
+ contextProvider.stop();
}
public Client getHttpClient() {
return httpClient;
}
- public ContextBrokerResource getContextBroker() {
+ public ContextProvider getContextProvider() { return contextProvider; }
+
+ public ContextBrokerV2Resource getContextBroker() {
return getContextBroker(getTarget(httpClient, contextBrokerHostUri.build()));
}
- public ContextBrokerResource getContextBroker(ResteasyWebTarget target) {
- return target.proxy(ContextBrokerResource.class);
+ 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() {
@@ -131,4 +155,11 @@ public class AssetsService implements ContainerService {
).toBlocking().singleOrDefault(false);
}
+ public boolean registerAssetProvider(String assetType, String assetId, List<Attribute> attributes, AssetProvider provider) {
+ return contextProvider.registerAssetProvider(assetType, assetId, attributes, provider);
+ }
+
+ public void unregisterAssetProvider(String assetType, String assetId, AssetProvider provider) {
+ contextProvider.unregisterAssetProvider(assetType, assetId, provider);
+ }
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV1Resource.java b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV1Resource.java
new file mode 100644
index 000000000..3f067be06
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV1Resource.java
@@ -0,0 +1,56 @@
+/*
+ * 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.assets;
+
+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)
+ ContextResponseWrapper queryContext(EntityAttributeQuery query);
+
+ /*
+ * ***************************************
+ * NGSI9
+ * ***************************************
+ */
+
+ @POST
+ @Path("registry/registerContext")
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ ContextRegistrationV1Response registerContext(ContextRegistrationV1 registration);
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV1ResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV1ResourceImpl.java
new file mode 100644
index 000000000..03c438870
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV1ResourceImpl.java
@@ -0,0 +1,299 @@
+/*
+ * 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.assets;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.jboss.marshalling.Pair;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+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.assets.ContextBrokerV1ResourceImpl.CONTEXT_PROVIDER_V1_ENDPOINT_PATH;
+import static org.openremote.manager.shared.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 ContextRegistrationV1 providerRegistration = new ContextRegistrationV1(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 void stop() {
+ if (updateTimer != null) {
+ updateTimer.cancel();
+ }
+ }
+
+ @Override
+ public ContextResponseWrapper queryContext(EntityAttributeQuery query) {
+ List<ContextResponse> responses = query.getEntities()
+ .stream()
+ .map(e -> getContextResponse(e, query.getAttributes()))
+ .filter(cr -> cr != null)
+ .collect(Collectors.toList());
+
+ if (responses.size() == 0) {
+ return new ContextResponseWrapper(null, new StatusCode("404", "No context element found"));
+ } else {
+ return new ContextResponseWrapper(responses);
+ }
+ }
+
+ @Override
+ public ContextRegistrationV1Response registerContext(ContextRegistrationV1 registration) {
+ return null;
+ }
+
+ @Override
+ public String getContextProviderUri() {
+ 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 ContextResponse getContextResponse(ContextEntity entityQuery, List<String> attributeNames) {
+ Map.Entry<Pair<String, String>, Map<Attribute, AssetProvider>> providerEntry = providers
+ .entrySet()
+ .stream()
+ .filter(es -> es.getKey().getA().equalsIgnoreCase(entityQuery.getId()))
+ .findFirst()
+ .orElse(null);
+ Map<Attribute, AssetProvider> providerInfo = providerEntry != null ? providerEntry.getValue() : null;
+ Map<AssetProvider, List<String>> attributeProviders = null;
+
+ if (providerInfo != null) {
+ if (attributeNames == null || attributeNames.isEmpty()) {
+ // Get all attribute providers
+ attributeProviders = providerInfo
+ .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, AssetProvider> entry = providerInfo
+ .entrySet()
+ .stream()
+ .filter(es -> es.getKey().getName().equals(attr))
+ .findFirst()
+ .orElse(null);
+ return new Pair<>(entry.getValue(), attr);
+ })
+ .filter(p -> p.getA() != null)
+ .collect(Collectors.groupingBy(Pair::getA, Collectors.mapping(Pair::getB, Collectors.toList())));
+ }
+ }
+
+ if (attributeProviders == null || attributeProviders.isEmpty()) {
+ LOG.info("No asset providers found");
+ return null;
+ }
+
+ List<Attribute> attributes = attributeProviders.entrySet()
+ .stream()
+ .filter(es -> !es.getValue().isEmpty())
+ .flatMap(es -> es.getKey().getAssetAttributeValues(entityQuery.getId(), es.getValue()).stream())
+ .collect(Collectors.toList());
+
+ if (attributes.isEmpty()) {
+ LOG.info("Asset provider returned no attributes when asked for the value of one or more attributes");
+ return null;
+ }
+
+ return new ContextResponse(
+ new ContextElement(entityQuery.getType(),entityQuery.getId(), false, attributes),
+ new StatusCode("200", "OK"));
+ }
+
+ @Override
+ protected synchronized void updateRegistration(String assetType, String assetId, List<Attribute> attributes) {
+ // Check if this asset ID is already registered
+ EntityAttributeRegistrationV1 existingReg = providerRegistration.getRegistrations()
+ .stream()
+ .filter(reg ->
+ reg.getEntities()
+ .stream()
+ .anyMatch(e -> e.getId().equalsIgnoreCase(assetId)))
+ .findFirst()
+ .orElse(null);
+
+ if (existingReg != null) {
+ ContextEntity entity = existingReg.getEntities()
+ .stream()
+ .filter(e -> e.getId().equalsIgnoreCase(assetId))
+ .findFirst()
+ .orElse(null);
+
+ if (attributes.isEmpty()) {
+ // Just remove this entity from the registration
+ existingReg.getEntities().remove(entity);
+ } else {
+ // Check if attributes 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 attributes
+ 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()) {
+ EntityAttributeRegistrationV1 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(assetType, assetId, 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 EntityAttributeRegistrationV1(entities, attrs, getContextProviderUri());
+ 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?
+ ContextRegistrationV1 reg = providerRegistration;
+
+ if (reg.getDuration().equalsIgnoreCase("PT0S")) {
+ reg = new ContextRegistrationV1(new ArrayList<>(), reg.getDuration(), reg.getRegistrationId());
+ List<ContextEntity> dummyEntities = new ArrayList<>();
+ dummyEntities.add(new ContextEntity("##############","##############", false));
+ reg.getRegistrations().add(new EntityAttributeRegistrationV1(dummyEntities, null, getContextProviderUri()));
+ }
+
+ ContextRegistrationV1Response 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/assets/ContextBrokerResource.java b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV2Resource.java
similarity index 64%
rename from manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerResource.java
rename to manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV2Resource.java
index c64a30fc7..8fd4355f1 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerResource.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV2Resource.java
@@ -19,11 +19,8 @@
*/
package org.openremote.manager.server.assets;
-import elemental.json.JsonArray;
-import elemental.json.JsonObject;
import org.openremote.manager.shared.http.PATCH;
-import org.openremote.manager.shared.ngsi.Entity;
-import org.openremote.manager.shared.ngsi.EntryPoint;
+import org.openremote.manager.shared.ngsi.*;
import org.openremote.manager.shared.ngsi.params.EntityListParams;
import org.openremote.manager.shared.ngsi.params.EntityParams;
@@ -36,7 +33,12 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
* http://telefonicaid.github.io/fiware-orion/api/v2/stable/
*/
@Path("v2")
-public interface ContextBrokerResource {
+public interface ContextBrokerV2Resource {
+ /*
+ * ***************************************
+ * NGSI10
+ * ***************************************
+ */
@GET
@Produces(APPLICATION_JSON)
@@ -45,7 +47,7 @@ public interface ContextBrokerResource {
@GET
@Path("entities")
@Produces(APPLICATION_JSON)
- JsonArray getEntities(@BeanParam EntityListParams entityListParams);
+ Entity[] getEntities(@BeanParam EntityListParams entityListParams);
@POST
@Path("entities")
@@ -55,7 +57,7 @@ public interface ContextBrokerResource {
@GET
@Path("entities/{entityId}")
@Produces(APPLICATION_JSON)
- JsonObject getEntity(@PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
+ Entity getEntity(@PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
@DELETE
@Path("entities/{entityId}")
@@ -71,4 +73,28 @@ public interface ContextBrokerResource {
@Consumes(APPLICATION_JSON)
Response patchEntityAttributes(@PathParam("entityId") String entityId, Entity entity);
+ /*
+ * ***************************************
+ * NGSI9
+ * ***************************************
+ */
+
+ @POST
+ @Path("registrations")
+ @Consumes(APPLICATION_JSON)
+ Response createRegistration(ContextRegistrationV2 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/register")
+ @Consumes(APPLICATION_JSON)
+ Response batchRegistration(BatchContextRegistrationV2 registrations);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV2ResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV2ResourceImpl.java
new file mode 100644
index 000000000..42eb766a5
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextBrokerV2ResourceImpl.java
@@ -0,0 +1,395 @@
+/*
+ * 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.assets;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.jboss.marshalling.Pair;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+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.assets.ContextBrokerV2ResourceImpl.CONTEXT_PROVIDER_V2_ENDPOINT_PATH;
+import static org.openremote.manager.shared.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 BatchContextRegistrationV2 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 Response createRegistration(ContextRegistrationV2 registration) {
+ 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(BatchContextRegistrationV2 registrations) {
+ throw new NotSupportedException("NGSI v2 Provider doesn't support this method");
+ }
+
+ @Override
+ public String getContextProviderUri() {
+ 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<Pair<String, String>, Map<Attribute, AssetProvider>>> 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().getA())));
+ } else if (entityListParams.idPattern != null) {
+ // Filter by ID (regex)
+ Pattern idRegex = Pattern.compile(entityListParams.idPattern);
+ filteredProviders = filteredProviders
+ .filter(
+ es -> idRegex.matcher(es.getKey().getA()).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().getB())));
+ } else if (entityListParams.typePattern != null) {
+ // Further filter by type (regex)
+ Pattern typeRegex = Pattern.compile(entityListParams.typePattern);
+ filteredProviders = filteredProviders.filter(
+ es -> typeRegex.matcher(es.getKey().getB()).matches()
+ );
+ }
+
+ return filteredProviders.map(es -> es.getKey().getA()).toArray(size -> new String[size]);
+ }
+
+ protected synchronized Entity getEntityResponse(String entityId, List<String> attributeNames) {
+ Map<AssetProvider, List<String>> attributeProviders = null;
+
+ Map.Entry<Pair<String, String>, Map<Attribute, AssetProvider>> providerEntry = providers
+ .entrySet()
+ .stream()
+ .filter(es -> es.getKey().getA().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, AssetProvider> entry = providerEntry
+ .getValue()
+ .entrySet()
+ .stream()
+ .filter(es -> es.getKey().getName().equals(attr))
+ .findFirst()
+ .orElse(null);
+ return new Pair<>(entry.getValue(), attr);
+ })
+ .filter(p -> p.getA() != null)
+ .collect(Collectors.groupingBy(Pair::getA, Collectors.mapping(Pair::getB, Collectors.toList())));
+ }
+ }
+
+ if (attributeProviders == null || attributeProviders.isEmpty()) {
+ LOG.info("No asset providers found");
+ return null;
+ }
+
+ List<Attribute> attributes = attributeProviders.entrySet()
+ .stream()
+ .filter(es -> !es.getValue().isEmpty())
+ .flatMap(es -> es.getKey().getAssetAttributeValues(entityId, es.getValue()).stream())
+ .collect(Collectors.toList());
+
+ if (attributes.isEmpty()) {
+ LOG.info("Asset provider returned no attributes when asked for the value of one or more attributes");
+ return null;
+ }
+
+ // Construct the entity object
+ Entity entity = new Entity();
+ entity.setType(providerEntry.getKey().getB());
+ entity.setId(providerEntry.getKey().getA());
+ attributes.forEach(entity::addAttribute);
+
+ return entity;
+ }
+
+ @Override
+ // TODO: Update registration code cnce NGSI9 v2 is finalised
+ protected synchronized void updateRegistration(String assetType, String assetId, List<Attribute> attributes) {
+ // Check if this asset ID is already registered
+ ContextRegistrationV2 existingReg = providerRegistration.getRegistrations()
+ .stream()
+ .filter(reg ->
+ reg.getSubject().getEntities()
+ .stream()
+ .anyMatch(e -> e.getId().equalsIgnoreCase(assetId)))
+ .findFirst()
+ .orElse(null);
+
+ if (existingReg != null) {
+ ContextEntity entity = existingReg.getSubject().getEntities()
+ .stream()
+ .filter(e -> e.getId().equalsIgnoreCase(assetId))
+ .findFirst()
+ .orElse(null);
+
+ if (attributes.isEmpty()) {
+ // Just remove this entity from the registration
+ existingReg.getSubject().getEntities().remove(entity);
+ } else {
+ // Check if attributes 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 attributes
+ 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);
+ }
+ }
+
+ ContextRegistrationV2 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(assetType, assetId, 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())));
+ EntityAttributeRegistrationV2 subject = new EntityAttributeRegistrationV2(entities,attrs);
+ newReg = new ContextRegistrationV2(subject, getContextProviderUri(), 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 cnce 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/assets/ContextProvider.java b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextProvider.java
new file mode 100644
index 000000000..bc4f280d2
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/assets/ContextProvider.java
@@ -0,0 +1,49 @@
+/*
+ * 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.assets;
+
+import org.openremote.container.Container;
+import org.openremote.manager.shared.ngsi.Attribute;
+
+import java.util.List;
+
+public interface ContextProvider {
+ void configure(Container container) throws Exception;
+
+ void stop();
+
+ String getContextProviderUri();
+
+ boolean registerAssetProvider(String assetType, String assetId, List<Attribute> attributes, AssetProvider provider);
+
+ void unregisterAssetProvider(String assetType, String assetId, AssetProvider 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
+ * @param seconds
+ */
+ void setRefreshInterval(int seconds);
+}
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
new file mode 100644
index 000000000..341960aeb
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/Agent.java
@@ -0,0 +1,95 @@
+package org.openremote.manager.shared.agent;
+
+import elemental.json.Json;
+import elemental.json.JsonObject;
+import org.openremote.manager.shared.ngsi.Attribute;
+import org.openremote.manager.shared.ngsi.AttributeType;
+import org.openremote.manager.shared.ngsi.Entity;
+
+public class Agent extends Entity {
+ // Persisted properties
+ public static final String TYPE = "Agent";
+ public static final String ATTRIBUTE_NAME = "name";
+ public static final String ATTRIBUTE_DESCRIPTION = "description";
+ public static final String ATTRIBUTE_CONNECTOR_TYPE = "connectorType";
+ public static final String ATTRIBUTE_ENABLED = "enabled";
+
+ // State properties that must be read from the agent (agent is context provider for these values)
+ protected boolean valid;
+ protected boolean available;
+ protected boolean connected;
+ protected JsonObject settings;
+
+ public Agent() {
+ super();
+ setType(TYPE);
+ }
+
+ public Agent(JsonObject jsonObject) {
+ super(jsonObject);
+ }
+
+ public String getName() { return getAttributeValueAsString(ATTRIBUTE_NAME); }
+
+ public void setName(String name) {
+ Attribute attr = new Attribute(ATTRIBUTE_NAME, AttributeType.STRING, Json.create(name));
+ super.addAttribute(attr);
+ }
+
+ public String getDescription() {
+ return getAttributeValueAsString(ATTRIBUTE_DESCRIPTION);
+ }
+
+ public void setDescription(String description) {
+ Attribute attr = new Attribute(ATTRIBUTE_DESCRIPTION, AttributeType.STRING, Json.create(description));
+ super.addAttribute(attr);
+ }
+
+ public String getConnectorType() { return getAttributeValueAsString(ATTRIBUTE_CONNECTOR_TYPE); }
+
+ public void setConnectorType(String connectorType) {
+ Attribute attr = new Attribute(ATTRIBUTE_CONNECTOR_TYPE, AttributeType.STRING, Json.create(connectorType));
+ super.addAttribute(attr);
+ }
+
+ public boolean isAvailable() {
+ return available;
+ }
+
+ public void setAvailable(boolean available) {
+ this.available = available;
+ }
+
+ public boolean isEnabled() {
+ return getAttributeValueAsBoolean(ATTRIBUTE_ENABLED);
+ }
+
+ public void setEnabled(boolean enabled) {
+ Attribute attr = new Attribute(ATTRIBUTE_ENABLED, AttributeType.BOOLEAN, Json.create(enabled));
+ super.addAttribute(attr);
+ }
+
+ public boolean isValid() {
+ return valid;
+ }
+
+ public void setValid(boolean valid) {
+ this.valid = valid;
+ }
+
+ public boolean isConnected() {
+ return connected;
+ }
+
+ public void setConnected(boolean connected) {
+ this.connected = connected;
+ }
+
+ public JsonObject getSettings() {
+ return settings;
+ }
+
+ public void setSettings(JsonObject settings) {
+ this.settings = settings;
+ }
+}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java
index 66b99338a..434f6c388 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java
@@ -46,7 +46,7 @@ public interface AssetsResource {
@Produces(APPLICATION_JSON)
@SuccessStatusCode(200)
@RolesAllowed({"read:assets"})
- JsonArray getEntities(@BeanParam RequestParams requestParams, @BeanParam EntityListParams entityListParams);
+ Entity[] getEntities(@BeanParam RequestParams requestParams, @BeanParam EntityListParams entityListParams);
@POST
@Path("entities")
@@ -60,7 +60,7 @@ public interface AssetsResource {
@Produces(APPLICATION_JSON)
@SuccessStatusCode(200)
@RolesAllowed({"read:assets"})
- JsonObject getEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
+ Entity getEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
@DELETE
@Path("entities/{entityId}")
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
new file mode 100644
index 000000000..2c64c7b3a
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ActionType.java
@@ -0,0 +1,26 @@
+/*
+ * 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
index 868f73a39..4b5dedb13 100644
--- 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
@@ -19,11 +19,16 @@
*/
package org.openremote.manager.shared.ngsi;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
public class Attribute extends AbstractAttribute {
+ @JsonIgnore
final protected JsonObject jsonObject;
public Attribute(String name, JsonObject jsonObject) {
@@ -31,10 +36,18 @@ public class Attribute extends AbstractAttribute {
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;
@@ -46,12 +59,14 @@ public class Attribute extends AbstractAttribute {
return this;
}
- public String getType() {
- return jsonObject.hasKey("type") ? jsonObject.getString("type") : null;
+ @JsonProperty("type")
+ public AttributeType getType() {
+ String keyValue = jsonObject.hasKey("type") ? jsonObject.getString("type") : null;
+ return keyValue != null ? AttributeType.fromName(keyValue) : null;
}
- public Attribute setType(String type) {
- jsonObject.put("type", type);
+ public Attribute setType(AttributeType type) {
+ jsonObject.put("type", type.getName());
return this;
}
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
new file mode 100644
index 000000000..f70010a37
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/AttributeType.java
@@ -0,0 +1,71 @@
+/*
+ * 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.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import elemental.json.JsonType;
+import org.openremote.manager.shared.util.Util;
+
+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/BatchContextRegistrationV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/BatchContextRegistrationV2.java
new file mode 100644
index 000000000..ecd9affdb
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/BatchContextRegistrationV2.java
@@ -0,0 +1,44 @@
+/*
+ * 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 BatchContextRegistrationV2 {
+ protected List<ContextRegistrationV2> registrations;
+ protected ActionType actionType;
+
+ public BatchContextRegistrationV2(List<ContextRegistrationV2> registrations, ActionType actionType) {
+ this.registrations = registrations;
+ this.actionType = actionType;
+ }
+
+ public List<ContextRegistrationV2> 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
new file mode 100644
index 000000000..0aaea1486
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextAttribute.java
@@ -0,0 +1,54 @@
+/*
+ * 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
new file mode 100644
index 000000000..3888a55a6
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextDiscovery.java
@@ -0,0 +1,49 @@
+/*
+ * 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("attributes") 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
new file mode 100644
index 000000000..3287818e4
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextElement.java
@@ -0,0 +1,39 @@
+/*
+ * 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("attributes") 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
new file mode 100644
index 000000000..c7664d608
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextEntity.java
@@ -0,0 +1,55 @@
+/*
+ * 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/ContextRegistrationV1.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV1.java
new file mode 100644
index 000000000..e9ecf167b
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV1.java
@@ -0,0 +1,69 @@
+/*
+ * 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 ContextRegistrationV1 {
+ @JsonProperty(value = "contextRegistrations")
+ protected List<EntityAttributeRegistrationV1> registrations;
+ @JsonInclude
+ protected String duration;
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ protected String registrationId;
+
+ public ContextRegistrationV1(List<EntityAttributeRegistrationV1> registrations, String duration) {
+ this.registrations = registrations;
+ this.duration = duration;
+ }
+
+ public ContextRegistrationV1(@JsonProperty("registrations") List<EntityAttributeRegistrationV1> registrations, @JsonProperty("duration") String duration, @JsonProperty("registrationId") String registrationId) {
+ this.registrations = registrations;
+ this.duration = duration;
+ this.registrationId = registrationId;
+ }
+
+ public List<EntityAttributeRegistrationV1> 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<EntityAttributeRegistrationV1> registrations) {
+ this.registrations = registrations;
+ }
+}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV1Response.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV1Response.java
new file mode 100644
index 000000000..b2c5dc770
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV1Response.java
@@ -0,0 +1,50 @@
+/*
+ * 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 ContextRegistrationV1Response {
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ protected String duration;
+ @JsonInclude
+ protected String registrationId;
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ protected StatusCode errorCode;
+
+ public ContextRegistrationV1Response(@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/ContextRegistrationV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV2.java
new file mode 100644
index 000000000..402ac13d9
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextRegistrationV2.java
@@ -0,0 +1,78 @@
+/*
+ * 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 ContextRegistrationV2 {
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ protected EntityAttributeRegistrationV2 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 ContextRegistrationV2(EntityAttributeRegistrationV2 subject, String providerUri, JsonObject metadata, String duration) {
+ this.subject = subject;
+ this.providerUri = providerUri;
+ this.metadata = metadata;
+ this.duration = duration;
+ }
+
+ public ContextRegistrationV2(String duration) {
+ this.duration = duration;
+ }
+
+ public EntityAttributeRegistrationV2 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/ContextResponse.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextResponse.java
new file mode 100644
index 000000000..9cb14cca7
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextResponse.java
@@ -0,0 +1,43 @@
+/*
+ * 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 ContextResponse {
+ @JsonInclude
+ protected ContextElement contextElement;
+ @JsonInclude
+ protected StatusCode statusCode;
+
+ public ContextResponse(@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/ContextResponseWrapper.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextResponseWrapper.java
new file mode 100644
index 000000000..2171bb221
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/ContextResponseWrapper.java
@@ -0,0 +1,53 @@
+/*
+ * 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 ContextResponseWrapper {
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ protected List<ContextResponse> contextResponses;
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ protected StatusCode errorCode;
+
+ public ContextResponseWrapper(@JsonProperty("contextResponses") List<ContextResponse> contextResponses, @JsonProperty("errorCode") StatusCode errorCode) {
+ this.contextResponses = contextResponses;
+ this.errorCode = errorCode;
+ }
+
+ public ContextResponseWrapper(List<ContextResponse> contextResponses) {
+ this.contextResponses = contextResponses;
+ }
+
+ public ContextResponseWrapper(StatusCode errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ public List<ContextResponse> getContextResponses() {
+ return contextResponses;
+ }
+
+ public StatusCode getErrorCode() {
+ return errorCode;
+ }
+}
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
new file mode 100644
index 000000000..e0c688f72
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Duration.java
@@ -0,0 +1,35 @@
+/*
+ * 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
index bd37d2e4b..b3c9f09cd 100644
--- 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
@@ -43,6 +43,10 @@ public class Entity extends AbstractEntity<Attribute> {
super(jsonObject);
}
+ public Entity() {
+ super(elemental.json.Json.createObject());
+ }
+
@Override
public Attribute[] getAttributes() {
Set<Attribute> attributes = new LinkedHashSet<>();
@@ -91,4 +95,14 @@ public class Entity extends AbstractEntity<Attribute> {
}
}
}
+
+ 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() : false;
+ }
}
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
new file mode 100644
index 000000000..896f3ff81
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeQuery.java
@@ -0,0 +1,45 @@
+/*
+ * 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("attributes")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/EntityAttributeRegistrationV1.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeRegistrationV1.java
new file mode 100644
index 000000000..5aa74f8a6
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeRegistrationV1.java
@@ -0,0 +1,52 @@
+/*
+ * 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 EntityAttributeRegistrationV1 {
+ @JsonInclude
+ protected List<ContextEntity> entities;
+ @JsonInclude
+ protected List<ContextAttribute> attributes;
+ @JsonProperty(value = "providingApplication")
+ protected String providerUri;
+
+ public EntityAttributeRegistrationV1(@JsonProperty("entities") List<ContextEntity> entities, @JsonProperty("attributes") 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/EntityAttributeRegistrationV2.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeRegistrationV2.java
new file mode 100644
index 000000000..5b999c847
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/EntityAttributeRegistrationV2.java
@@ -0,0 +1,47 @@
+/*
+ * 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 EntityAttributeRegistrationV2 {
+ @JsonInclude
+ protected List<ContextEntity> entities;
+ @JsonInclude
+ protected List<ContextAttribute> attributes;
+
+
+ public EntityAttributeRegistrationV2(@JsonProperty("entities") List<ContextEntity> entities, @JsonProperty("attributes") 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/Error.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Error.java
new file mode 100644
index 000000000..049c1bfbd
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/Error.java
@@ -0,0 +1,35 @@
+/*
+ * 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/StatusCode.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/StatusCode.java
new file mode 100644
index 000000000..d6538f69a
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/StatusCode.java
@@ -0,0 +1,55 @@
+/*
+ * 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/params/EntityListParams.java b/manager/shared/src/main/java/org/openremote/manager/shared/ngsi/params/EntityListParams.java
index ba80a1b50..f205e4489 100644
--- 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
@@ -39,6 +39,9 @@ public class EntityListParams {
@QueryParam("idPattern")
public String idPattern;
+ @QueryParam("typePattern")
+ public String typePattern;
+
@QueryParam("q")
public Query query;
@@ -86,6 +89,12 @@ public class EntityListParams {
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;
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java b/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java
index a8a5f6401..4b51306b9 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/util/Util.java
@@ -52,4 +52,21 @@ public class Util {
return name;
}
+ /**
+ * Get an enum value from a string without throwing exception.
+ * Enum should be in uppercase to use this method.
+ *
+ * @param c
+ * @param string
+ * @return
+ */
+ public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
+ if (c != null && string != null) {
+ try {
+ return Enum.valueOf(c, string.trim().toUpperCase());
+ } catch (IllegalArgumentException ex) {
+ }
+ }
+ return null;
+ }
}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetsResourceTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetsResourceTest.groovy
index a0eaaac8e..34e45ad5e 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetsResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetsResourceTest.groovy
@@ -11,6 +11,7 @@ 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.Specification
@@ -43,58 +44,58 @@ class AssetsResourceTest extends Specification implements ContainerTrait {
def assetsResource = clientTarget.proxy(AssetsResource.class);
when: "query with no restrictions"
- def entities = Entity.from(assetsResource.getEntities(null, null));
+ def entities = assetsResource.getEntities(null, null);
then: "the result should match"
entities.length == 2
assertRoom(entities[0], null, null, null);
assertRoom(entities[1], null, null, null);
when: "query with id restriction"
- entities = Entity.from(assetsResource.getEntities(
+ entities = assetsResource.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 = Entity.from(assetsResource.getEntities(
+ entities = assetsResource.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 = Entity.from(assetsResource.getEntities(
+ entities = assetsResource.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 = Entity.from(assetsResource.getEntities(
+ entities = assetsResource.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 = Entity.from(assetsResource.getEntities(
+ entities = assetsResource.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")
@@ -109,14 +110,14 @@ class AssetsResourceTest extends Specification implements ContainerTrait {
assert room.getType() == "Room"
def temperature = room.getAttribute("temperature");
- assert temperature.getType() == "float"
+ 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() == "string"
+ assert label.getType() == AttributeType.STRING
assert label.getMetadata() != null
assert label.getMetadata().getElements().length == 0
if (expectedLabel)
@@ -151,19 +152,19 @@ class AssetsResourceTest extends Specification implements ContainerTrait {
room.setType("Room");
room.addAttribute(
new Attribute("label", Json.createObject())
- .setType("string")
+ .setType(AttributeType.STRING)
.setValue(Json.create("Office 123"))
)
room.addAttribute(
new Attribute("temperature", Json.createObject())
- .setType("float")
+ .setType(AttributeType.FLOAT)
.setValue(Json.create(20.5))
);
when: "the room is posted"
assetsResource.postEntity(null, room);
and: "the new room has been retrieved"
- def createdRoom = Entity.from(assetsResource.getEntity(null, room.getId(), null));
+ def createdRoom = assetsResource.getEntity(null, room.getId(), null);
Attribute temperature = createdRoom.getAttribute("temperature");
then: "the room details should match"
createdRoom.getId() == room.getId()
@@ -177,7 +178,7 @@ class AssetsResourceTest extends Specification implements ContainerTrait {
and: "the room is updated"
assetsResource.patchEntityAttributes(null, createdRoom.getId(), roomPatch);
and: "the updated room has been retrieved"
- def updatedRoom = Entity.from(assetsResource.getEntity(null, room.getId(), null));
+ def updatedRoom = assetsResource.getEntity(null, room.getId(), null);
def updatedTemperature = updatedRoom.getAttribute("temperature");
then: "the room details should match"
updatedRoom.getId() == room.getId()
@@ -188,7 +189,7 @@ class AssetsResourceTest extends Specification implements ContainerTrait {
when: "the room is deleted"
assetsResource.deleteEntity(null, room.getId());
and: "the deleted room has been retrieved"
- Entity.from(assetsResource.getEntity(null, room.getId(), null));
+ assetsResource.getEntity(null, room.getId(), null);
then: "the room shouldn't exist"
thrown NotFoundException
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetsServiceTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetsServiceTest.groovy
new file mode 100644
index 000000000..f6f2c2a87
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetsServiceTest.groovy
@@ -0,0 +1,230 @@
+/*
+ * 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.assets
+
+import elemental.json.Json
+import org.openremote.manager.server.assets.AssetProvider
+import org.openremote.manager.server.assets.AssetsService
+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.EntityAttributeQuery
+import org.openremote.test.ContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+class AssetsServiceTest extends Specification implements ContainerTrait {
+
+ def "Register Asset Provider"() {
+ def requestedAttributes = [];
+
+ given: "the server container is started"
+ def serverPort = findEphemeralPort();
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+
+ and: "the assets service is retrieved"
+ def assetsService = container.getService(AssetsService.class);
+
+ when: "a mock asset provider with fake attributes is created"
+ def fakeAttributes = [
+ new Attribute("temperature", AttributeType.FLOAT, Json.create(10.1)),
+ new Attribute("speed", AttributeType.INTEGER, Json.create(50))
+ ];
+
+ def assetProvider = new AssetProvider() {
+ @Override
+ Attribute getAssetAttributeValue(String assetId, String attribute) {
+ requestedAttributes.add(attribute);
+ return attribute.equals("temperature") ?
+ fakeAttributes[0]
+ : fakeAttributes[1];
+ }
+
+ @Override
+ List<Attribute> getAssetAttributeValues(String assetId) {
+ return fakeAttributes;
+ }
+
+ @Override
+ List<Attribute> getAssetAttributeValues(String assetId, List<String> attributes) {
+ if (attributes.size() != 2 || !attributes.contains("temperature") || !attributes.contains("speed")) {
+ return null;
+ }
+
+ requestedAttributes.addAll(attributes);
+
+ return fakeAttributes;
+ }
+ }
+
+ and: "the mock provider registers as a provider of a fake entity with the assets service"
+ def result = assetsService.registerAssetProvider("Car", "Car1", fakeAttributes, assetProvider);
+
+ then: "the mock provider is registered"
+ result == true;
+
+ when: "an asset registered with the mock provider is requested"
+ def response = assetsService.getContextBrokerV1().queryContext(
+ new EntityAttributeQuery([new ContextEntity("Car", "Car1", false)], null)
+ );
+
+ then: "the mock asset 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();
+
+ when: "provider is unregistered and previously registered asset is requested"
+ assetsService.unregisterAssetProvider("Car", "Car1", assetProvider);
+ response = assetsService.getContextBrokerV1().queryContext(
+ new EntityAttributeQuery([new ContextEntity("Car", "Car1", false)], null)
+ );
+
+ then: "a 404 response should be received"
+ conditions.eventually {
+ assert response.getErrorCode() != null;
+ assert response.getErrorCode().code == "404"
+ }
+
+ cleanup: "ensure mock provider is unregistered"
+ assetsService.unregisterAssetProvider("Car", "Car1", assetProvider);
+
+ and: "the server should be stopped"
+ stopContainer(container);
+ }
+
+ def "Auto Refresh of Registration"() {
+ def requestedAttributes = [];
+
+ given: "the server container is started"
+ def serverPort = findEphemeralPort();
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+
+ and: "the assets service is retrieved"
+ def assetsService = container.getService(AssetsService.class);
+
+ when: "a mock asset provider with fake attributes is created"
+ def fakeAttributes = [
+ new Attribute("temperature", AttributeType.FLOAT, Json.create(10.1)),
+ new Attribute("speed", AttributeType.INTEGER, Json.create(50))
+ ];
+
+ def assetProvider = new AssetProvider() {
+ @Override
+ Attribute getAssetAttributeValue(String assetId, String attribute) {
+ requestedAttributes.add(attribute);
+ return attribute.equals("temperature") ?
+ fakeAttributes[0]
+ : fakeAttributes[1];
+ }
+
+ @Override
+ List<Attribute> getAssetAttributeValues(String assetId) {
+ return fakeAttributes;
+ }
+
+ @Override
+ List<Attribute> getAssetAttributeValues(String assetId, List<String> attributes) {
+ if (attributes.size() != 2 || !attributes.contains("temperature") || !attributes.contains("speed")) {
+ return null;
+ }
+
+ requestedAttributes.addAll(attributes);
+
+ return fakeAttributes;
+ }
+ }
+
+ and: "the context provider refresh interval is set to 30s (minimum)"
+ assetsService.getContextProvider().setRefreshInterval(30);
+
+ and: "the mock provider registers as a provider of a fake entity with the assets service"
+ def result = assetsService.registerAssetProvider("Car", "Car1", fakeAttributes, assetProvider);
+
+ then: "the mock provider is registered"
+ result == true;
+
+ when: "enough time passes that auto refresh would have occurred"
+ Thread.sleep(35000);
+
+ and: "an asset registered with the mock provider is requested"
+ def response = assetsService.getContextBrokerV1().queryContext(
+ new EntityAttributeQuery([new ContextEntity("Car", "Car1", false)], null)
+ );
+
+ then: "the mock asset 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"
+ assetsService.unregisterAssetProvider("Car", "Car1", assetProvider);
+
+ and: "the server should be stopped"
+ stopContainer(container);
+ }
+}