100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Migrated sample data
Christian Bauer86fc1fbfd684
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex d0df83257..2315b7b43 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -1,21 +1,66 @@package org.openremote.container;+import com.fasterxml.jackson.annotation.JsonAutoDetect;+import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.PropertyAccessor;+import com.fasterxml.jackson.databind.DeserializationFeature;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.SerializationFeature;import com.fasterxml.jackson.databind.node.ObjectNode;+import java.io.IOException;+import java.io.InputStream;import java.util.*;import java.util.concurrent.ConcurrentHashMap;+import java.util.logging.LogManager;import java.util.logging.Logger;import java.util.stream.Stream;import java.util.stream.StreamSupport;public class Container {- private static final Logger LOG = ContainerRuntime.LOG;+ public static final Logger LOG;+ public static final ObjectMapper JSON;- public final ObjectNode CONFIG;+ static {+ if (System.getProperty("java.util.logging.config.file") == null) {+ try (InputStream is = Container.class.getClassLoader().getResourceAsStream("logging.properties")) {+ if (is != null) {+ LogManager.getLogManager().readConfiguration(is);+ }+ } catch (IOException ignore) {+ // Ignore+ }+ }++ LOG = Logger.getLogger(Container.class.getName());+ LOG.info("Starting runtime container...");++ JSON = new ObjectMapper();+ JSON.setSerializationInclusion(JsonInclude.Include.NON_NULL)+ .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)+ .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)+ .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)+ .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)+ .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)+ .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)+ .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE);+ }++ public static final String DEV_MODE = "DEV_MODE";+ public static final boolean DEV_MODE_DEFAULT = true;++ protected final ObjectNode config;+ protected final boolean devMode;protected final Map<Class<? extends ContainerService>, ContainerService> services = new ConcurrentHashMap<>();+ public static void configure(Container container) {+ if (container.getConfigBoolean(DEV_MODE, DEV_MODE_DEFAULT)) {+ JSON.enable(SerializationFeature.INDENT_OUTPUT);+ }+ }public Container() {this(System.getenv(),@@ -35,11 +80,12 @@ public class Container {@SafeVarargspublic Container(Map<String, String> config, Stream<ContainerService>... serviceStreams) {- CONFIG = ContainerRuntime.JSON.createObjectNode();+ this.config = JSON.createObjectNode();for (Map.Entry<String, String> entry : config.entrySet()) {- CONFIG.put(entry.getKey(), entry.getValue());+ this.config.put(entry.getKey(), entry.getValue());}- ContainerRuntime.configure(this);++ this.devMode = getConfigBoolean(DEV_MODE, DEV_MODE_DEFAULT);if (serviceStreams != null) {for (Stream<ContainerService> serviceStream : serviceStreams) {@@ -47,19 +93,27 @@ public class Container {}}- ContainerRuntime.addShutdownHook(this::stop);+ Runtime.getRuntime().addShutdownHook(new Thread(this::stop));+ }++ public ObjectNode getConfig() {+ return config;}public String getConfig(String variable, String defaultValue) {- return CONFIG.has(variable) ? CONFIG.get(variable).asText() : defaultValue;+ return config.has(variable) ? config.get(variable).asText() : defaultValue;}public boolean getConfigBoolean(String variable, boolean defaultValue) {- return CONFIG.has(variable) ? CONFIG.get(variable).asBoolean() : defaultValue;+ return config.has(variable) ? config.get(variable).asBoolean() : defaultValue;}public int getConfigInteger(String variable, int defaultValue) {- return CONFIG.has(variable) ? CONFIG.get(variable).asInt() : defaultValue;+ return config.has(variable) ? config.get(variable).asInt() : defaultValue;+ }++ public boolean isDevMode() {+ return devMode;}synchronized public void start() {diff --git a/container/src/main/java/org/openremote/container/ContainerRuntime.java b/container/src/main/java/org/openremote/container/ContainerRuntime.javadeleted file mode 100644index 23670a942..000000000--- a/container/src/main/java/org/openremote/container/ContainerRuntime.java+++ /dev/null@@ -1,59 +0,0 @@-package org.openremote.container;--import com.fasterxml.jackson.annotation.JsonAutoDetect;-import com.fasterxml.jackson.annotation.JsonInclude;-import com.fasterxml.jackson.annotation.PropertyAccessor;-import com.fasterxml.jackson.databind.DeserializationFeature;-import com.fasterxml.jackson.databind.ObjectMapper;-import com.fasterxml.jackson.databind.SerializationFeature;--import java.io.IOException;-import java.io.InputStream;-import java.util.logging.LogManager;-import java.util.logging.Logger;--public class ContainerRuntime {-- public static final String DEV_MODE = "DEV_MODE";- public static final boolean DEV_MODE_DEFAULT = true;-- public static final Logger LOG;- public static final ObjectMapper JSON;-- static {- if (System.getProperty("java.util.logging.config.file") == null) {- try (InputStream is = Container.class.getClassLoader().getResourceAsStream("logging.properties")) {- if (is != null) {- LogManager.getLogManager().readConfiguration(is);- }- } catch (IOException ignore) {- // Ignore- }- }-- LOG = Logger.getLogger(ContainerRuntime.class.getName());- LOG.info("Starting runtime container...");-- JSON = new ObjectMapper();- JSON.setSerializationInclusion(JsonInclude.Include.NON_NULL)- .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)- .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)- .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)- .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)- .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)- .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)- .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)- .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE);- }-- public static void configure(Container container) {- if (container.getConfigBoolean(DEV_MODE, DEV_MODE_DEFAULT)) {- JSON.enable(SerializationFeature.INDENT_OUTPUT);- }- }-- public static void addShutdownHook(Runnable runnable) {- java.lang.Runtime.getRuntime().addShutdownHook(new Thread(runnable));- }--}diff --git a/container/src/main/java/org/openremote/container/web/JacksonConfig.java b/container/src/main/java/org/openremote/container/web/JacksonConfig.javaindex 04becfc70..7510dcd90 100644--- a/container/src/main/java/org/openremote/container/web/JacksonConfig.java+++ b/container/src/main/java/org/openremote/container/web/JacksonConfig.java@@ -1,7 +1,7 @@package org.openremote.container.web;import com.fasterxml.jackson.databind.ObjectMapper;-import org.openremote.container.ContainerRuntime;+import org.openremote.container.Container;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;@@ -14,6 +14,6 @@ public class JacksonConfig implements ContextResolver<ObjectMapper> {@Overridepublic ObjectMapper getContext(Class<?> type) {- return ContainerRuntime.JSON;+ return Container.JSON;}}\ No newline at end of filediff --git a/manager/src/main/java/org/openremote/manager/server2/SampleDataService.java b/manager/src/main/java/org/openremote/manager/server2/SampleDataService.javanew file mode 100644index 000000000..296201606--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/server2/SampleDataService.java@@ -0,0 +1,230 @@+package org.openremote.manager.server2;++import elemental.json.Json;+import org.apache.log4j.Logger;+import org.keycloak.representations.idm.*;+import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.manager.server.contextbroker.ContextBrokerService;+import org.openremote.manager.server.util.UrlUtil;+import org.openremote.manager.server2.identity.AuthForm;+import org.openremote.manager.server2.identity.IdentityService;+import org.openremote.manager.server2.identity.Keycloak;+import org.openremote.manager.shared.model.ngsi.Attribute;+import org.openremote.manager.shared.model.ngsi.Entity;+import rx.Observable;++import java.util.ArrayList;+import java.util.List;++import static javax.ws.rs.core.MediaType.APPLICATION_JSON;+import static org.openremote.manager.server.Constants.MANAGER_CLIENT_ID;+import static org.openremote.manager.server.Constants.MASTER_REALM;+import static org.openremote.manager.server.identity.KeycloakClient.ADMIN_CLI_CLIENT;+import static org.openremote.manager.server.util.IdentifierUtil.generateGlobalUniqueId;+import static rx.Observable.fromCallable;++public class SampleDataService implements ContainerService {++ private static final Logger LOG = Logger.getLogger(SampleDataService.class.getName());++ public static final String IMPORT_SAMPLE_DATA = "IMPORT_SAMPLE_DATA";+ public static final boolean IMPORT_SAMPLE_DATA_DEFAULT = false;++ public static final String ADMIN_USERNAME = "admin";+ public static final String ADMIN_PASSWORD = "admin";++ protected IdentityService identityService;+ /* TODO+ protected ContextBrokerService contextBrokerService,+ protected PersistenceService persistenceService+ */++ @Override+ public void prepare(Container container) {+ if (!container.isDevMode())+ return;++ identityService = container.getService(IdentityService.class);+ }++ @Override+ public void start(Container container) {+ if (!container.isDevMode())+ return;++ LOG.info("--- CREATING SAMPLE DATA ---");++ String accessToken = identityService.getKeycloak().getAccessToken(+ MASTER_REALM, new AuthForm(ADMIN_CLI_CLIENT, ADMIN_USERNAME, ADMIN_PASSWORD)+ ).getToken();++ configureMasterRealm(identityService, accessToken);+ registerClientApplications(identityService, accessToken);+ addRolesAndTestUsers(identityService, accessToken);++ /* TODO+ createSampleRooms(contextBrokerService);++ persistenceService.createSchema();+ EntityManager em = persistenceService.getEntityManagerFactory().createEntityManager();+ EntityTransaction tx = em.getTransaction();+ tx.begin();+ em.persist(someSampleData);+ tx.commit();+ */+ }++ @Override+ public void stop(Container container) {+ }++ protected void createSampleRooms(ContextBrokerService contextBrokerService) {+ Entity room1 = new Entity(Json.createObject());+ room1.setId(generateGlobalUniqueId());+ room1.setType("Room");+ room1.addAttribute(+ new Attribute("temperature", Json.createObject())+ .setType("float")+ .setValue(Json.create(21.3))+ ).addAttribute(+ new Attribute("label", Json.createObject())+ .setType("string")+ .setValue(Json.create("Office 123"))+ );++ Entity room2 = new Entity(Json.createObject());+ room2.setId(generateGlobalUniqueId());+ room2.setType("Room");+ room2.addAttribute(+ new Attribute("temperature", Json.createObject())+ .setType("float")+ .setValue(Json.create(22.1))+ ).addAttribute(+ new Attribute("label", Json.createObject())+ .setType("string")+ .setValue(Json.create("Office 456"))+ );+++ contextBrokerService.getClient().listEntities()+ .flatMap(Observable::from)+ .flatMap(entity -> contextBrokerService.getClient().deleteEntity(entity))+ .toList().toBlocking().single();++ contextBrokerService.getClient().postEntity(room1).toBlocking().first();+ contextBrokerService.getClient().postEntity(room2).toBlocking().first();+ }++ protected void configureMasterRealm(IdentityService identityService, String accessToken) {+ Keycloak keycloak = identityService.getKeycloak(accessToken);++ RealmRepresentation masterRealm = keycloak.getRealm(MASTER_REALM);++ masterRealm.setDisplayNameHtml("<div class=\"kc-logo-text\"><span>OpenRemote</span></div>");++ masterRealm.setLoginTheme("openremote");++ keycloak.putRealm(MASTER_REALM, masterRealm);+ }++ protected void registerClientApplications(IdentityService identityService, String accessToken) {+ Keycloak keycloak = identityService.getKeycloak(accessToken);++ // Find out if there is a client already present for this application, if so, delete it+ fromCallable(() -> keycloak.getClientApplications(MASTER_REALM))+ .flatMap(Observable::from)+ .filter(clientRepresentation -> clientRepresentation.getClientId().equals(MANAGER_CLIENT_ID))+ .map(ClientRepresentation::getId)+ .subscribe(clientObjectId -> {+ keycloak.deleteClientApplication(MASTER_REALM, clientObjectId);+ });++ // Register a new client for this application+ ClientRepresentation managerClient = new ClientRepresentation();++ managerClient.setRegistrationAccessToken(accessToken);++ managerClient.setClientId(MANAGER_CLIENT_ID);++ managerClient.setName("OpenRemote Manager");+ managerClient.setPublicClient(true);++ String callbackUrl = UrlUtil.url(+ identityService.isConfigNetworkSecure() ? "https" : "http",+ identityService.getConfigNetworkHost(),+ identityService.getConfigNetworkWebserverPort(),+ MASTER_REALM+ ).toString();++ List<String> redirectUrls = new ArrayList<>();+ redirectUrls.add(callbackUrl);+ managerClient.setRedirectUris(redirectUrls);++ String clientResourceLocation =+ keycloak.registerClientApplication(MASTER_REALM, managerClient).getLocation().toString();++ LOG.info("Registered client application '" + MANAGER_CLIENT_ID + "' with identity provider: " + clientResourceLocation);+ }++ protected void addRolesAndTestUsers(IdentityService identityService, String accessToken) {+ Keycloak keycloak = identityService.getKeycloak(accessToken);++ String clientObjectId = fromCallable(() -> keycloak.getClientApplications(MASTER_REALM))+ .flatMap(Observable::from)+ .filter(clientRepresentation -> clientRepresentation.getClientId().equals(MANAGER_CLIENT_ID))+ .map(ClientRepresentation::getId)+ .toBlocking().singleOrDefault(null);++ // Register some roles+ RoleRepresentation readRole =+ fromCallable(() -> keycloak.createRoleForClientApplication(+ MASTER_REALM, clientObjectId, new RoleRepresentation("read", "Read all data", false)+ )).map(response ->+ identityService.getTarget(response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)+ ).toBlocking().single();+ LOG.info("Added role '" + readRole.getName() + "'");++ RoleRepresentation readMapRole =+ fromCallable(() -> keycloak.createRoleForClientApplication(+ MASTER_REALM, clientObjectId, new RoleRepresentation("read:map", "View map", false)+ )).map(response ->+ identityService.getTarget(response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)+ ).toBlocking().single();++ keycloak.addCompositesToRoleForClientApplication(+ MASTER_REALM, clientObjectId, readRole.getName(), new RoleRepresentation[]{readMapRole}+ );+ LOG.info("Added role '" + readMapRole.getName() + "'");++ // Find out if there is a 'test' user already present+ fromCallable(() -> keycloak.getUsers(MASTER_REALM))+ .flatMap(Observable::from)+ .filter(userRepresentation -> userRepresentation.getUsername().equals("test"))+ .subscribe(userRepresentation -> keycloak.deleteUser(MASTER_REALM, userRepresentation.getId()));++ // Create a new 'test' user with 'read' role+ UserRepresentation testUser = new UserRepresentation();+ testUser.setUsername("test");+ testUser.setFirstName("Testuserfirst");+ testUser.setLastName("Testuserlast");+ testUser.setEnabled(true);+ final UserRepresentation finalTestUser = testUser;+ testUser = fromCallable(() -> keycloak.createUser(MASTER_REALM, finalTestUser))+ .map(response ->+ identityService.getTarget(response.getLocation(), accessToken).request(APPLICATION_JSON).get(UserRepresentation.class)+ ).toBlocking().single();++ CredentialRepresentation testUserCredential = new CredentialRepresentation();+ testUserCredential.setType("password");+ testUserCredential.setValue("test");+ testUserCredential.setTemporary(false);+ keycloak.resetPassword(MASTER_REALM, testUser.getId(), testUserCredential);++ LOG.info("Added user '" + testUser.getUsername() + "' with password '" + testUserCredential.getValue() + "'");++ // Add mapping for client role 'read' to user 'test'+ keycloak.addUserClientRoleMapping(MASTER_REALM, testUser.getId(), clientObjectId, new RoleRepresentation[]{readRole});++ }+}diff --git a/manager/src/main/java/org/openremote/manager/server2/Server.java b/manager/src/main/java/org/openremote/manager/server2/Server.javaindex 1f5f9fcf6..ba7169245 100644--- a/manager/src/main/java/org/openremote/manager/server2/Server.java+++ b/manager/src/main/java/org/openremote/manager/server2/Server.java@@ -5,7 +5,9 @@ import org.openremote.container.Container;public class Server {public static void main(String[] args) {- Container container = new Container();++ Container container = new Container(new SampleDataService());+container.start();}}diff --git a/manager/src/main/java/org/openremote/manager/server2/identity/AuthForm.java b/manager/src/main/java/org/openremote/manager/server2/identity/AuthForm.javaindex 5b77d3cfe..43a9fbbed 100644--- a/manager/src/main/java/org/openremote/manager/server2/identity/AuthForm.java+++ b/manager/src/main/java/org/openremote/manager/server2/identity/AuthForm.java@@ -19,6 +19,10 @@ public class AuthForm {public AuthForm() {}+ public AuthForm(String clientId, String username, String password) {+ this(clientId, username, password, "password");+ }+public AuthForm(String clientId, String username, String password, String grantType) {this.clientId = clientId;this.username = username;diff --git a/manager/src/main/java/org/openremote/manager/server2/identity/IdentityService.java b/manager/src/main/java/org/openremote/manager/server2/identity/IdentityService.javaindex 4446db0d2..c5dbcf919 100644--- a/manager/src/main/java/org/openremote/manager/server2/identity/IdentityService.java+++ b/manager/src/main/java/org/openremote/manager/server2/identity/IdentityService.java@@ -28,6 +28,7 @@ import javax.ws.rs.core.Response;import javax.ws.rs.core.UriBuilder;import java.io.IOException;import java.io.UnsupportedEncodingException;+import java.net.URI;import java.util.Base64;import java.util.concurrent.TimeUnit;import java.util.logging.Level;@@ -219,11 +220,11 @@ public class IdentityService implements ContainerService {return configNetworkWebserverPort;}- protected ResteasyWebTarget getTarget() {- return getTarget(keycloakServiceUri, null);+ public ResteasyWebTarget getTarget() {+ return getTarget(keycloakServiceUri.build(), null);}- protected ResteasyWebTarget getTarget(UriBuilder uri, String accessToken) {+ public ResteasyWebTarget getTarget(URI uri, String accessToken) {ResteasyWebTarget target = ((ResteasyWebTarget) client.target(uri));if (accessToken != null) {target.property("accessToken", accessToken);@@ -231,7 +232,7 @@ public class IdentityService implements ContainerService {return target;}- protected ResteasyWebTarget getTarget(UriBuilder uri, String clientId, String clientSecret) {+ public ResteasyWebTarget getTarget(URI uri, String clientId, String clientSecret) {ResteasyWebTarget target = getTarget(uri, null);if (clientId != null) {target.property("clientId", clientId);@@ -242,19 +243,19 @@ public class IdentityService implements ContainerService {return target;}- protected Keycloak getKeycloak() {- return getKeycloak(getTarget(keycloakServiceUri, null));+ public Keycloak getKeycloak() {+ return getKeycloak(getTarget(keycloakServiceUri.build(), null));}- protected Keycloak getKeycloak(String accessToken) {- return getKeycloak(getTarget(keycloakServiceUri, accessToken));+ public Keycloak getKeycloak(String accessToken) {+ return getKeycloak(getTarget(keycloakServiceUri.build(), accessToken));}- protected Keycloak getKeycloak(ResteasyWebTarget target) {+ public Keycloak getKeycloak(ResteasyWebTarget target) {return target.proxy(Keycloak.class);}- protected void pingKeycloak() {+ public void pingKeycloak() {Observable.fromCallable(() -> {Response response = getKeycloak().getWelcomePage();try {diff --git a/manager/src/main/java/org/openremote/manager/server2/map/MapService.java b/manager/src/main/java/org/openremote/manager/server2/map/MapService.javaindex bb09a626f..269817723 100644--- a/manager/src/main/java/org/openremote/manager/server2/map/MapService.java+++ b/manager/src/main/java/org/openremote/manager/server2/map/MapService.java@@ -14,7 +14,7 @@ import java.util.HashMap;import java.util.Map;import java.util.logging.Logger;-import static org.openremote.container.ContainerRuntime.JSON;+import static org.openremote.container.Container.JSON;import static org.openremote.manager.server.Constants.*;public class MapService implements ContainerService {@@ -36,7 +36,7 @@ public class MapService implements ContainerService {@Overridepublic void prepare(Container container) {- this.devMode = container.getConfigBoolean(DEV_MODE, DEV_MODE_DEFAULT);+ this.devMode = container.isDevMode();mapTilesPath = Paths.get(container.getConfig(MAP_TILES_PATH, MAP_TILES_PATH_DEFAULT));if (!Files.isRegularFile(mapTilesPath)) {