Skip to content

armgit / core

Public Imported from GitHub
0

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

Added persistence code

Christian Bauere9603d5bbdf1
diff --git a/README.md b/README.md
index 244f86818..caae104fc 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,6 @@
## Manager
* Run GWT code server: `./gradlew -p manager gwtSuperDev`
-* Run server main class `io.vertx.core.Launcher` with arguments `run org.openremote.manager.server.ManagerVerticle --redeploy=**/*.class --launcher-class=io.vertx.core.Launcher`
-* (Alternative when debugger is needed) Run server main class `org.openremote.manager.server.Server`
+* Run server main class `org.openremote.manager.server.Server`
* Open http://localhost:8080/
-
+* Run tests: `./gradlew test`
diff --git a/gradle.properties b/gradle.properties
index 036cd4ac7..c74602f4d 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,9 +1,16 @@
projectVersion = 3.0-SNAPSHOT
+gwtGradlePluginVersion = 0.6
+aptGradlePluginVersion = 0.4
+
slf4jVersion = 1.7.10
vertxVersion = 3.2.0
junitVersion = 4.12
gwtVersion = 2.8.0-beta1
-gwtGradlePluginVersion = 0.6
ginVersion = 2.1.2
restygwtVersion = 2.1.1
+hibernateVersion = 5.0.7.Final
+# TODO Upgrade Hibernate validator when GWT supports javax.validation 1.1
+hibernateValidatorVersion = 4.3.2.Final
+h2Version = 1.4.190
+hikaricpVersion = 2.4.3
\ No newline at end of file
diff --git a/manager/.gitignore b/manager/.gitignore
index 52f288326..802ea2b83 100644
--- a/manager/.gitignore
+++ b/manager/.gitignore
@@ -1 +1,2 @@
src/main/webapp/gwt
+or-manager-database*
diff --git a/manager/build.gradle b/manager/build.gradle
index 19d79c1d9..47c72ab0a 100644
--- a/manager/build.gradle
+++ b/manager/build.gradle
@@ -1,13 +1,18 @@
buildscript {
repositories {
jcenter()
+ maven {
+ url "https://plugins.gradle.org/m2/"
+ }
}
dependencies {
classpath "de.richsource.gradle.plugins:gwt-gradle-plugin:$gwtGradlePluginVersion"
+ classpath "net.ltgt.gradle:gradle-apt-plugin:$aptGradlePluginVersion"
}
}
apply plugin: "java"
+apply plugin: "net.ltgt.apt"
apply plugin: "gwt-compiler"
sourceCompatibility = '1.8'
@@ -16,12 +21,18 @@ dependencies {
compile "org.slf4j:slf4j-api:$slf4jVersion"
compile "org.slf4j:slf4j-jdk14:$slf4jVersion"
- /* TODO Activate if we have dependencies on commons logging or log4j
- compile "org.slf4j:log4j-over-slf4j:$slf4jVersion"
compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"
- */
+ compile "org.slf4j:log4j-over-slf4j:$slf4jVersion"
compile "io.vertx:vertx-web:$vertxVersion"
+ compile "com.yahoo.elide:elide-core:1.0.0.20"
+ compile "com.yahoo.elide:elide-datastore-hibernate5:1.0.0.20"
+
+ compile "com.h2database:h2:$h2Version"
+ compile "com.zaxxer:HikariCP:$hikaricpVersion"
+ compile "org.hibernate:hibernate-entitymanager:$hibernateVersion"
+ compile "org.hibernate:hibernate-java8:$hibernateVersion"
+ compile "org.hibernate:hibernate-validator:$hibernateValidatorVersion"
compile "com.google.gwt:gwt-user:$gwtVersion"
compile "com.google.gwt:gwt-elemental:$gwtVersion"
@@ -29,7 +40,9 @@ dependencies {
exclude group: "asm"
}
compile "org.fusesource.restygwt:restygwt:$restygwtVersion"
-
+
+ apt "org.hibernate:hibernate-jpamodelgen:$hibernateVersion"
+
testCompile "junit:junit:$junitVersion"
testCompile "io.vertx:vertx-unit:$vertxVersion"
diff --git a/manager/src/main/java/org/openremote/manager/server/Constants.java b/manager/src/main/java/org/openremote/manager/server/Constants.java
new file mode 100644
index 000000000..3de11bc8c
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/Constants.java
@@ -0,0 +1,7 @@
+package org.openremote.manager.server;
+
+public interface Constants {
+
+ String DEV_MODE = "DEV_MODE";
+ boolean DEV_MODE_DEFAULT = true;
+}
diff --git a/manager/src/main/java/org/openremote/manager/server/Database.java b/manager/src/main/java/org/openremote/manager/server/Database.java
new file mode 100644
index 000000000..9e21ade3a
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/Database.java
@@ -0,0 +1,56 @@
+package org.openremote.manager.server;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import org.hibernate.cfg.AvailableSettings;
+import org.hibernate.dialect.H2Dialect;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public interface Database {
+
+ Map<String, Object> open(String connectionUrl, String username, String password, int minIdle, int maxPoolSize);
+
+ void close();
+
+ enum Product implements Database {
+
+ H2 {
+
+ protected HikariConfig hikariConfig;
+ protected HikariDataSource hikariDataSource;
+
+ @Override
+ public Map<String, Object> open(String connectionUrl, String username, String password, int minIdle, int maxPoolSize) {
+
+ // Don't trace log values larger than X bytes (especially useful for debugging LOBs, which are accessed in toString()!)
+ System.setProperty("h2.maxTraceDataLength", "256"); // 256 bytes, default is 64 kilobytes
+
+ hikariConfig = new HikariConfig();
+ hikariConfig.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
+ hikariConfig.addDataSourceProperty("URL", connectionUrl);
+ hikariConfig.setUsername(username);
+ hikariConfig.setPassword(password);
+ hikariConfig.setMinimumIdle(minIdle);
+ hikariConfig.setMaximumPoolSize(maxPoolSize);
+
+ hikariDataSource = new HikariDataSource(hikariConfig);
+
+ Map<String, Object> properties = new HashMap<>();
+ properties.put(AvailableSettings.DIALECT, H2Dialect.class.getName());
+ properties.put(AvailableSettings.DATASOURCE, hikariDataSource);
+
+ return properties;
+ }
+
+ @Override
+ public void close() {
+ if (hikariDataSource != null)
+ hikariDataSource.close();
+ hikariConfig = null;
+ hikariDataSource = null;
+ }
+ };
+ }
+}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/server/ManagerVerticle.java b/manager/src/main/java/org/openremote/manager/server/ManagerVerticle.java
deleted file mode 100644
index 0ab8dd766..000000000
--- a/manager/src/main/java/org/openremote/manager/server/ManagerVerticle.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package org.openremote.manager.server;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import io.vertx.core.AbstractVerticle;
-import io.vertx.core.Future;
-import io.vertx.core.http.HttpServer;
-import io.vertx.core.http.HttpServerOptions;
-import io.vertx.core.http.HttpServerResponse;
-import io.vertx.ext.web.Router;
-import io.vertx.ext.web.handler.StaticHandler;
-import org.openremote.manager.shared.model.Asset;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static org.openremote.manager.server.util.JsonUtil.JSON;
-
-public class ManagerVerticle extends AbstractVerticle {
-
- private static final Logger LOG = Logger.getLogger(ManagerVerticle.class.getName());
-
- @Override
- public void start(Future<Void> future) {
-
- HttpServerOptions options = new HttpServerOptions();
- HttpServer server = vertx.createHttpServer(options);
-
- Router router = Router.router(vertx);
-
- router.route("/hello").handler(routingContext -> {
- LOG.info("### HELLO SERVICE METHOD CALLED !!!");
- HttpServerResponse response = routingContext.response();
- response.putHeader("content-type", "text/plain");
- response.end("Hello from Server, the time is: " + System.currentTimeMillis());
- });
-
- router.route("/asset").handler(routingContext -> {
- HttpServerResponse response = routingContext.response();
- response.putHeader("content-type", "application/json");
-
- try {
- response.end(JSON.writeValueAsString(new Asset("Hello Asset")));
- } catch (JsonProcessingException e) {
- LOG.log(Level.SEVERE, "JSON Failed", e);
- }
- });
-
- router.route("/*").handler(StaticHandler.create("manager/src/main/webapp").setCachingEnabled(false));
-
- server
- .requestHandler(router::accept)
- .listen(8080, result -> {
- if (result.succeeded()) {
- future.complete();
- } else {
- future.fail(result.cause());
- }
- });
-
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/server/PersistenceService.java b/manager/src/main/java/org/openremote/manager/server/PersistenceService.java
new file mode 100644
index 000000000..d008db403
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/PersistenceService.java
@@ -0,0 +1,95 @@
+package org.openremote.manager.server;
+
+import io.vertx.core.json.JsonObject;
+
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import static org.openremote.manager.server.Constants.DEV_MODE;
+import static org.openremote.manager.server.Constants.DEV_MODE_DEFAULT;
+
+public class PersistenceService {
+
+ private static final Logger LOG = Logger.getLogger(PersistenceService.class.getName());
+
+ public static final String PERSISTENCE_UNIT_NAME = "PERSISTENCE_UNIT_NAME";
+ public static final String PERSISTENCE_UNIT_NAME_DEFAULT = "ManagerPU";
+ public static final String DATABASE_PRODUCT = "DATABASE_PRODUCT";
+ public static final String DATABASE_PRODUCT_DEFAULT = "H2";
+ public static final String DATABASE_CONNECTION_URL = "DATABASE_CONNECTION_URL";
+ public static final String DATABASE_CONNECTION_URL_DEFAULT = "jdbc:h2:file:./or-manager-database";
+ public static final String DATABASE_CONNECTION_URL_DEV_MODE = "jdbc:h2:mem:test";
+ public static final String DATABASE_USERNAME = "DATABASE_USERNAME";
+ public static final String DATABASE_USERNAME_DEFAULT = "sa";
+ public static final String DATABASE_PASSWORD = "DATABASE_PASSWORD";
+ public static final String DATABASE_PASSWORD_DEFAULT = "";
+ public static final String DATABASE_MIN_POOL_SIZE = "DATABASE_MIN_POOL_SIZE";
+ public static final int DATABASE_MIN_POOL_SIZE_DEFAULT = 5;
+ public static final String DATABASE_MAX_POOL_SIZE = "DATABASE_MAX_POOL_SIZE";
+ public static final int DATABASE_MAX_POOL_SIZE_DEFAULT = 20;
+
+ protected Database database;
+ protected String persistenceUnitName;
+ protected Map<String, Object> persistenceUnitProperties;
+ protected EntityManagerFactory entityManagerFactory;
+
+ public void start(JsonObject config) {
+ boolean devMode = config.getBoolean(DEV_MODE, DEV_MODE_DEFAULT);
+ String databaseProduct = config.getString(DATABASE_PRODUCT, DATABASE_PRODUCT_DEFAULT);
+
+ LOG.info("Starting persistence service for database: " + databaseProduct);
+
+ database = Database.Product.valueOf(databaseProduct);
+
+ String connectionUrl = devMode
+ ? DATABASE_CONNECTION_URL_DEV_MODE
+ : config.getString(DATABASE_CONNECTION_URL, DATABASE_CONNECTION_URL_DEFAULT);
+ LOG.info("Using database connection URL: " + connectionUrl);
+
+ String databaseUsername = config.getString(DATABASE_USERNAME, DATABASE_USERNAME_DEFAULT);
+ String databasePassword = config.getString(DATABASE_PASSWORD, DATABASE_PASSWORD_DEFAULT);
+ int databaseMinPoolSize = config.getInteger(DATABASE_MIN_POOL_SIZE, DATABASE_MIN_POOL_SIZE_DEFAULT);
+ int databaseMaxPoolSize = config.getInteger(DATABASE_MAX_POOL_SIZE, DATABASE_MAX_POOL_SIZE_DEFAULT);
+ persistenceUnitProperties =
+ database.open(connectionUrl, databaseUsername, databasePassword, databaseMinPoolSize, databaseMaxPoolSize);
+
+ persistenceUnitName = config.getString(PERSISTENCE_UNIT_NAME, PERSISTENCE_UNIT_NAME_DEFAULT);
+ this.entityManagerFactory =
+ Persistence.createEntityManagerFactory(persistenceUnitName, persistenceUnitProperties);
+ }
+
+ public void stop() {
+ LOG.info("Stopping persistence service...");
+ if (entityManagerFactory != null) {
+ entityManagerFactory.close();
+ }
+ if (database != null) {
+ database.close();
+ }
+ }
+
+ public EntityManagerFactory getEntityManagerFactory() {
+ return entityManagerFactory;
+ }
+
+ public void createSchema() {
+ generateSchema("create");
+ }
+
+ public void dropSchema() {
+ generateSchema("drop");
+ }
+
+ protected void generateSchema(String action) {
+ // Take exiting EMF properties, override the schema generation setting on a copy
+ Map<String, Object> createSchemaProperties = new HashMap<>(persistenceUnitProperties);
+ createSchemaProperties.put(
+ "javax.persistence.schema-generation.database.action",
+ action
+ );
+ Persistence.generateSchema(persistenceUnitName, createSchemaProperties);
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/server/SampleData.java b/manager/src/main/java/org/openremote/manager/server/SampleData.java
new file mode 100644
index 000000000..d8dd5908e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/SampleData.java
@@ -0,0 +1,41 @@
+package org.openremote.manager.server;
+
+import org.apache.log4j.Logger;
+import org.openremote.manager.shared.model.inventory.Device;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityTransaction;
+
+import static org.openremote.manager.server.util.IdentifierUtil.generateGlobalUniqueId;
+
+public class SampleData {
+
+ private static final Logger LOG = Logger.getLogger(SampleData.class.getName());
+
+ public void create(PersistenceService persistenceService) {
+ LOG.info("--- CREATING TEST DATA ---");
+
+ persistenceService.createSchema();
+
+ EntityManager em = persistenceService.getEntityManagerFactory().createEntityManager();
+ EntityTransaction tx = em.getTransaction();
+ tx.begin();
+
+ Device a1 = new Device("My Device A", generateGlobalUniqueId(), "urn:org-openremote:device");
+ a1.setSensorEndpoints(new String[]{
+ "zwave://123/foo",
+ "zwave://123/bar"
+ });
+ em.persist(a1);
+
+ Device a2 = new Device("Device B", generateGlobalUniqueId(), "urn:org-openremote:device");
+ em.persist(a2);
+
+ tx.commit();
+ }
+
+ public void drop(PersistenceService persistenceService) {
+ LOG.info("--- DROPPING TEST DATA ---");
+ persistenceService.dropSchema();
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/server/Server.java b/manager/src/main/java/org/openremote/manager/server/Server.java
index 899d9c510..0bae2c0dd 100644
--- a/manager/src/main/java/org/openremote/manager/server/Server.java
+++ b/manager/src/main/java/org/openremote/manager/server/Server.java
@@ -1,20 +1,29 @@
package org.openremote.manager.server;
+import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import java.util.logging.Logger;
+import static org.openremote.manager.server.util.EnvironmentUtil.getEnvironment;
+
public class Server {
private static final Logger LOG = Logger.getLogger(Server.class.getName());
public static void main(String[] args) {
- Vertx vertx = Vertx.vertx();
+ Vertx vertx = Vertx.vertx();
+
+ LOG.info("Starting server...");
+
+ DeploymentOptions options = new DeploymentOptions()
+ .setConfig(getEnvironment());
vertx.deployVerticle(
- ManagerVerticle.class.getName(),
+ ServerVerticle.class.getName(),
+ options,
event -> {
- LOG.info("Server startup complete.");
+ LOG.info("Server startup complete");
}
);
}
diff --git a/manager/src/main/java/org/openremote/manager/server/ServerVerticle.java b/manager/src/main/java/org/openremote/manager/server/ServerVerticle.java
new file mode 100644
index 000000000..5f83cec88
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/ServerVerticle.java
@@ -0,0 +1,122 @@
+package org.openremote.manager.server;
+
+import com.yahoo.elide.Elide;
+import com.yahoo.elide.ElideResponse;
+import com.yahoo.elide.audit.Slf4jLogger;
+import com.yahoo.elide.core.DataStore;
+import com.yahoo.elide.datastores.hibernate5.HibernateStore;
+import io.vertx.core.AbstractVerticle;
+import io.vertx.core.Future;
+import io.vertx.core.http.HttpServer;
+import io.vertx.core.http.HttpServerOptions;
+import io.vertx.core.http.HttpServerResponse;
+import io.vertx.ext.web.Router;
+import io.vertx.ext.web.handler.StaticHandler;
+import org.hibernate.SessionFactory;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
+import java.util.logging.Logger;
+
+import static org.openremote.manager.server.Constants.DEV_MODE;
+import static org.openremote.manager.server.Constants.DEV_MODE_DEFAULT;
+
+public class ServerVerticle extends AbstractVerticle {
+
+ private static final Logger LOG = Logger.getLogger(ServerVerticle.class.getName());
+
+ public static final String WEB_SERVER_PORT = "WEB_SERVER_PORT";
+ public static final int WEB_SEVER_PORT_DEFAULT = 8080;
+
+ protected boolean devMode;
+
+ protected PersistenceService persistenceService;
+
+ protected SampleData sampleData;
+
+ protected Elide elide;
+
+ @Override
+ public void start(Future<Void> future) {
+
+ devMode = config().getBoolean(DEV_MODE, DEV_MODE_DEFAULT);
+
+ persistenceService = new PersistenceService();
+ persistenceService.start(config());
+
+ if (devMode) {
+ sampleData = new SampleData();
+ sampleData.create(persistenceService);
+ }
+
+ SessionFactory sessionFactory =
+ persistenceService.getEntityManagerFactory().unwrap(SessionFactory.class);
+ DataStore dataStore = new HibernateStore(sessionFactory);
+ com.yahoo.elide.audit.Logger auditLogger = new Slf4jLogger();
+ elide = new Elide(auditLogger, dataStore);
+
+ HttpServerOptions options = new HttpServerOptions();
+ HttpServer server = vertx.createHttpServer(options);
+ Router router = Router.router(vertx);
+
+ router.route("/hello").handler(routingContext -> {
+ HttpServerResponse response = routingContext.response();
+ response.putHeader("content-type", "text/plain");
+ response.end("Hello from Server, the time is: " + System.currentTimeMillis());
+ });
+
+ router.route("/device").handler(routingContext -> {
+
+ vertx.executeBlocking(
+ event -> {
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ // TODO: Copy request parameters into map
+ try {
+ ElideResponse response = elide.get("/device", params, "someUsername");
+ event.complete(response);
+ } catch (Exception ex) {
+ event.fail(ex);
+ }
+ },
+ result -> {
+ if (result.succeeded()) {
+ ElideResponse elideResponse = (ElideResponse) result.result();
+ HttpServerResponse response = routingContext.response();
+ response.putHeader("content-type", "application/json");
+ response.end(elideResponse.getBody());
+ } else {
+ HttpServerResponse response = routingContext.response();
+ response.setStatusCode(500).end(result.cause().toString());
+ }
+ }
+ );
+ });
+
+ router.route("/*").handler(StaticHandler.create("manager/src/main/webapp").setCachingEnabled(false));
+
+ int webserverPort = config().getInteger(WEB_SERVER_PORT, WEB_SEVER_PORT_DEFAULT);
+ LOG.info("Starting web server on port: " + webserverPort);
+ server
+ .requestHandler(router::accept)
+ .listen(webserverPort, result -> {
+ if (result.succeeded()) {
+ future.complete();
+ } else {
+ future.fail(result.cause());
+ }
+ });
+ }
+
+ @Override
+ public void stop(Future<Void> stopFuture) throws Exception {
+ try {
+ if (devMode && sampleData != null)
+ sampleData.drop(persistenceService);
+ persistenceService.stop();
+ stopFuture.complete();
+ } catch (Exception ex) {
+ stopFuture.fail(ex);
+ }
+ }
+}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/server/util/EnvironmentUtil.java b/manager/src/main/java/org/openremote/manager/server/util/EnvironmentUtil.java
new file mode 100644
index 000000000..4c1e5e1be
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/util/EnvironmentUtil.java
@@ -0,0 +1,17 @@
+package org.openremote.manager.server.util;
+
+import io.vertx.core.json.JsonObject;
+
+import java.util.Map;
+
+public class EnvironmentUtil {
+
+ public static JsonObject getEnvironment() {
+ JsonObject env = new JsonObject();
+ Map<String, String> environment = System.getenv();
+ for (Map.Entry<String, String> entry : environment.entrySet()) {
+ env.put(entry.getKey(), entry.getValue());
+ }
+ return env;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/server/util/IdentifierUtil.java b/manager/src/main/java/org/openremote/manager/server/util/IdentifierUtil.java
new file mode 100644
index 000000000..d88e335b9
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/util/IdentifierUtil.java
@@ -0,0 +1,99 @@
+package org.openremote.manager.server.util;
+
+import java.net.NetworkInterface;
+import java.nio.ByteBuffer;
+import java.nio.LongBuffer;
+import java.nio.charset.Charset;
+import java.security.MessageDigest;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.UUID;
+
+/**
+ * Utility functions for identifier value generation.
+ */
+public class IdentifierUtil {
+
+ /**
+ * A random 128 bit UUID in URL-safe 22 characters.
+ */
+ public static String generateGlobalUniqueId() {
+ String encoded = Base64.getUrlEncoder().encodeToString(IdentifierUtil.toByteArray(UUID.randomUUID()));
+ while (encoded.charAt(encoded.length() - 1) == '=')
+ encoded = encoded.substring(0, encoded.length() - 1);
+ return encoded;
+ }
+
+ /**
+ * Generates a unique identifier that is the same every time this method is invoked on the same machine with
+ * the same argument. This is a short (27 characters) URL-safe string.
+ * <p>
+ * This method combines the first non-loopback network interface's MAC address with given salt, then produces a
+ * SHA-1 hash. In other words, every time you call this method with the same salt on the same
+ * machine, you get the same identifier. If you use the same salt on a different machine, a different identifier
+ * will be generated.
+ * </p>
+ *
+ * @param salt An arbitrary string, longer values improve uniqueness.
+ * @return A global unique identifier, stable for the current system and salt, with 48 bit + [salt bytes] uniqueness.
+ */
+ public static String generateSystemUniqueId(String salt) {
+ return getEncodedHash(
+ IdentifierUtil.getFirstNetworkInterfaceHardwareAddress(),
+ salt.getBytes(Charset.forName("UTF-8"))
+ );
+ }
+
+ /**
+ * Generates a URL-safe, 27 character unpadded Base64 encoded SHA-1 hash of the given bytes.
+ */
+ public static String getEncodedHash(byte[]... bytes) {
+ if (bytes == null)
+ throw new IllegalArgumentException("Can't encode/hash null bytes");
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-1");
+ digest.reset();
+ for (byte[] byteArray : bytes) {
+ digest.update(byteArray);
+ }
+ byte[] hash = digest.digest();
+ digest.reset();
+ String encoded = Base64.getUrlEncoder().encodeToString(hash);
+ while (encoded.charAt(encoded.length() - 1) == '=')
+ encoded = encoded.substring(0, encoded.length() - 1);
+ return encoded;
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ /**
+ * Gets the first non-loopback, "up" network interface's MAC address or throws an exception.
+ */
+ public static byte[] getFirstNetworkInterfaceHardwareAddress() {
+ try {
+ Enumeration<NetworkInterface> interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
+ for (NetworkInterface iface : Collections.list(interfaceEnumeration)) {
+ if (!iface.isLoopback() && iface.isUp() && iface.getHardwareAddress() != null) {
+ return iface.getHardwareAddress();
+ }
+ }
+ } catch (Exception ex) {
+ throw new RuntimeException("Could not discover first network interface hardware address", ex);
+ }
+ throw new RuntimeException("Could not discover first network interface hardware address");
+ }
+
+ /**
+ * Returns the 16 bytes of the given UUID.
+ */
+ public static byte[] toByteArray(UUID uuid) {
+ byte[] byteArray = new byte[(Long.SIZE / Byte.SIZE) * 2];
+ ByteBuffer buffer = ByteBuffer.wrap(byteArray);
+ LongBuffer longBuffer = buffer.asLongBuffer();
+ longBuffer.put(new long[]{uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()});
+ return byteArray;
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/Asset.java b/manager/src/main/java/org/openremote/manager/shared/model/Asset.java
deleted file mode 100644
index b718e3640..000000000
--- a/manager/src/main/java/org/openremote/manager/shared/model/Asset.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.openremote.manager.shared.model;
-
-public class Asset {
-
- public String name;
-
- public Asset() {
- }
-
- public Asset(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/Identifiable.java b/manager/src/main/java/org/openremote/manager/shared/model/Identifiable.java
new file mode 100644
index 000000000..723da0b9e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/model/Identifiable.java
@@ -0,0 +1,70 @@
+package org.openremote.manager.shared.model;
+
+import jsinterop.annotations.JsIgnore;
+import jsinterop.annotations.JsType;
+
+import javax.persistence.Column;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+@JsType
+@MappedSuperclass
+public abstract class Identifiable {
+
+ @Id
+ @Column(name = "ID")
+ public String id;
+
+ @NotNull
+ @Size(min = 3, max = 255)
+ @Column(name = "MODEL_TYPE")
+ public String type; // URI
+
+ @JsIgnore
+ protected Identifiable() {
+ }
+
+ @JsIgnore
+ public Identifiable(String id, String type) {
+ this.id = id;
+ this.type = type;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public boolean isOfType(String type) {
+ return getType().equals(type);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Identifiable that = (Identifiable) o;
+
+ return getId().equals(that.getId());
+ }
+
+ @Override
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+ public String toTypeIdString() {
+ return type + ':' + id;
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/inventory/Asset.java b/manager/src/main/java/org/openremote/manager/shared/model/inventory/Asset.java
new file mode 100644
index 000000000..7978b39f7
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/model/inventory/Asset.java
@@ -0,0 +1,29 @@
+package org.openremote.manager.shared.model.inventory;
+
+public class Asset extends InventoryObject {
+
+ protected Device[] devices;
+
+ protected Asset[] children;
+
+ protected Asset() {
+ }
+
+ public Asset(String label, String id, String type, Asset... children) {
+ this(label, id, type, new Device[0], children);
+ }
+
+ public Asset(String label, String id, String type, Device[] devices, Asset... children) {
+ super(label, id, type);
+ this.children = children;
+ this.devices = devices;
+ }
+
+ public Device[] getDevices() {
+ return devices;
+ }
+
+ public Asset[] getChildren() {
+ return children;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/inventory/Device.java b/manager/src/main/java/org/openremote/manager/shared/model/inventory/Device.java
new file mode 100644
index 000000000..854865436
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/model/inventory/Device.java
@@ -0,0 +1,78 @@
+package org.openremote.manager.shared.model.inventory;
+
+import jsinterop.annotations.JsIgnore;
+import jsinterop.annotations.JsType;
+import org.openremote.manager.shared.util.StringArrayConverter;
+
+import javax.persistence.*;
+import java.util.Arrays;
+
+@JsType
+@Entity
+@Table(name = "DEVICE")
+public class Device extends InventoryObject {
+
+ @JsType
+ public enum Status {
+ UNINITIALIZED,
+ READY,
+ OFFLINE,
+ ONLINE,
+ COMMUNICATION_ERROR,
+ MAINTENANCE
+ }
+
+ @Column(name = "DEVICE_STATUS", nullable = false)
+ @Enumerated(EnumType.STRING)
+ public Status status = Status.UNINITIALIZED;
+
+ @Column(name = "SENSOR_ENDPOINTS", nullable = true, length = 32768)
+ @Convert(converter = StringArrayConverter.class)
+ public String[] sensorEndpoints;
+
+ @Column(name = "ACTUATOR_ENDPOINTS", nullable = true, length = 32768)
+ @Convert(converter = StringArrayConverter.class)
+ public String[] actuatorEndpoints;
+
+ @JsIgnore
+ protected Device() {
+ }
+
+ @JsIgnore
+ public Device(String label, String id, String type) {
+ super(label, id, type);
+ }
+
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ public String[] getSensorEndpoints() {
+ return sensorEndpoints;
+ }
+
+ public void setSensorEndpoints(String[] sensorEndpoints) {
+ this.sensorEndpoints = sensorEndpoints;
+ }
+
+ public String[] getActuatorEndpoints() {
+ return actuatorEndpoints;
+ }
+
+ public void setActuatorEndpoints(String[] actuatorEndpoints) {
+ this.actuatorEndpoints = actuatorEndpoints;
+ }
+
+ @Override
+ public String toString() {
+ return "Device{" +
+ "status=" + status +
+ ", sensorEndpoints=" + Arrays.toString(sensorEndpoints) +
+ ", actuatorEndpoints=" + Arrays.toString(actuatorEndpoints) +
+ "} " + super.toString();
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/inventory/InventoryObject.java b/manager/src/main/java/org/openremote/manager/shared/model/inventory/InventoryObject.java
new file mode 100644
index 000000000..0757d06cc
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/model/inventory/InventoryObject.java
@@ -0,0 +1,58 @@
+package org.openremote.manager.shared.model.inventory;
+
+import jsinterop.annotations.JsIgnore;
+import jsinterop.annotations.JsType;
+import org.openremote.manager.shared.model.Identifiable;
+
+import javax.persistence.Column;
+import javax.persistence.MappedSuperclass;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+@JsType
+@MappedSuperclass
+public class InventoryObject extends Identifiable {
+
+ @NotNull
+ @Size(min = 3, max = 1023)
+ @Column(name = "LABEL")
+ public String label;
+
+ @Column(name = "ITEM_PROPERTIES", nullable = true, length = 1048576) // TODO 1MB?
+ public String properties;
+
+ @JsIgnore
+ protected InventoryObject() {
+ }
+
+ @JsIgnore
+ public InventoryObject(String label, String id, String type) {
+ super(id, type);
+ this.label = label;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public String getProperties() {
+ return properties;
+ }
+
+ public void setProperties(String properties) {
+ this.properties = properties;
+ }
+
+ @Override
+ public String toString() {
+ return "InventoryObject{" +
+ "label='" + getLabel() + '\'' +
+ ", id=" + getId() +
+ ", properties=" + getProperties() +
+ '}';
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/inventory/package-info.java b/manager/src/main/java/org/openremote/manager/shared/model/inventory/package-info.java
new file mode 100644
index 000000000..e57523949
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/model/inventory/package-info.java
@@ -0,0 +1,3 @@
[email protected](rootLevel=true)
+
+package org.openremote.manager.shared.model.inventory;
diff --git a/manager/src/main/java/org/openremote/manager/shared/model/package-info.java b/manager/src/main/java/org/openremote/manager/shared/model/package-info.java
new file mode 100644
index 000000000..1bd74f226
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/model/package-info.java
@@ -0,0 +1,15 @@
+ name = "ID_GENERATOR",
+ strategy = "enhanced-sequence",
+ parameters = {
+ @org.hibernate.annotations.Parameter(
+ name = "sequence_name",
+ value = "OR_MANAGER_SEQUENCE"
+ ),
+ @org.hibernate.annotations.Parameter(
+ name = "initial_value",
+ value = "1000"
+ )
+ }
+)
+package org.openremote.manager.shared.model;
diff --git a/manager/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.java b/manager/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.java
new file mode 100644
index 000000000..3e6cb58bf
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/util/StringArrayConverter.java
@@ -0,0 +1,27 @@
+package org.openremote.manager.shared.util;
+
+import javax.persistence.AttributeConverter;
+
+public class StringArrayConverter implements AttributeConverter<String[], String> {
+
+ @Override
+ public String convertToDatabaseColumn(String[] attribute) {
+ if (attribute == null || attribute.length == 0)
+ return null;
+ StringBuilder sb = new StringBuilder();
+ for (String s : attribute) {
+ sb.append(s).append(",");
+ }
+ if (sb.length() > 0) {
+ sb.deleteCharAt(sb.length()-1);
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String[] convertToEntityAttribute(String data) {
+ if (data == null)
+ return new String[0];
+ return data.split(",");
+ }
+}
\ No newline at end of file
diff --git a/manager/src/main/resources/META-INF/persistence.xml b/manager/src/main/resources/META-INF/persistence.xml
new file mode 100644
index 000000000..46c5e503d
--- /dev/null
+++ b/manager/src/main/resources/META-INF/persistence.xml
@@ -0,0 +1,23 @@
+<persistence
+ version="2.1"
+ xmlns="http://xmlns.jcp.org/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
+ http://xmlns.jcp.org/xml/ns/persistence_2_1.xsd">
+
+ <persistence-unit name="ManagerPU" transaction-type="RESOURCE_LOCAL">
+
+ <!-- package-info -->
+ <class>org.openremote.manager.shared.model</class>
+
+ <class>org.openremote.manager.shared.model.inventory.Device</class>
+
+ <exclude-unlisted-classes>true</exclude-unlisted-classes>
+ <properties>
+ <property name="hibernate.format_sql" value="true"/>
+ <property name="hibernate.use_sql_comments" value="true"/>
+ <property name="hibernate.archive.autodetection" value="none"/>
+ <property name="hibernate.current_session_context_class" value="thread"/>
+ </properties>
+ </persistence-unit>
+</persistence>
\ No newline at end of file
diff --git a/manager/src/main/resources/META-INF/validation.xml b/manager/src/main/resources/META-INF/validation.xml
new file mode 100644
index 000000000..7ee35c51f
--- /dev/null
+++ b/manager/src/main/resources/META-INF/validation.xml
@@ -0,0 +1,10 @@
+<validation-config
+ xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration http://jboss.org/xml/ns/javax/validation/configuration"
+ version="1.1">
+ <!-- This assumes that the Bean Validation implementation on the classpath is Hibernate Validator -->
+<!-- TODO Old HV version?
+ <message-interpolator>org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator</message-interpolator>
+-->
+</validation-config>
\ No newline at end of file
diff --git a/manager/src/main/resources/vertx-default-jul-logging.properties b/manager/src/main/resources/vertx-default-jul-logging.properties
index 7c3a12bc6..009f1bacf 100644
--- a/manager/src/main/resources/vertx-default-jul-logging.properties
+++ b/manager/src/main/resources/vertx-default-jul-logging.properties
@@ -3,8 +3,15 @@ handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.formatter=org.openremote.manager.server.util.LogFormatter
java.util.logging.ConsoleHandler.level=FINEST
-.level=FINEST
-io.vertx.ext.web.level=FINEST
-io.vertx.level=FINEST
+.level=INFO
+io.vertx.ext.web.level=INFO
+io.vertx.level=INFO
com.hazelcast.level=INFO
io.netty.util.internal.PlatformDependent.level=SEVERE
+
+# Persistence
+org.hibernate.SQL.level=WARNING
+org.hibernate.type.descriptor.sql.BasicBinder.level=WARNING
+org.hibernate.jpa.internal.util.level = WARNING
+org.hibernate.dialect.Dialect.level = WARNING
+org.hibernate.validator.internal.xml.ValidationXmlParser.level = WARNING
diff --git a/manager/src/test/java/org/openremote/manager/test/DevicesTest.java b/manager/src/test/java/org/openremote/manager/test/DevicesTest.java
new file mode 100644
index 000000000..64c040053
--- /dev/null
+++ b/manager/src/test/java/org/openremote/manager/test/DevicesTest.java
@@ -0,0 +1,86 @@
+package org.openremote.manager.test;
+
+import com.yahoo.elide.jsonapi.models.JsonApiDocument;
+import io.vertx.core.DeploymentOptions;
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.unit.Async;
+import io.vertx.ext.unit.TestContext;
+import io.vertx.ext.unit.junit.VertxUnitRunner;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openremote.manager.server.ServerVerticle;
+
+import java.io.IOException;
+import java.net.Inet4Address;
+import java.net.ServerSocket;
+import java.util.logging.Logger;
+
+import static org.openremote.manager.server.util.JsonUtil.JSON;
+
+@RunWith(VertxUnitRunner.class)
+public class DevicesTest {
+
+ private static final Logger LOG = Logger.getLogger(DevicesTest.class.getName());
+
+ private Vertx vertx;
+ private int ephemeralPort;
+
+ @Before
+ public void setUp(TestContext context) {
+ vertx = Vertx.vertx();
+
+ this.ephemeralPort = findEphemeralPort();
+
+ DeploymentOptions options = new DeploymentOptions().setConfig(
+ new JsonObject().put(ServerVerticle.WEB_SERVER_PORT, ephemeralPort)
+ );
+
+ vertx.deployVerticle(
+ ServerVerticle.class.getName(),
+ options,
+ context.asyncAssertSuccess()
+ );
+ }
+
+ @After
+ public void tearDown(TestContext context) {
+ vertx.close(context.asyncAssertSuccess());
+ }
+
+ @Test
+ public void retrieveDevices(TestContext context) {
+ final Async async = context.async();
+
+ vertx.createHttpClient().getNow(ephemeralPort, "localhost", "/device",
+ response -> {
+ response.handler(body -> {
+ try {
+ JsonApiDocument jsonApiDocument =
+ JSON.readValue(body.toString(), JsonApiDocument.class);
+
+ context.assertTrue(
+ jsonApiDocument.getData().get().size() == 2
+ );
+
+ } catch (IOException ex) {
+ context.fail(ex);
+ }
+ async.complete();
+ });
+ });
+ }
+
+ protected Integer findEphemeralPort() {
+ try {
+ ServerSocket socket = new ServerSocket(0, 0, Inet4Address.getLocalHost());
+ int port = socket.getLocalPort();
+ socket.close();
+ return port;
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+}
\ No newline at end of file
diff --git a/manager/src/test/java/org/openremote/manager/test/MyFirstVerticleTest.java b/manager/src/test/java/org/openremote/manager/test/MyFirstVerticleTest.java
deleted file mode 100644
index 903183536..000000000
--- a/manager/src/test/java/org/openremote/manager/test/MyFirstVerticleTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package org.openremote.manager.test;
-
-import io.vertx.core.Vertx;
-import io.vertx.ext.unit.Async;
-import io.vertx.ext.unit.TestContext;
-import io.vertx.ext.unit.junit.VertxUnitRunner;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openremote.manager.server.ManagerVerticle;
-
-import java.util.logging.Logger;
-
-@RunWith(VertxUnitRunner.class)
-public class MyFirstVerticleTest {
-
- private static final Logger LOG = Logger.getLogger(MyFirstVerticleTest.class.getName());
-
- private Vertx vertx;
-
- @Before
- public void setUp(TestContext context) {
- vertx = Vertx.vertx();
-
- vertx.deployVerticle(
- ManagerVerticle.class.getName(),
- context.asyncAssertSuccess()
- );
- }
-
- @After
- public void tearDown(TestContext context) {
- vertx.close(context.asyncAssertSuccess());
- }
-
- @Test
- public void testMyApplication(TestContext context) {
- final Async async = context.async();
-
- vertx.createHttpClient().getNow(8080, "localhost", "/hello",
- response -> {
- response.handler(body -> {
- context.assertTrue(body.toString().contains("Hello"));
- async.complete();
- });
- });
- }
-}
\ No newline at end of file