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 map service
Christian Bauer4bede3401237
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex 8806fee5b..d0df83257 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -10,7 +10,7 @@ import java.util.stream.StreamSupport;public class Container {- private static final Logger LOG = Runtime.LOG;+ private static final Logger LOG = ContainerRuntime.LOG;public final ObjectNode CONFIG;@@ -35,11 +35,11 @@ public class Container {@SafeVarargspublic Container(Map<String, String> config, Stream<ContainerService>... serviceStreams) {- CONFIG = Runtime.JSON.createObjectNode();+ CONFIG = ContainerRuntime.JSON.createObjectNode();for (Map.Entry<String, String> entry : config.entrySet()) {CONFIG.put(entry.getKey(), entry.getValue());}- Runtime.configure(this);+ ContainerRuntime.configure(this);if (serviceStreams != null) {for (Stream<ContainerService> serviceStream : serviceStreams) {@@ -47,7 +47,7 @@ public class Container {}}- Runtime.addShutdownHook(this::stop);+ ContainerRuntime.addShutdownHook(this::stop);}public String getConfig(String variable, String defaultValue) {diff --git a/container/src/main/java/org/openremote/container/Runtime.java b/container/src/main/java/org/openremote/container/ContainerRuntime.javasimilarity index 95%rename from container/src/main/java/org/openremote/container/Runtime.javarename to container/src/main/java/org/openremote/container/ContainerRuntime.javaindex 4ed0b2fb6..23670a942 100644--- a/container/src/main/java/org/openremote/container/Runtime.java+++ b/container/src/main/java/org/openremote/container/ContainerRuntime.java@@ -12,7 +12,7 @@ import java.io.InputStream;import java.util.logging.LogManager;import java.util.logging.Logger;-public class Runtime {+public class ContainerRuntime {public static final String DEV_MODE = "DEV_MODE";public static final boolean DEV_MODE_DEFAULT = true;@@ -31,7 +31,7 @@ public class Runtime {}}- LOG = Logger.getLogger(Runtime.class.getName());+ LOG = Logger.getLogger(ContainerRuntime.class.getName());LOG.info("Starting runtime container...");JSON = new ObjectMapper();diff --git a/container/src/main/java/org/openremote/container/web/GZIPPEDEncodingInterceptor.java b/container/src/main/java/org/openremote/container/web/GZIPPEDEncodingInterceptor.javanew file mode 100644index 000000000..4081807a7--- /dev/null+++ b/container/src/main/java/org/openremote/container/web/GZIPPEDEncodingInterceptor.java@@ -0,0 +1,30 @@+package org.openremote.container.web;++import javax.annotation.Priority;+import javax.ws.rs.Priorities;+import javax.ws.rs.WebApplicationException;+import javax.ws.rs.ext.Provider;+import javax.ws.rs.ext.WriterInterceptor;+import javax.ws.rs.ext.WriterInterceptorContext;+import java.io.IOException;++import static javax.ws.rs.core.HttpHeaders.CONTENT_ENCODING;++/**+ * If content is already zipped we need a way to disable RESTEasy's stupid automatic zipping.+ */+@Provider+@Priority(Priorities.ENTITY_CODER)+public class GZIPPEDEncodingInterceptor implements WriterInterceptor {++ @Override+ public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {+ Object encoding = context.getHeaders().getFirst(CONTENT_ENCODING);++ if (encoding != null && encoding.toString().equalsIgnoreCase("gzipped")) {+ // It's already zipped... just add the header+ context.getHeaders().putSingle(CONTENT_ENCODING, "gzip");+ }+ context.proceed();+ }+}diff --git a/container/src/main/java/org/openremote/container/web/JacksonConfig.java b/container/src/main/java/org/openremote/container/web/JacksonConfig.javaindex 35f1a77ac..04becfc70 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.Runtime;+import org.openremote.container.ContainerRuntime;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 Runtime.JSON;+ return ContainerRuntime.JSON;}}\ No newline at end of filediff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.javaindex 2b263fda7..1812822a7 100644--- a/container/src/main/java/org/openremote/container/web/WebResource.java+++ b/container/src/main/java/org/openremote/container/web/WebResource.java@@ -15,7 +15,7 @@ public class WebResource {protected Application application;@Context- UriInfo uriInfo;+ protected UriInfo uriInfo;public WebApplication getApplication() {return (WebApplication) application;diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.javaindex 70b8a239b..58b99a315 100644--- a/container/src/main/java/org/openremote/container/web/WebService.java+++ b/container/src/main/java/org/openremote/container/web/WebService.java@@ -208,6 +208,7 @@ public abstract class WebService implements ContainerService {// Custom providers (these only apply to server applications, not client calls)resteasyDeployment.getActualProviderClasses().add(JacksonConfig.class);+ resteasyDeployment.getActualProviderClasses().add(GZIPPEDEncodingInterceptor.class);ServletInfo restServlet = Servlets.servlet("RESTEasy Servlet", HttpServlet30Dispatcher.class).setAsyncSupported(true)diff --git a/manager/src/main/java/org/openremote/manager/client/rest/MapRestService.java b/manager/src/main/java/org/openremote/manager/client/rest/MapRestService.javaindex 6dc4c27f8..b532cd364 100644--- a/manager/src/main/java/org/openremote/manager/client/rest/MapRestService.java+++ b/manager/src/main/java/org/openremote/manager/client/rest/MapRestService.java@@ -5,6 +5,8 @@ import org.fusesource.restygwt.client.TextCallback;import javax.ws.rs.GET;import javax.ws.rs.Path;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;/*** Created by Richard on 19/02/2016.@@ -13,6 +15,7 @@ public interface MapRestService extends RestService {@GET@Path("/map")+ @Produces(MediaType.APPLICATION_JSON)void getOptions(TextCallback optionsCallback);}diff --git a/manager/src/main/java/org/openremote/manager/server2/map/MapResource.java b/manager/src/main/java/org/openremote/manager/server2/map/MapResource.javanew file mode 100644index 000000000..930ac9e35--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/server2/map/MapResource.java@@ -0,0 +1,45 @@+package org.openremote.manager.server2.map;++import com.fasterxml.jackson.databind.node.ObjectNode;+import org.openremote.container.web.WebResource;++import javax.ws.rs.*;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;+import java.util.logging.Logger;++@Path("map")+public class MapResource extends WebResource {++ private static final Logger LOG = Logger.getLogger(MapResource.class.getName());++ protected final MapService mapService;++ public MapResource(MapService mapService) {+ this.mapService = mapService;+ }++ @GET+ @Produces(MediaType.APPLICATION_JSON)+ public ObjectNode getMapSettings() {+ String tileUrl = uriInfo.getBaseUriBuilder().clone()+ .replacePath(getRealm()).path("map/tile").build().toString() + "/{z}/{x}/{y}";+ return mapService.getMapSettings(tileUrl);+ }++ @GET+ @Path("/tile/{zoom}/{column}/{row}")+ @Produces("application/vnd.mapbox-vector-tile")+ public Response getTile(@PathParam("zoom") int zoom, @PathParam("column") int column, @PathParam("row") int row) {+ try {+ byte[] tile = mapService.getMapTile(zoom, column, row);+ if (tile != null) {+ return Response.ok().encoding("gzipped").entity(tile).build();+ } else {+ return Response.status(Response.Status.NOT_FOUND).build();+ }+ } catch (Exception ex) {+ throw new WebApplicationException(ex);+ }+ }+}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.javanew file mode 100644index 000000000..bb09a626f--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/server2/map/MapService.java@@ -0,0 +1,192 @@+package org.openremote.manager.server2.map;++import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.manager.server2.ManagerWebService;++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;+import java.util.logging.Logger;++import static org.openremote.container.ContainerRuntime.JSON;+import static org.openremote.manager.server.Constants.*;++public class MapService implements ContainerService {++ private static final Logger LOG = Logger.getLogger(MapService.class.getName());++ public static final String MAP_TILES_PATH = "MAP_TILES_PATH";+ public static final String MAP_TILES_PATH_DEFAULT = "sample/mapdata.mbtiles";+ public static final String MAP_SETTINGS_PATH = "MAP_SETTINGS_PATH";+ public static final String MAP_SETTINGS_PATH_DEFAULT = "sample/mapsettings.json";++ // Shared SQL connection is fine concurrently in SQLite+ protected Connection connection;++ protected boolean devMode;+ protected Path mapTilesPath;+ protected Path mapSettingsPath;+ protected ObjectNode mapSettings;++ @Override+ public void prepare(Container container) {+ this.devMode = container.getConfigBoolean(DEV_MODE, DEV_MODE_DEFAULT);++ mapTilesPath = Paths.get(container.getConfig(MAP_TILES_PATH, MAP_TILES_PATH_DEFAULT));+ if (!Files.isRegularFile(mapTilesPath)) {+ throw new IllegalStateException(+ "MapWidget tiles data file not found: " + mapTilesPath.toAbsolutePath()+ );+ }++ mapSettingsPath = Paths.get(container.getConfig(MAP_SETTINGS_PATH, MAP_SETTINGS_PATH_DEFAULT));+ if (!Files.isRegularFile(mapSettingsPath)) {+ throw new IllegalStateException(+ "MapWidget settings file not found: " + mapSettingsPath.toAbsolutePath()+ );+ }++ container.getService(ManagerWebService.class).getApiSingletons().add(+ new MapResource(this)+ );+ }++ @Override+ public void start(Container container) {+ LOG.info("Starting map service with tile data: " + mapTilesPath.toAbsolutePath());+ try {+ Class.forName(org.sqlite.JDBC.class.getName());+ connection = DriverManager.getConnection("jdbc:sqlite:" + mapTilesPath.toAbsolutePath());+ } catch (Exception ex) {+ throw new IllegalStateException(ex);+ }++ readMapSettings();+ }++ @Override+ public void stop(Container container) {+ LOG.info("Stopping map service...");+ if (connection != null) {+ try {+ connection.close();+ } catch (SQLException ex) {+ LOG.warning("Error closing connection: " + ex);+ }+ }+ }++ public ObjectNode getMapSettings(String tileUrl) {++ // Refresh map settings for every request in dev mode, cache it in production+ if (devMode) {+ readMapSettings();+ }++ ObjectNode settingsCopy = mapSettings.deepCopy();+ ArrayNode tilesArray = JSON.createArrayNode();+ tilesArray.add(tileUrl);+ settingsCopy.with("style").with("sources").with("vector_tiles").set("tiles", tilesArray);+ return settingsCopy;+ }++ public byte[] getMapTile(int zoom, int column, int row) throws Exception {+ // Flip y, oh why+ row = new Double(Math.pow(2, zoom) - 1 - row).intValue();++ PreparedStatement query = null;+ ResultSet result = null;+ try {+ query = connection.prepareStatement(+ "select TILE_DATA from TILES where ZOOM_LEVEL = ? and TILE_COLUMN = ? and TILE_ROW = ?"+ );++ int index = 0;+ query.setInt(++index, zoom);+ query.setInt(++index, column);+ query.setInt(++index, row);++ result = query.executeQuery();++ if (result.next()) {+ return result.getBytes(1);+ } else {+ return null;+ }+ } finally {+ closeQuietly(query, result);+ }+ }++ protected void readMapSettings() {++ // Mix settings from file with database metadata, and some hardcoded magic+ try {+ String mapSettingsJson = new String(Files.readAllBytes(mapSettingsPath), "utf-8");+ mapSettings = JSON.readValue(mapSettingsJson, ObjectNode.class);+ } catch (Exception ex) {+ throw new RuntimeException("Error parsing map settings: " + mapSettingsPath.toAbsolutePath(), ex);+ }++ ObjectNode style = mapSettings.with("style");++ style.put("version", 8);++ style.put("glyphs", STATIC_PATH + "/fonts/{fontstack}/{range}.pbf");++ ObjectNode sources = JSON.createObjectNode();+ style.set("sources", sources);++ ObjectNode vectorTiles = JSON.createObjectNode();+ sources.set("vector_tiles", vectorTiles);++ vectorTiles.put("type", "vector");++ PreparedStatement query = null;+ ResultSet result = null;+ try {+ query = connection.prepareStatement("select NAME, VALUE from METADATA");+ result = query.executeQuery();++ Map<String, String> resultMap = new HashMap<>();+ while (result.next()) {+ resultMap.put(result.getString(1), result.getString(2));+ }++ if (resultMap.size() == 0) {+ throw new RuntimeException("Missing JSON metadata in map database");+ }++ ObjectNode metadataJson = JSON.readValue(resultMap.get("json"), ObjectNode.class);+ vectorTiles.set("vector_layers", metadataJson.get("vector_layers"));+ vectorTiles.put("maxzoom", Integer.valueOf(resultMap.get("maxzoom")));+ vectorTiles.put("minzoom", Integer.valueOf(resultMap.get("minzoom")));+ vectorTiles.put("attribution", resultMap.get("attribution"));++ } catch (Exception ex) {+ throw new RuntimeException(ex);+ } finally {+ closeQuietly(query, result);+ }+ }++ protected void closeQuietly(PreparedStatement query, ResultSet result) {+ try {+ if (result != null) {+ result.close();+ }+ if (query != null) {+ query.close();+ }+ } catch (Exception ex) {+ LOG.warning("Error closing query/result: " + ex);+ }+ }++}\ No newline at end of filediff --git a/manager/src/main/resources/META-INF/services/org.openremote.container.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.container.ContainerServiceindex e7c9bf05c..56d6e7bfb 100644--- a/manager/src/main/resources/META-INF/services/org.openremote.container.ContainerService+++ b/manager/src/main/resources/META-INF/services/org.openremote.container.ContainerService@@ -1,2 +1,3 @@org.openremote.manager.server2.ManagerWebService-org.openremote.manager.server2.identity.IdentityService\ No newline at end of file+org.openremote.manager.server2.identity.IdentityService+org.openremote.manager.server2.map.MapService\ No newline at end of file