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
Persist manager_config.json across deployments and improve test robustness (#1414)
Panos Kalogeropoulosec2c17e40346
diff --git a/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java b/container/src/main/java/org/openremote/container/web/WebServiceExceptions.javaindex 17c7f3fae..fd8492a07 100644--- a/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java+++ b/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java@@ -222,10 +222,16 @@ public class WebServiceExceptions {if ("java.io.IOException: Connection reset by peer".equals(getRootCause(throwable).toString()))return;- if (throwable instanceof WebApplicationException && ((WebApplicationException) throwable).getResponse().getStatus() == 404) {+ if (throwable instanceof WebApplicationException) {+ int statusCode = ((WebApplicationException) throwable).getResponse().getStatus();+ if (statusCode == 404) {// Don't stack trace 404s just want request uriLOG.log(Level.FINE, "Web service exception (404) in '" + origin + "' for '" + info + "'");return;+ } else if (statusCode >= 200 && statusCode < 300) {+ LOG.log(Level.FINE, "Web service response ("+statusCode+") in '" + origin + "' for '" + info + "'");+ return;+ }}if (LOG.isLoggable(Level.FINE)) {diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.javaindex 2ebd74362..2414b81a6 100644--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java@@ -414,7 +414,7 @@ public class AgentService extends RouteBuilder implements ContainerService {LOG.fine("Starting protocol instance: " + protocol);protocol.start(container);protocolInstanceMap.put(agent.getId(), protocol);- LOG.fine("Started protocol instance:" + protocol);+ LOG.fine("Started protocol instance: " + protocol);LOG.finest("Linking attributes to protocol instance: " + protocol);@@ -447,7 +447,7 @@ public class AgentService extends RouteBuilder implements ContainerService {}}protocolInstanceMap.remove(agent.getId());- LOG.log(Level.SEVERE, "Failed to start protocol '" + protocol + "': " + agent, e);+ LOG.log(Level.SEVERE, "Failed to start protocol '" + protocol + "': " + agent + " msg=" + e.getMessage());sendAttributeEvent(new AttributeEvent(agent.getId(), Agent.STATUS.getName(), ConnectionStatus.ERROR));}}@@ -499,7 +499,7 @@ public class AgentService extends RouteBuilder implements ContainerService {protocol.linkAttribute(assetId, attribute);}} catch (Exception ex) {- LOG.log(Level.SEVERE, "Failed to link attribute '" + attributeRef + "' to protocol: " + protocol, ex);+ LOG.log(Level.SEVERE, "Failed to link attribute '" + attributeRef + "' to protocol: " + protocol + " msg=" + ex.getMessage());}});}@@ -601,6 +601,11 @@ public class AgentService extends RouteBuilder implements ContainerService {return;}+ // Ignore events that have come from the AssetStorageService (i.e. Asset merges as these are handled separately)+ if (AssetStorageService.class.getSimpleName().equals(event.getSource())) {+ return;+ }+// Update in memory agentagent.getAttribute(event.getName()).ifPresent(attr -> attr.setValue(event.getValue().orElse(null), event.getTimestamp()));diff --git a/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.java b/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.javaindex ecce4a074..9e77cc048 100644--- a/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/app/ConfigurationResourceImpl.java@@ -19,6 +19,9 @@*/package org.openremote.manager.app;+import com.fasterxml.jackson.databind.node.ObjectNode;+import jakarta.ws.rs.InternalServerErrorException;+import jakarta.ws.rs.core.Response;import org.openremote.container.timer.TimerService;import org.openremote.container.web.WebService;import org.openremote.manager.security.ManagerIdentityService;@@ -27,6 +30,10 @@ import org.openremote.model.manager.ConfigurationResource;import org.openremote.model.file.FileInfo;import org.openremote.model.http.RequestParams;+import java.io.*;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.NoSuchElementException;import java.util.logging.Logger;public class ConfigurationResourceImpl extends ManagerWebResource implements ConfigurationResource {@@ -39,16 +46,61 @@ public class ConfigurationResourceImpl extends ManagerWebResource implements Conthis.configurationService = configurationService;}-@Override- public Object update(RequestParams requestParams, Object managerConfiguration) {- this.configurationService.saveMangerConfig(managerConfiguration);+ public ObjectNode update(RequestParams requestParams, ObjectNode managerConfiguration) {+ try {+ this.configurationService.saveManagerConfig(managerConfiguration);+ } catch (Exception e) {+ LOG.warning("Couldn't store manager_config.json:" +e.getMessage());+ throw new InternalServerErrorException("Error updating manager_config.json");+ }return managerConfiguration;}@Overridepublic String fileUpload(RequestParams requestParams, String path, FileInfo fileInfo) {- this.configurationService.saveImageFile(path, fileInfo);- return path;+ try {+ this.configurationService.saveManagerConfigImage(path, fileInfo);+ } catch (Exception e) {+ LOG.warning("Save image failed '" + path + "': " + e.getMessage());+ throw new InternalServerErrorException("Error storing image");+ }+ Path managerConfigPath = Path.of("/api")+ .resolve("master")+ .resolve("configuration")+ .resolve("manager")+ .resolve("image")+ .resolve(path);++ return managerConfigPath.toString();+ }++ @Override+ public ObjectNode getManagerConfig() {+ return configurationService.getManagerConfig();+ }++ @Override+ public Object getManagerConfigImage(String fileName) {+ try {+ File imageFile = configurationService.getManagerConfigImage(fileName).orElseThrow();+ if (!imageFile.exists()) {+ return Response.status(Response.Status.NOT_FOUND).build();+ }++ String mimeType = Files.probeContentType(imageFile.toPath());+ if (mimeType == null) {+ mimeType = "application/octet-stream";+ }++ Response.ResponseBuilder response = Response.ok(imageFile, mimeType);+ return response.build();+ }+ catch (NoSuchElementException e){+ return Response.status(Response.Status.NOT_FOUND).entity("Image not Found").build();+ }+ catch (Exception e) {+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error retrieving image").build();+ }}}diff --git a/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java b/manager/src/main/java/org/openremote/manager/app/ConfigurationService.javaindex a9e101c84..73864b351 100644--- a/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java+++ b/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java@@ -19,11 +19,11 @@*/package org.openremote.manager.app;-import org.apache.camel.builder.RouteBuilder;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.node.ObjectNode;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;import org.openremote.container.util.CodecUtil;-import org.openremote.container.web.WebService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;import org.openremote.model.Container;@@ -31,33 +31,41 @@ import org.openremote.model.ContainerService;import org.openremote.model.file.FileInfo;import org.openremote.model.util.ValueUtil;-import java.io.*;+import java.io.File;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;+import java.util.Iterator;+import java.util.List;+import java.util.Map;+import java.util.Optional;import java.util.logging.Level;import java.util.logging.Logger;+import java.util.stream.Stream;+import static org.openremote.container.util.MapAccess.getString;import static org.openremote.manager.web.ManagerWebService.OR_CUSTOM_APP_DOCROOT;import static org.openremote.manager.web.ManagerWebService.OR_CUSTOM_APP_DOCROOT_DEFAULT;-import static org.openremote.container.util.MapAccess.getString;-public class ConfigurationService extends RouteBuilder implements ContainerService {+public class ConfigurationService implements ContainerService {++ public static final String OR_MAP_SETTINGS_PATH = "OR_MAP_SETTINGS_PATH";+ public static final String OR_MAP_SETTINGS_PATH_DEFAULT = "manager/src/map/mapsettings.json";++ public static final String OR_MAP_TILES_PATH = "OR_MAP_TILES_PATH";+ public static final String OR_MAP_TILES_PATH_DEFAULT = "manager/src/map/mapdata.mbtiles";protected ManagerIdentityService identityService;protected PersistenceService persistenceService;protected Path pathPublicRoot;- private static final Logger LOG = Logger.getLogger(WebService.class.getName());+ private static final Logger LOG = Logger.getLogger(ConfigurationService.class.getName());- @Override- public int getPriority() {- return ContainerService.DEFAULT_PRIORITY;- }-- @Override- public void configure() throws Exception {- /* code not overridden yet */- }+ protected Path mapTilesPath;+ protected Path mapSettingsPath;+ protected Path managerConfigPath;@Overridepublic void init(Container container) throws Exception {@@ -69,11 +77,41 @@ public class ConfigurationService extends RouteBuilder implements ContainerServicontainer.getService(TimerService.class),identityService, this));++ // Retrieve default configuration files; Try to find all possible default locations of each file, and then+ // return the first one. Since the stream maintains ordering, we use the first available one, since they're placed+ // below in order of most importance. Throw an Exception if no default file could be found.++ mapSettingsPath = Stream.of(getPersistedMapConfigPath().toString(), getString(container.getConfig(), OR_MAP_SETTINGS_PATH, OR_MAP_SETTINGS_PATH_DEFAULT), "/opt/map/mapsettings.json", OR_MAP_SETTINGS_PATH_DEFAULT)+ .map(Path::of)+ .map(Path::toAbsolutePath)+ .filter(Files::isRegularFile)+ .findFirst().orElse(null);++ mapTilesPath = Stream.of(getString(container.getConfig(), OR_MAP_TILES_PATH, OR_MAP_TILES_PATH_DEFAULT), "/deployment/map/mapdata.mbtiles", "/opt/map/mapdata.mbtiles", OR_MAP_TILES_PATH_DEFAULT)+ .map(Path::of)+ .map(Path::toAbsolutePath)+ .filter(Files::isRegularFile)+ .findFirst().orElse(null);++ managerConfigPath = Stream.of(getPersistedManagerConfigPath(), pathPublicRoot.resolve("manager_config.json"))+ .map(Path::toAbsolutePath)+ .filter(Files::isRegularFile)+ .findFirst().orElse(null);++ if (mapSettingsPath == null) {+ LOG.warning("Could not find map settings");+ return;+ }++ LOG.info("Configuration Service Used files:");+ LOG.info("\t- manager_config.json: " + managerConfigPath);+ LOG.info("\t- mapsettings.json: " + mapSettingsPath);+ LOG.info("\t- mapdata.mbtiles: " + mapTilesPath);}@Overridepublic void start(Container container) throws Exception {- /* code not overridden yet */}@Override@@ -81,36 +119,178 @@ public class ConfigurationService extends RouteBuilder implements ContainerServi/* code not overridden yet */}+ @Override+ public String toString() {+ return "ConfigurationService{" ++ "mapTilesPath=" + mapTilesPath ++ ", mapSettingsPath=" + mapSettingsPath ++ ", managerConfigPath=" + managerConfigPath ++ '}';+ }- public void saveMangerConfig(Object managerConfiguration) {- LOG.log(Level.INFO, "Saving manager_config.json..");- try (OutputStream out = new FileOutputStream(pathPublicRoot + "/manager_config.json")) {- out.write(ValueUtil.JSON.writeValueAsString(managerConfiguration).getBytes());- } catch (IOException | SecurityException exception) {- LOG.log(Level.WARNING, "Error when trying to save manager_config.json", exception);+ public ObjectNode getMapConfig() {+ if (mapSettingsPath == null) {+ return null;+ }+ try {+ return (ObjectNode) ValueUtil.JSON.readTree(mapSettingsPath.toFile());+ } catch (IOException e) {+ LOG.severe("Could not read map_settings.json from " + mapSettingsPath);}+ return null;}+ public void saveMapConfig(ObjectNode mapConfiguration) throws RuntimeException {+ LOG.log(Level.INFO, "Saving map_settings.json to: " + getPersistedMapConfigPath());+ try {+ Path p = getPersistedMapConfigPath();+ File file = p.toAbsolutePath().toFile();+ if (!file.getParentFile().exists()) file.getParentFile().mkdirs();- public void saveImageFile(String path, FileInfo fileInfo) {- LOG.log(Level.INFO, "Saving image in manger_config.json..");- File file = new File(pathPublicRoot + path);+ Files.writeString(p, ValueUtil.JSON.writeValueAsString(mapConfiguration), StandardCharsets.UTF_8);+ // Ensure mapSettingsPath is now pointing to persistence path+ mapSettingsPath = p;+ } catch (Exception exception) {+ String msg = "Error saving map_settings.json: msg=" + exception.getMessage();+ LOG.log(Level.WARNING, msg);+ throw new IllegalStateException(msg);+ }+ }++ public Path getMapTilesPath() {+ return mapTilesPath;+ }++ public ObjectNode getManagerConfig() {+ if (managerConfigPath == null) {+ return null;+ }try {- file.getParentFile().mkdirs();- if (file.exists()) {- file.delete();+ return (ObjectNode) ValueUtil.JSON.readTree(managerConfigPath.toFile());+ } catch (Exception e) {+ LOG.severe("Could not read manager_config.json from " + managerConfigPath);+ return null;+ }+ }++ public void saveManagerConfig(ObjectNode managerConfiguration) throws Exception {+ LOG.log(Level.INFO, "Saving manager_config.json to: " + getPersistedManagerConfigPath());++ try {+ // Check references to images+ managerConfiguration = checkAndFixImageReferences(managerConfiguration);+ Path p = getPersistedManagerConfigPath();+ File file = p.toAbsolutePath().toFile();+ if (!file.getParentFile().exists()) file.getParentFile().mkdirs();++ Files.writeString(p, ValueUtil.JSON.writeValueAsString(managerConfiguration), StandardCharsets.UTF_8);+ // Ensure managerConfigPath is now pointing to persistence path+ managerConfigPath = p;+ } catch (Exception exception) {+ String msg = "Error saving manager_config.json: msg=" + exception.getMessage();+ LOG.log(Level.WARNING, msg);+ throw new Exception(msg);+ }+ }++ public void saveManagerConfigImage(String path, FileInfo fileInfo) throws Exception {+ LOG.log(Level.INFO, "Saving image in manager_config.json: " + fileInfo);+ path = path.replace("/images/", "");+ path = path.charAt(0) == '/' ? path.substring(1) : path;+ Path resolvedPath = Path.of(path);+ resolvedPath = getPersistedManagerConfigImagePath().resolve(resolvedPath);+ Path filePath = getPersistedManagerConfigImagePath().resolve(path);+ File file = filePath.toAbsolutePath().toFile();++ try {+ boolean isValid = resolvedPath.toFile().getCanonicalPath().contains(getPersistedManagerConfigImagePath().toFile().getCanonicalPath() + File.separator);++ if (!isValid) {+ String msg = "Failed to save manager config image path outside permitted directory: " + resolvedPath;+ LOG.warning(msg);+ throw new Exception("Failed to save manager config image path outside permitted directory: " + resolvedPath);}- } catch (SecurityException se) {- LOG.log(Level.WARNING, "Could not access folder for editing image in manager_config.json");- return;++ if (!file.getParentFile().exists()) file.getParentFile().mkdirs();+ Files.write(filePath, CodecUtil.decodeBase64(fileInfo.getContents()));+ } catch (Exception exception) {+ String msg = "Error saving image in manager_config.json '" + filePath + "': msg=" + exception.getMessage();+ LOG.log(Level.WARNING, msg);+ throw new Exception(msg);}+ }++ public Optional<File> getManagerConfigImage(String filename) {+ File file = getPersistedManagerConfigImagePath().resolve(filename).toFile();+ String checkPath;- try (OutputStream out = new FileOutputStream(file)) {- out.write(CodecUtil.decodeBase64(fileInfo.getContents()));- } catch (IOException | SecurityException exception) {- LOG.log(Level.WARNING, "Error when saving image in manger_config.json", exception);+ try {+ if (file.isFile()) {+ checkPath = getPersistedManagerConfigImagePath().toFile().getCanonicalPath();+ } else {+ // fallback to OR_CUSTOM_APP_DOCROOT+ file = pathPublicRoot.resolve("images").resolve(filename).toFile();+ checkPath = pathPublicRoot.toFile().getCanonicalPath();+ }++ //Check if the file retrieved is somewhere within the allowed directory.+ boolean isValid = file.getCanonicalPath().contains(checkPath + File.separator);+ if (!isValid) return Optional.empty();+ } catch (IOException e) {+ return Optional.empty();}+ return file.isFile() ? Optional.of(file) : Optional.empty();+ }++ protected Path getPersistedManagerConfigPath() {+ return persistenceService.getStorageDir().resolve("manager").resolve("manager_config.json");+ }++ protected Path getPersistedMapConfigPath() {+ return persistenceService.getStorageDir().resolve("manager").resolve("mapsettings.json");+ }++ protected Path getPersistedManagerConfigImagePath() {+ return this.persistenceService.resolvePath("manager").resolve("images");+ }++ protected ObjectNode checkAndFixImageReferences(ObjectNode managerConfig) {++ List<String> imageTypes = List.of("logo", "logoMobile", "favicon");+ if (!getPersistedManagerConfigImagePath().toFile().exists()) getPersistedManagerConfigImagePath().toFile().mkdirs();+ for (Iterator<Map.Entry<String, JsonNode>> it = managerConfig.get("realms").fields(); it.hasNext(); ) {+ Map.Entry<String, JsonNode> kvp = it.next();+ String realmName = kvp.getKey();+ JsonNode realm = kvp.getValue();+ for (String type : imageTypes) {+ String image = realm.get(type) != null ? realm.get(type).asText() : "";+ if (!image.isBlank()) {+ image = image.replace("/api/master/configuration/manager/image/", "");+ image = image.replace("images/", "");+ image = image.charAt(0) == '/' ? image.substring(1) : image;+ Path imagePath = Path.of(image);+ Path persistedImagePath = getPersistedManagerConfigImagePath().resolve(imagePath).toAbsolutePath();+ Path path = pathPublicRoot.resolve("images").resolve(imagePath).toAbsolutePath();++ if (!Files.isRegularFile(persistedImagePath)) {+ if (Files.isRegularFile(path)) {+ try {+ // Image doesn't exist in persisted path but does exist in doc root so copy it+ Files.copy(path, persistedImagePath);+ // Change the reference in the config to the typical API-like reference:+ ((ObjectNode) managerConfig.get("realms").get(realmName)).put(type, "/api/master/configuration/manager/image/" + imagePath);+ } catch (Exception e) {+ LOG.warning("Error occurred whilst copying manager config image to persisted path: " + imagePath);+ }+ } else {+ LOG.warning("manager_config.json image reference doesn't exist: " + imagePath);+ }+ }+ }+ }+ }+ return managerConfig;}}diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex c612e2dfb..815975a68 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -1351,6 +1351,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicnewAttribute.getTimestamp().orElse(0L),newAttribute.getValue().orElse(null),newAttribute.getTimestamp().orElse(0L))+ .setSource(getClass().getSimpleName())));}case UPDATE -> {@@ -1376,6 +1377,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic.forEach(obsoleteAttribute ->clientEventService.publishEvent(new AttributeEvent(asset, obsoleteAttribute, getClass().getSimpleName(), null, timerService.getCurrentTimeMillis(), null, 0L)+ .setSource(getClass().getSimpleName()).setDeleted(true)));}@@ -1401,7 +1403,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicnewOrModifiedAttribute.getTimestamp().orElse(0L),oldAttribute.flatMap(Attribute::getValue).orElse(null),oldAttribute.flatMap(Attribute::getTimestamp).orElse(0L)- ));+ ).setSource(getClass().getSimpleName()));});}case DELETE -> {@@ -1419,6 +1421,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicdeletedAttributes.forEach(obsoleteAttribute ->clientEventService.publishEvent(new AttributeEvent(asset, obsoleteAttribute, getClass().getSimpleName(), null, timerService.getCurrentTimeMillis(), null, 0L)+ .setSource(getClass().getSimpleName()).setDeleted(true)));}diff --git a/manager/src/main/java/org/openremote/manager/asset/OutdatedAttributeEvent.java b/manager/src/main/java/org/openremote/manager/asset/OutdatedAttributeEvent.javaindex eb674fcbf..1d14c55f1 100644--- a/manager/src/main/java/org/openremote/manager/asset/OutdatedAttributeEvent.java+++ b/manager/src/main/java/org/openremote/manager/asset/OutdatedAttributeEvent.java@@ -14,4 +14,8 @@ public class OutdatedAttributeEvent extends Event {super(event.getTimestamp());this.event = event;}++ public AttributeEvent getEvent() {+ return event;+ }}diff --git a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.javaindex 1516db0d4..350a2d62f 100644--- a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java@@ -68,7 +68,7 @@ public class MapResourceImpl extends WebResource implements MapResource {if (tile != null) {return tile;} else {- throw new WebApplicationException(Response.Status.NOT_FOUND);+ throw new WebApplicationException(Response.Status.NO_CONTENT);}}}diff --git a/manager/src/main/java/org/openremote/manager/map/MapService.java b/manager/src/main/java/org/openremote/manager/map/MapService.javaindex 08f7f41d3..9e2f0cad5 100644--- a/manager/src/main/java/org/openremote/manager/map/MapService.java+++ b/manager/src/main/java/org/openremote/manager/map/MapService.java@@ -25,7 +25,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.undertow.server.HttpHandler;import io.undertow.server.handlers.ResponseCodeHandler;import io.undertow.server.handlers.proxy.ProxyHandler;+import jakarta.ws.rs.core.UriBuilder;import org.openremote.container.web.WebService;+import org.openremote.manager.app.ConfigurationService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;import org.openremote.model.Container;@@ -34,12 +36,8 @@ import org.openremote.model.manager.MapRealmConfig;import org.openremote.model.util.TextUtil;import org.openremote.model.util.ValueUtil;-import jakarta.ws.rs.core.UriBuilder;-import java.io.*;import java.net.URI;-import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.sql.*;import java.util.HashMap;import java.util.Map;@@ -57,10 +55,6 @@ import static org.openremote.manager.web.ManagerWebService.API_PATH;public class MapService implements ContainerService {public static final String MAP_SHARED_DATA_BASE_URI = "/shared";- public static final String OR_MAP_TILES_PATH = "OR_MAP_TILES_PATH";- public static final String OR_MAP_TILES_PATH_DEFAULT = "manager/src/map/mapdata.mbtiles";- public static final String OR_MAP_SETTINGS_PATH = "OR_MAP_SETTINGS_PATH";- public static final String OR_MAP_SETTINGS_PATH_DEFAULT = "manager/src/map/mapsettings.json";public static final String OR_MAP_TILESERVER_HOST = "OR_MAP_TILESERVER_HOST";public static final String OR_MAP_TILESERVER_HOST_DEFAULT = null;public static final String OR_MAP_TILESERVER_PORT = "OR_MAP_TILESERVER_PORT";@@ -70,31 +64,22 @@ public class MapService implements ContainerService {public static final String OR_MAP_TILESERVER_REQUEST_TIMEOUT = "OR_MAP_TILESERVER_REQUEST_TIMEOUT";public static final int OR_MAP_TILESERVER_REQUEST_TIMEOUT_DEFAULT = 10000;private static final Logger LOG = Logger.getLogger(MapService.class.getName());+ private static ConfigurationService configurationService;// Shared SQL connection is fine concurrently in SQLiteprotected Connection connection;- protected Path mapTilesPath;- protected Path mapSettingsPath;protected Metadata metadata;protected ObjectNode mapConfig;protected ConcurrentMap<String, ObjectNode> mapSettings = new ConcurrentHashMap<>();protected ConcurrentMap<String, ObjectNode> mapSettingsJs = new ConcurrentHashMap<>();- public ObjectNode saveMapConfig(Map<String, MapRealmConfig> mapConfiguration) {- LOG.log(Level.INFO, "Saving mapsettings.json..");- this.mapConfig.putNull("options");- this.mapSettings.clear();- ObjectNode mapSettingsJson = loadMapSettingsJson(mapSettingsPath);- if(mapSettingsJson == null) {- mapSettingsJson = ValueUtil.JSON.createObjectNode();- }- try(OutputStream out = new FileOutputStream(new File(mapSettingsPath.toUri()))){- mapSettingsJson.putPOJO("options", mapConfiguration);- out.write(ValueUtil.JSON.writeValueAsString(mapSettingsJson).getBytes());- this.setData();- } catch (ClassNotFoundException | IOException | NullPointerException | SQLException exception) {- LOG.log(Level.WARNING, "Error trying to save mapsettings.json", exception);+ public ObjectNode saveMapConfig(Map<String, MapRealmConfig> mapConfiguration) throws RuntimeException {+ if (mapConfig == null) {+ mapConfig = ValueUtil.JSON.createObjectNode();}- return mapSettingsJson;+ mapConfig.putPOJO("options", mapConfiguration);+ configurationService.saveMapConfig(mapConfig);+ mapSettings.clear();+ return mapConfig;}protected static Metadata getMetadata(Connection connection) {@@ -112,7 +97,7 @@ public class MapService implements ContainerService {resultMap.put(result.getString(1), result.getString(2));}- if (resultMap.size() == 0) {+ if (resultMap.isEmpty()) {return new Metadata();}@@ -137,17 +122,6 @@ public class MapService implements ContainerService {return metadata;}- protected static ObjectNode loadMapSettingsJson(Path mapSettingsPath) {- ObjectNode mapSettings = null;-- try {- mapSettings = (ObjectNode) ValueUtil.JSON.readTree(Files.readAllBytes(mapSettingsPath));- } catch (Exception ex) {- LOG.log(Level.SEVERE, "Failed to extract map config from: " + mapSettingsPath.toAbsolutePath(), ex);- }- return mapSettings;- }-protected static void closeQuietly(PreparedStatement query, ResultSet result) {try {if (result != null) {@@ -161,47 +135,10 @@ public class MapService implements ContainerService {}}- @Override- public int getPriority() {- return ContainerService.DEFAULT_PRIORITY;- }-@Overridepublic void init(Container container) throws Exception {- mapTilesPath = Paths.get(getString(container.getConfig(), OR_MAP_TILES_PATH, OR_MAP_TILES_PATH_DEFAULT));- if (!Files.isRegularFile(mapTilesPath)) {- LOG.warning("Map tiles data file not found '" + mapTilesPath.toAbsolutePath() + "', falling back to built in map");- mapTilesPath = null;- }-- mapSettingsPath = Paths.get(getString(container.getConfig(), OR_MAP_SETTINGS_PATH, OR_MAP_SETTINGS_PATH_DEFAULT));- if (!Files.isRegularFile(mapSettingsPath)) {- LOG.warning("Map settings file not found '" + mapSettingsPath.toAbsolutePath() + "', falling back to built in map settings");- mapSettingsPath = null;- }--// if (mapTilesPath == null || mapSettingsPath == null) {-// return;-// }-- if (mapTilesPath == null) {- if (Files.isRegularFile(Paths.get("/deployment/map/mapdata.mbtiles"))) {- mapTilesPath = Paths.get("/deployment/map/mapdata.mbtiles");- } else if (Files.isRegularFile(Paths.get("/opt/map/mapdata.mbtiles"))) {- mapTilesPath = Paths.get("/opt/map/mapdata.mbtiles");- } else if (Files.isRegularFile(Paths.get("manager/src/map/mapdata.mbtiles"))) {- mapTilesPath = Paths.get("manager/src/map/mapdata.mbtiles");- }- }-- if (mapSettingsPath == null) {- if (Files.isRegularFile(Paths.get("/opt/map/mapsettings.json"))) {- mapSettingsPath = Paths.get("/opt/map/mapsettings.json");- } else if (Files.isRegularFile(Paths.get("manager/src/map/mapsettings.json"))) {- mapSettingsPath = Paths.get("manager/src/map/mapsettings.json");- }- }+ configurationService = container.getService(ConfigurationService.class);container.getService(ManagerWebService.class).addApiSingleton(new MapResourceImpl(this, container.getService(ManagerIdentityService.class))@@ -242,23 +179,25 @@ public class MapService implements ContainerService {@Overridepublic void start(Container container) throws Exception {- this.setData();+ setData();}public void setData() throws ClassNotFoundException, SQLException, NullPointerException {- if (mapTilesPath == null || mapSettingsPath == null) {+ Path mapTilesPath = configurationService.getMapTilesPath();+ if (mapTilesPath == null) {+ return;+ }+ mapTilesPath = mapTilesPath.toAbsolutePath();+ if (!mapTilesPath.toFile().exists()) {return;}-- LOG.info("Starting map service with tile data: " + mapTilesPath.toAbsolutePath());Class.forName(org.sqlite.JDBC.class.getName());- connection = DriverManager.getConnection("jdbc:sqlite:" + mapTilesPath.toAbsolutePath());-+ connection = DriverManager.getConnection("jdbc:sqlite:" + mapTilesPath);metadata = getMetadata(connection);+if (metadata.isValid()) {- mapConfig = loadMapSettingsJson(mapSettingsPath);+ mapConfig = configurationService.getMapConfig();if (mapConfig == null) {- LOG.warning("Map config could not be loaded from '" + mapSettingsPath.toAbsolutePath() + "', map functionality will not work");return;}} else {@@ -350,15 +289,6 @@ public class MapService implements ContainerService {String tileUrl = UriBuilder.fromUri(host).replacePath(API_PATH).path(realm).path("map/tile").build().toString() + "/{z}/{x}/{y}";tilesArray.insert(0, tileUrl);vectorTilesObj.replace("tiles", tilesArray);--// vectorTilesObj.put(-// "url",-// baseUriBuilder.clone()-// .replacePath(API_PATH)-// .path(realm)-// .path("map/source")-// .build()-// .toString());});// Set sprite URL to shared folder@@ -442,14 +372,6 @@ public class MapService implements ContainerService {}}- @Override- public String toString() {- return getClass().getSimpleName() + "{" +- "mapTilesPath=" + mapTilesPath +- ", mapSettingsPath=" + mapSettingsPath +- '}';- }-protected static final class Metadata {protected String attribution;protected ArrayNode vectorLayers;diff --git a/model/src/main/java/org/openremote/model/manager/ConfigurationResource.java b/model/src/main/java/org/openremote/model/manager/ConfigurationResource.javaindex c6db255e9..8499f8371 100644--- a/model/src/main/java/org/openremote/model/manager/ConfigurationResource.java+++ b/model/src/main/java/org/openremote/model/manager/ConfigurationResource.java@@ -19,6 +19,7 @@*/package org.openremote.model.manager;+import com.fasterxml.jackson.databind.node.ObjectNode;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import org.openremote.model.Constants;@@ -40,7 +41,7 @@ public interface ConfigurationResource {@Path("manager")@RolesAllowed({Constants.WRITE_ADMIN_ROLE})@Operation(operationId = "updateConfiguration", summary = "Update manager configuration")- Object update(@BeanParam RequestParams requestParams, Object managerConfiguration);+ ObjectNode update(@BeanParam RequestParams requestParams, ObjectNode managerConfiguration);@POST@Consumes(APPLICATION_JSON)@@ -55,5 +56,14 @@ public interface ConfigurationResource {FileInfo fileInfo);+ @GET+ @Produces(APPLICATION_JSON)+ @Path("manager")+ @Operation(operationId = "getManagerConfig", summary = "Retrieve the manager configuration JSON")+ ObjectNode getManagerConfig();+ @GET+ @Path("manager/image/{filename: .+}")+ @Operation(operationId = "getManagerConfigImage", summary = "Retrieve manager configuration images")+ Object getManagerConfigImage(@PathParam("filename")String fileName);}diff --git a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovyindex 7abedaf80..6bb305175 100644--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy@@ -288,7 +288,6 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {and: "the protocol instance and agent should be removed"conditions.eventually {assert agentService.getProtocolInstance(mockAgent2.id) == null- assert (MockProtocol)agentService.getProtocolInstance(mockAgent2.id) == null}when: "the mock protocol tries to update the plain readonly attribute"diff --git a/test/src/test/groovy/org/openremote/test/protocol/mail/MailClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/mail/MailClientProtocolTest.groovyindex 481817353..7df3ccdba 100644--- a/test/src/test/groovy/org/openremote/test/protocol/mail/MailClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/mail/MailClientProtocolTest.groovy@@ -28,6 +28,7 @@ import org.openremote.agent.protocol.mail.*import org.openremote.manager.agent.AgentServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.asset.OutdatedAttributeEventimport org.openremote.manager.event.ClientEventServiceimport org.openremote.model.Constantsimport org.openremote.model.asset.agent.Agent@@ -106,7 +107,11 @@ class MailClientProtocolTest extends Specification implements ManagerContainerTrConsumer<AttributeEvent> eventConsumer = it -> {attributeEvents.add(it)}+ Consumer<OutdatedAttributeEvent> outdatedEventConsumer = it -> {+ attributeEvents.add(it.event)+ }clientEventService.addSubscription(AttributeEvent.class, null, eventConsumer)+ clientEventService.addSubscription(OutdatedAttributeEvent.class, null, outdatedEventConsumer)and: "some mail messages exist"sendMessage("from@localhost")@@ -237,6 +242,7 @@ class MailClientProtocolTest extends Specification implements ManagerContainerTrcleanup: "the event subscription is removed"if (clientEventService != null) {clientEventService.removeSubscription(eventConsumer)+ clientEventService.removeSubscription {outdatedEventConsumer}}if (asset != null) {assetStorageService.delete([agent.id, asset.id])diff --git a/test/src/testFixtures/groovy/org/openremote/test/ManagerContainerTrait.groovy b/test/src/testFixtures/groovy/org/openremote/test/ManagerContainerTrait.groovyindex d36b8061f..8cc88c620 100644--- a/test/src/testFixtures/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/test/src/testFixtures/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -68,6 +68,10 @@ trait ManagerContainerTrait extends ContainerTrait {container.getService(TimerService.class).getNow()}+ void advancePseudoClock(long amount, TimeUnit unit) {+ advancePseudoClock(amount, unit, container)+ }+void advancePseudoClock(long amount, TimeUnit unit, Container container) {withClockOf(container) { it.advanceTime(amount, unit) }}diff --git a/ui/app/insights/src/index.ts b/ui/app/insights/src/index.tsindex 393583ae7..22ffa611b 100644--- a/ui/app/insights/src/index.ts+++ b/ui/app/insights/src/index.ts@@ -1,10 +1,10 @@import {combineReducers, configureStore} from "@reduxjs/toolkit";-import "@openremote/or-app";import {AppConfig, appReducer, OrApp, PageProvider, RealmAppConfig} from "@openremote/or-app";import {pageViewProvider} from "./pages/page-view";import {ManagerAppConfig} from "@openremote/model";-declare const CONFIG_URL_PREFIX: string;+declare const MANAGER_URL: string | undefined;+declare const CONFIG_URL_PREFIX: string | undefined;const rootReducer = combineReducers({app: appReducer@@ -30,14 +30,20 @@ export const DefaultAppConfig: AppConfig<RootState> = {};// Try and load the app config from JSON and if anything is found amalgamate it with default-const configURL = (CONFIG_URL_PREFIX || "") + "/manager_config.json";+const configURL = (MANAGER_URL ?? "") + "/api/master/configuration/manager";fetch(configURL).then(async (result) => {- if (!result.ok) {+ if (!result.ok || result.status === 204) {return DefaultAppConfig;}- return await result.json() as ManagerAppConfig;+ const appConfig = await result.json() as ManagerAppConfig;++ if (appConfig === null) {+ return DefaultAppConfig;+ }++ return appConfig;}).then((appConfig: ManagerAppConfig) => {@@ -60,7 +66,6 @@ fetch(configURL).then(async (result) => {appConfig.manager.translationsLoadPath = CONFIG_URL_PREFIX + appConfig.manager.translationsLoadPath;}}-// Override specific for Insights app, since it doesn't require login.// Login and logout buttons can be found in the sidebar menu of the app.appConfig.manager.autoLogin = false;@@ -103,18 +108,6 @@ fetch(configURL).then(async (result) => {}})- // Add config prefix if defined (used in dev)- if (CONFIG_URL_PREFIX) {- Object.values(orAppConfig.realms).forEach((realmConfig) => {- if (typeof (realmConfig.logo) === "string") {- realmConfig.logo = CONFIG_URL_PREFIX + realmConfig.logo;- }- if (typeof (realmConfig.logoMobile) === "string") {- realmConfig.logoMobile = CONFIG_URL_PREFIX + realmConfig.logoMobile;- }- });- }-// Add insights page with correct parametersorAppConfig.pages.push(pageViewProvider(store, orAppConfig.realms))diff --git a/ui/app/manager/src/components/configuration/or-conf-panel.ts b/ui/app/manager/src/components/configuration/or-conf-panel.tsindex 859b03a73..b956358dc 100644--- a/ui/app/manager/src/components/configuration/or-conf-panel.ts+++ b/ui/app/manager/src/components/configuration/or-conf-panel.ts@@ -41,7 +41,9 @@ export class OrConfPanel extends LitElement {protected isMapConfig(object: unknown): boolean {const keys = Object.keys(object);- return this.realmOptions.filter((o) => keys.includes(o.name)).length === keys.length;+ // Instead of looking for the exact same entries, ensure that at least one of them can be mapped.+ // This also shows realm configs that don't have parent realms, but are still existing in the mapsettings.json+ return this.realmOptions.filter((o) => keys.includes(o.name)).length > 0;}protected isManagerConfig(object: any): object is ManagerAppConfig {diff --git a/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.ts b/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.tsindex 43e31eef9..06c882b2b 100644--- a/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.ts+++ b/ui/app/manager/src/components/configuration/or-conf-realm/or-conf-realm-card.ts@@ -38,6 +38,8 @@ import { DialogAction, OrMwcDialog, showDialog } from "@openremote/or-mwc-componimport {when} from 'lit/directives/when.js';import ISO6391 from 'iso-639-1';+declare const MANAGER_URL: string+@customElement("or-conf-realm-card")export class OrConfRealmCard extends LitElement {@@ -215,7 +217,7 @@ export class OrConfRealmCard extends LitElement {protected _getImagePath(file:File, fileName: string){if (file.type.startsWith("image/")){const extension = file.name.slice(file.name.lastIndexOf('.'), file.name.length);- return "/images/" + this.name + "/" + fileName + extension+ return this.name + "/" + fileName + extension}return null}@@ -225,15 +227,16 @@ export class OrConfRealmCard extends LitElement {protected async _setImageForUpload(file: File, fileName: string) {const path = this._getImagePath(file, fileName)if (path){- this.files[path] = {+ this.files[fileName] = {+ name: fileName,path: path,contents: await Util.blobToBase64(file),} as FileInfo;this.realm[fileName] = path- this[fileName] = this.files[path].contents+ this[fileName] = this.files[fileName].contentsthis.requestUpdate()this.notifyConfigChange(this.realm);- return this.files[path].contents;+ return this.files[fileName].contents;}}@@ -287,6 +290,7 @@ export class OrConfRealmCard extends LitElement {render() {const colors = this._getColors();const app = this;+ const managerUrl = (MANAGER_URL || "");// On an empty search; return the common language as set in DEFAULT_LANGUAGES// If searching, compare strings using lowercase. (with no maximum)@@ -320,13 +324,13 @@ export class OrConfRealmCard extends LitElement {<div class="d-inline-flex"><or-file-uploader .title="${i18next.t('configuration.logo')}"@change="${async (e: CustomEvent) => await app._setImageForUpload(e.detail.value[0], "logo")}"- .src="${app.logo ? app.logo : app.realm.logo}"></or-file-uploader>+ .src="${app.logo ? app.logo : app.realm.logo}" .managerUrl="${managerUrl}"></or-file-uploader><or-file-uploader .title="${i18next.t('configuration.logoMobile')}"@change="${async (e: CustomEvent) => await app._setImageForUpload(e.detail.value[0], "logoMobile")}"- .src="${app.logoMobile ? app.logoMobile : app.realm.logoMobile}"></or-file-uploader>+ .src="${app.logoMobile ? app.logoMobile : app.realm.logoMobile}" .managerUrl="${managerUrl}"></or-file-uploader><or-file-uploader .title="${html`Favicon`}"@change="${async (e: CustomEvent) => await app._setImageForUpload(e.detail.value[0], "favicon")}"- .src="${app.favicon ? app.favicon : app.realm.favicon}"></or-file-uploader>+ .src="${app.favicon ? app.favicon : app.realm.favicon}" .managerUrl="${managerUrl}"></or-file-uploader></div></div><div class="color-group">diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.tsindex 1579c0a65..f29894a5d 100644--- a/ui/app/manager/src/index.ts+++ b/ui/app/manager/src/index.ts@@ -47,7 +47,8 @@ import {pageAlarmsProvider} from "./pages/page-alarms";import { ManagerAppConfig } from "@openremote/model";import {pageGatewayTunnelProvider} from "./pages/page-gateway-tunnel";-declare var CONFIG_URL_PREFIX: string;+declare var CONFIG_URL_PREFIX: string | undefined;+declare var MANAGER_URL: string | undefined;const rootReducer = combineReducers({app: appReducer,@@ -122,14 +123,20 @@ export const DefaultAppConfig: AppConfig<RootState> = {};// Try and load the app config from JSON and if anything is found amalgamate it with default-const configURL = (CONFIG_URL_PREFIX || "") + "/manager_config.json";+const configURL = (MANAGER_URL ?? "") + "/api/master/configuration/manager";fetch(configURL).then(async (result) => {- if (!result.ok) {+ if (!result.ok || result.status === 204) {return DefaultAppConfig;}- return await result.json() as ManagerAppConfig;+ const appConfig = await result.json() as ManagerAppConfig;++ if (appConfig === null) {+ return DefaultAppConfig;+ }++ return appConfig;}).then((appConfig: ManagerAppConfig) => {@@ -274,18 +281,6 @@ fetch(configURL).then(async (result) => {}})- // Add config prefix if defined (used in dev)- if (CONFIG_URL_PREFIX) {- Object.values(orAppConfig.realms).forEach((realmConfig) => {- if (typeof (realmConfig.logo) === "string") {- realmConfig.logo = CONFIG_URL_PREFIX + realmConfig.logo;- }- if (typeof (realmConfig.logoMobile) === "string") {- realmConfig.logoMobile = CONFIG_URL_PREFIX + realmConfig.logoMobile;- }- });- }-return orAppConfig;};diff --git a/ui/app/manager/src/pages/page-configuration.ts b/ui/app/manager/src/pages/page-configuration.tsindex 41266d76c..2f2513029 100644--- a/ui/app/manager/src/pages/page-configuration.ts+++ b/ui/app/manager/src/pages/page-configuration.ts@@ -36,8 +36,10 @@ import {OrConfRealmCard} from "../components/configuration/or-conf-realm/or-confimport {OrConfPanel} from "../components/configuration/or-conf-panel";import {Input} from "@openremote/or-rules/lib/flow-viewer/services/input";import { InputType } from "@openremote/or-mwc-components/or-mwc-input";+import {DefaultAppConfig} from "../index";declare const CONFIG_URL_PREFIX: string;+declare const MANAGER_URL: string | undefined;export function pageConfigurationProvider(store: Store<AppStateKeyed>): PageProvider<AppStateKeyed> {return {@@ -298,8 +300,8 @@ export class PageConfiguration extends Page<AppStateKeyed> {// FETCH METHODSprotected async getManagerConfig(): Promise<ManagerAppConfig | undefined> {- const response = await fetch(this.urlPrefix + "/manager_config.json", { cache: "reload" });- return await response.json() as ManagerAppConfig;+ const response = await manager.rest.api.ConfigurationResource.getManagerConfig();+ return response.status === 200 ? response.data as ManagerAppConfig : DefaultAppConfig;}protected async getMapConfig(): Promise<{[id: string]: any}> {@@ -315,19 +317,22 @@ export class PageConfiguration extends Page<AppStateKeyed> {this.loading = true;let managerPromise;- // POST manager config if changed...- if (this.managerConfigurationChanged) {- managerPromise = manager.rest.api.ConfigurationResource.update(config).then(() => {- fetch(this.urlPrefix + "/manager_config.json", {cache: "reload"});- this.managerConfiguration = config;- Object.entries(this.managerConfiguration.realms).forEach(([name, settings]) => {- fetch(this.urlPrefix + settings?.favicon, {cache: "reload"});- fetch(this.urlPrefix + settings?.logo, {cache: "reload"});- fetch(this.urlPrefix + settings?.logoMobile, {cache: "reload"});+ // Save the images to the server that have been uploaded by the user.+ // TODO: Optimize code so it only saves images that have been changed.+ const imagePromises = [];+ if(this.realmConfigPanel !== undefined) {+ const elems = this.realmConfigPanel.getCardElements() as OrConfRealmCard[];+ elems.forEach((elem, index) => {+ const files = elem?.getFiles();+ Object.entries(files).forEach(async ([x, y]) => {+ imagePromises.push(+ manager.rest.api.ConfigurationResource.fileUpload(y, {path: (y as any).path}).then(file =>{+ config.realms[elem.name][x] = file.data;+ })+ );});- }).catch((reason) => {- console.error(reason);- });+ })+ this.managerConfiguration = config;}// POST map config if changed...@@ -341,25 +346,25 @@ export class PageConfiguration extends Page<AppStateKeyed> {});}- // Save the images to the server that have been uploaded by the user.- // TODO: Optimize code so it only saves images that have been changed.- const imagePromises = [];- if(this.realmConfigPanel !== undefined) {- const elems = this.realmConfigPanel.getCardElements() as OrConfRealmCard[];- elems.forEach((elem, index) => {- const files = elem?.getFiles();- Object.entries(files).forEach(async ([x, y]) => {- imagePromises.push(manager.rest.api.ConfigurationResource.fileUpload(y, {path: x}));- });- })- }- // Wait for all requests to complete, then finish loading.- const promises = [...imagePromises, managerPromise, mapPromise];- Promise.all(promises).finally(() => {- this.loading = false;- this.managerConfigurationChanged = false;- this.mapConfigChanged = false;+ // We first wait for the imagePromises to finish, so that+ // we can use the path returned from the backend to store to the+ // manager_config.+ Promise.all(imagePromises).then((arr:string[]) => {+ // Wait for all requests to complete, then finish loading.+ const promises = [+ this.managerConfigurationChanged ? manager.rest.api.ConfigurationResource.update(config) : null,+ this.mapConfigChanged ? mapPromise : null];+ Promise.all(promises).finally(() => {+ this.requestUpdate();+ this.loading = false;+ this.managerConfigurationChanged = false;+ this.mapConfigChanged = false;+ const configURL = (MANAGER_URL ?? "") + "/api/master/configuration/manager";+ fetch(configURL, {cache: "reload"})+ window.location.reload();+ })})+}}diff --git a/ui/component/or-app/src/index.ts b/ui/component/or-app/src/index.tsindex 32d037780..0b01efbe3 100644--- a/ui/component/or-app/src/index.ts+++ b/ui/component/or-app/src/index.ts@@ -28,8 +28,8 @@ export * from "./or-header";export * from "./types";// Declare MANAGER_URL and KEYCLOAK_URL - Global var injected by webpack-declare var MANAGER_URL: string | undefined;-declare var KEYCLOAK_URL: string | undefined;+declare const MANAGER_URL: string | undefined;+declare const KEYCLOAK_URL: string | undefined;export {HeaderConfig, DEFAULT_LANGUAGES};@@ -38,8 +38,8 @@ export function getDefaultManagerConfig() {}const DEFAULT_MANAGER_CONFIG: ManagerConfig = {- managerUrl: MANAGER_URL,- keycloakUrl: KEYCLOAK_URL,+ managerUrl: (MANAGER_URL || ""),+ keycloakUrl: (KEYCLOAK_URL || ""),auth: Auth.KEYCLOAK,autoLogin: true,realm: undefined,@@ -371,12 +371,16 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {if (!this._config.logo) {this._config.logo = DefaultLogo;+ }else{+ this._config.logo = (MANAGER_URL || "")+this._config.logo}if (!this._config.logoMobile) {this._config.logoMobile = DefaultMobileLogo;+ }else{+ this._config.logoMobile = (MANAGER_URL || "")+this._config.logoMobile}- const favIcon = this._config && this._config.favicon ? this._config.favicon : DefaultFavIcon;+ const favIcon = this._config && this._config.favicon ? (MANAGER_URL || "")+this._config.favicon : DefaultFavIcon;let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;diff --git a/ui/component/or-components/src/or-file-uploader.ts b/ui/component/or-components/src/or-file-uploader.tsindex df0d58b48..e2b93c49c 100644--- a/ui/component/or-components/src/or-file-uploader.ts+++ b/ui/component/or-components/src/or-file-uploader.ts@@ -30,6 +30,9 @@ export class OrFileUploader extends LitElement {@property({ attribute: false })public readonly src: string = "";+ @property({ attribute: false })+ public readonly managerUrl: string = "";+@property()public readonly title: string = "";@@ -125,6 +128,15 @@ export class OrFileUploader extends LitElement {}render() {+ const file = () => {+ if(this.src){+ if(this.src.includes("data:image")){+ return this.src;+ }else{+ return this.managerUrl+this.src;+ }+ }+ }return html`<div class="container">${this.loading ? html`@@ -133,7 +145,7 @@ export class OrFileUploader extends LitElement {<div id="imageContainer">${this.src ? html`- <img src="${this.src}" alt="OR-File-Uploader">+ <img src="${file()}" alt="OR-File-Uploader"><div class="pencil-container"><or-icon icon="pencil-circle"></or-icon></div>