From f1f0682f15b70c3a1177fb25302ae1457c9a3aeb Mon Sep 17 00:00:00 2001 From: schwepmo <39306374+schwepmo@users.noreply.github.com> Date: Wed, 3 Jul 2024 15:45:57 +0200 Subject: [PATCH] chore(checkstyle): bumped checkstyle version to 10.15.0 (#392) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * done to support intelliJ checkstyle plugin * some adjustments in the configuration were required due to version changes * chore(checkstyle): set validateThrows to false (see http://www.javapractices.com/topic/TopicAction.do?Id=171) * chore(checkstyle): added further valid abbreviations * chore(checkstyle): getting rid of more checkstyle warnings * chore(checkstyle): added SuppressWarnings module so checkstyle warnings can be suppressed if necessary * chore(checkstyle): ignore naming in conventions in Wgs84Projection Signed-off-by: Moritz Schweppenhäuser --- checkstyle.xml | 28 +- .../simulation/AbstractSimulationUnit.java | 5 +- .../mosaic/fed/sumo/bridge/LibSumoBridge.java | 7 + .../database/persistence/SQLiteWriter.java | 283 ++++++++++-------- .../mosaic/lib/database/spatial/Edge.java | 3 +- .../org/eclipse/mosaic/lib/math/Vector3d.java | 273 ++++++++++++++++- .../org/eclipse/mosaic/lib/spatial/AStar.java | 13 +- .../mosaic/lib/spatial/BoundingBox.java | 93 ++++-- .../eclipse/mosaic/lib/spatial/KdTree.java | 13 +- .../mosaic/lib/spatial/LineString.java | 8 +- .../mosaic/lib/spatial/QuickHull2d.java | 57 ++-- .../lib/transform/LazyGeoProjection.java | 9 +- .../mosaic/lib/transform/Wgs84Projection.java | 142 ++++----- .../lib/coupling/ClientServerChannel.java | 53 ++-- .../lib/objects/addressing/IpResolver.java | 3 + .../eclipse/mosaic/lib/util/ClassUtils.java | 1 + .../lib/util/VehicleReferenceUtils.java | 1 + .../lib/util/cli/CommandLineParser.java | 29 +- pom.xml | 4 +- .../eclipse/mosaic/rti/api/RtiAmbassador.java | 8 +- .../rti/time/SequentialTimeManagement.java | 6 +- .../mosaic/starter/MosaicSimulation.java | 11 +- .../eclipse/mosaic/starter/MosaicStarter.java | 5 +- 23 files changed, 706 insertions(+), 349 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index c4837f9e3..76c8c8845 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -15,15 +15,16 @@ Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov. --> - + + - + @@ -44,14 +45,15 @@ - - - - - + + + + + + @@ -154,7 +156,7 @@ value="Type name ''{0}'' must match pattern ''{1}''."/> - + @@ -175,7 +177,7 @@ - + @@ -216,7 +218,7 @@ - + @@ -263,9 +265,9 @@ value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/> - + - + @@ -273,7 +275,7 @@ - + diff --git a/fed/mosaic-application/src/main/java/org/eclipse/mosaic/fed/application/ambassador/simulation/AbstractSimulationUnit.java b/fed/mosaic-application/src/main/java/org/eclipse/mosaic/fed/application/ambassador/simulation/AbstractSimulationUnit.java index 929726751..ccd09b22b 100644 --- a/fed/mosaic-application/src/main/java/org/eclipse/mosaic/fed/application/ambassador/simulation/AbstractSimulationUnit.java +++ b/fed/mosaic-application/src/main/java/org/eclipse/mosaic/fed/application/ambassador/simulation/AbstractSimulationUnit.java @@ -150,6 +150,7 @@ public final String getId() { * * @param event the event to process. * @return true if this method has processed the given event + * @throws RuntimeException if {@link Event} could not be properly handled by the processor */ public final boolean preProcessEvent(final Event event) { final Object resource = event.getResource(); @@ -501,10 +502,6 @@ public final File getConfigurationPath() { return SimulationKernel.SimulationKernel.getConfigurationPath(); } - public boolean canProcessEvent() { - return true; - } - @Override public String getGroup() { return group; diff --git a/fed/mosaic-sumo/src/main/java/org/eclipse/mosaic/fed/sumo/bridge/LibSumoBridge.java b/fed/mosaic-sumo/src/main/java/org/eclipse/mosaic/fed/sumo/bridge/LibSumoBridge.java index a6645bca3..4ee1b069b 100644 --- a/fed/mosaic-sumo/src/main/java/org/eclipse/mosaic/fed/sumo/bridge/LibSumoBridge.java +++ b/fed/mosaic-sumo/src/main/java/org/eclipse/mosaic/fed/sumo/bridge/LibSumoBridge.java @@ -12,6 +12,7 @@ * * Contact: mosaic@fokus.fraunhofer.de */ + package org.eclipse.mosaic.fed.sumo.bridge; @@ -45,6 +46,12 @@ public class LibSumoBridge implements Bridge { private final RouteFacade routeControl; private final PoiFacade poiControl; + /** + * Constructor for the {@link LibSumoBridge}, initializing simulation and facades based on configuration. + * + * @param sumoConfiguration the MOSAIC internal {@link CSumo SUMO configuration} + * @param parameters the program arguments for starting the simulation + */ public LibSumoBridge(CSumo sumoConfiguration, List parameters) { Simulation.load(new StringVector(parameters)); diff --git a/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/persistence/SQLiteWriter.java b/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/persistence/SQLiteWriter.java index f77ec78a6..fbedbd5aa 100644 --- a/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/persistence/SQLiteWriter.java +++ b/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/persistence/SQLiteWriter.java @@ -54,6 +54,9 @@ public class SQLiteWriter { */ final MosaicVersion stable; + /** + * Constructor for the {@link SQLiteWriter} reading the properties to retrieve the stable database version. + */ public SQLiteWriter() { // determine stable version to check against try (InputStream propertiesStream = this.getClass().getResourceAsStream("/database.properties")) { @@ -94,27 +97,7 @@ public void saveToFile(@Nonnull Database database, @Nonnull String fileName) { if (goSave) { try { Statement statement = sqlite.connect(); - log.debug("setting version and properties..."); - saveProperties(database); - log.info("Saving {} nodes...", database.getNodes().size()); - saveNodes(database); - log.info("Saving {} ways...", database.getWays().size()); - saveWays(database); - saveWayNodes(database); - log.info("Saving {} connections...", database.getConnections().size()); - saveConnections(database); - saveConnectionNodes(database); - log.info("Saving {} restrictions...", database.getRestrictions().size()); - saveRestrictions(database); - log.info("Saving {} routes...", database.getRoutes().size()); - saveRoutes(database); - log.info("Saving {} roundabouts...", database.getRoundabouts().size()); - saveRoundabouts(database); - log.info("Saving {} buildings...", database.getBuildings().size()); - saveBuildings(database); - log.info("Create Indices"); - createIndices(); - log.info("Database saved"); + executeSaves(database); sqlite.disconnect(statement); } catch (SQLException sqle) { log.error("error while trying to write database content: {}", sqle.getMessage()); @@ -122,6 +105,30 @@ public void saveToFile(@Nonnull Database database, @Nonnull String fileName) { } } + private void executeSaves(@Nonnull Database database) throws SQLException { + log.debug("setting version and properties..."); + saveProperties(database); + log.info("Saving {} nodes...", database.getNodes().size()); + saveNodes(database); + log.info("Saving {} ways...", database.getWays().size()); + saveWays(database); + saveWayNodes(database); + log.info("Saving {} connections...", database.getConnections().size()); + saveConnections(database); + saveConnectionNodes(database); + log.info("Saving {} restrictions...", database.getRestrictions().size()); + saveRestrictions(database); + log.info("Saving {} routes...", database.getRoutes().size()); + saveRoutes(database); + log.info("Saving {} roundabouts...", database.getRoundabouts().size()); + saveRoundabouts(database); + log.info("Saving {} buildings...", database.getBuildings().size()); + saveBuildings(database); + log.info("Create Indices"); + createIndices(); + log.info("Database saved"); + } + /** * Clears the database of all known/used tables. @@ -166,26 +173,39 @@ private void initTables() throws SQLException { // create tables // integrity statement.executeUpdate("CREATE TABLE " + TABLES.PROPERTIES + " (id TEXT UNIQUE, value TEXT)"); - statement.executeUpdate("INSERT INTO " + TABLES.PROPERTIES + "(id, value) VALUES ('" + Database.PROPERTY_VERSION + "', '" + Database.VERSION_UNKNOWN + "')"); - statement.executeUpdate("INSERT INTO " + TABLES.PROPERTIES + "(id, value) VALUES ('" + Database.PROPERTY_IMPORT_ORIGIN + "', '')"); + statement.executeUpdate("INSERT INTO " + TABLES.PROPERTIES + + "(id, value) VALUES ('" + Database.PROPERTY_VERSION + "', '" + Database.VERSION_UNKNOWN + "')"); + statement.executeUpdate("INSERT INTO " + TABLES.PROPERTIES + + "(id, value) VALUES ('" + Database.PROPERTY_IMPORT_ORIGIN + "', '')"); // pure network - statement.executeUpdate("CREATE TABLE " + TABLES.NODE + " (id TEXT, lat REAL, lon REAL, ele REAL, is_traffic_light BOOLEAN, is_intersection BOOLEAN, is_generated BOOLEAN)"); - statement.executeUpdate("CREATE TABLE " + TABLES.WAY + " (id TEXT, name TEXT, type TEXT, speed REAL, lanesForward INTEGER, lanesBackward INTEGER, oneway BOOLEAN)"); - statement.executeUpdate("CREATE TABLE " + TABLES.WAY_CONSISTS_OF + " (way_id TEXT, node_id TEXT, sequence_number INTEGER)"); - statement.executeUpdate("CREATE TABLE " + TABLES.CONNECTION + " (id TEXT, way_id TEXT, lanes INTEGER, length REAL)"); - statement.executeUpdate("CREATE TABLE " + TABLES.CONNECTION_CONSISTS_OF + " (connection_id TEXT, node_id TEXT, sequence_number INTEGER)"); + statement.executeUpdate("CREATE TABLE " + TABLES.NODE + + " (id TEXT, lat REAL, lon REAL, ele REAL, is_traffic_light BOOLEAN, is_intersection BOOLEAN, is_generated BOOLEAN)"); + statement.executeUpdate("CREATE TABLE " + + TABLES.WAY + " (id TEXT, name TEXT, type TEXT, speed REAL, lanesForward INTEGER, lanesBackward INTEGER, oneway BOOLEAN)"); + statement.executeUpdate("CREATE TABLE " + + TABLES.WAY_CONSISTS_OF + " (way_id TEXT, node_id TEXT, sequence_number INTEGER)"); + statement.executeUpdate("CREATE TABLE " + + TABLES.CONNECTION + " (id TEXT, way_id TEXT, lanes INTEGER, length REAL)"); + statement.executeUpdate("CREATE TABLE " + + TABLES.CONNECTION_CONSISTS_OF + " (connection_id TEXT, node_id TEXT, sequence_number INTEGER)"); // turn restrictions - statement.executeUpdate("CREATE TABLE " + TABLES.RESTRICTION + " (id TEXT, source_way_id TEXT, via_node_id TEXT, target_way_id TEXT, type TEXT)"); + statement.executeUpdate("CREATE TABLE " + TABLES.RESTRICTION + + " (id TEXT, source_way_id TEXT, via_node_id TEXT, target_way_id TEXT, type TEXT)"); // traffic signals - statement.executeUpdate("CREATE TABLE " + TABLES.TRAFFIC_SIGNALS + " (id TEXT, ref_node_id TEXT, phases TEXT, timing TEXT, from_way_id TEXT, via0_way_id TEXT, via1_way_id TEXT, to_way_id TEXT, lanes_from TEXT, lanes_via0 TEXT, lanes_via1 TEXT, lanes_to TEXT)"); + statement.executeUpdate("CREATE TABLE " + TABLES.TRAFFIC_SIGNALS + + " (id TEXT, ref_node_id TEXT, phases TEXT, timing TEXT, from_way_id TEXT, via0_way_id TEXT, via1_way_id TEXT," + + " to_way_id TEXT, lanes_from TEXT, lanes_via0 TEXT, lanes_via1 TEXT, lanes_to TEXT)"); // vehicle data - statement.executeUpdate("CREATE TABLE " + TABLES.ROUTE + " (id TEXT, sequence_number INTEGER, connection_id TEXT)"); + statement.executeUpdate("CREATE TABLE " + TABLES.ROUTE + + " (id TEXT, sequence_number INTEGER, connection_id TEXT)"); // roundabouts statement.executeUpdate("CREATE TABLE " + TABLES.ROUNDABOUT + " (id TEXT)"); - statement.executeUpdate("CREATE TABLE " + TABLES.ROUNDABOUT_CONSISTS_OF + " (roundabout_id TEXT, node_id TEXT, sequence_number INTEGER)"); + statement.executeUpdate("CREATE TABLE " + + TABLES.ROUNDABOUT_CONSISTS_OF + " (roundabout_id TEXT, node_id TEXT, sequence_number INTEGER)"); // buildings and its corners statement.executeUpdate("CREATE TABLE " + TABLES.BUILDING + " (id TEXT, name TEXT, height REAL)"); - statement.executeUpdate("CREATE TABLE " + TABLES.BUILDING_CONSISTS_OF + " (building_id TEXT, lat REAL, lon REAL, sequence_number INTEGER)"); + statement.executeUpdate("CREATE TABLE " + + TABLES.BUILDING_CONSISTS_OF + " (building_id TEXT, lat REAL, lon REAL, sequence_number INTEGER)"); // Connection Details (like parking lots) statement.executeUpdate("CREATE TABLE " + TABLES.CONNECTION_DETAILS + " (id TEXT, connection TEXT, type TEXT, value TEXT)"); @@ -241,24 +261,28 @@ private void saveNodes(Database database) { String statement = "INSERT INTO " + TABLES.NODE + "(" + columns + ") VALUES (?, ?, ?, ?, ?, ?, ?)"; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Node node : database.getNodes()) { - prep.setString(1, node.getId()); - prep.setDouble(2, node.getPosition().getLongitude()); - prep.setDouble(3, node.getPosition().getLatitude()); - prep.setDouble(4, node.getPosition().getAltitude()); - prep.setBoolean(5, node.getClass().equals(TrafficLightNode.class)); - prep.setBoolean(6, node.isIntersection()); - prep.setBoolean(7, node.isGenerated()); - prep.executeUpdate(); - } - sqlite.getConnection().commit(); + batchSaveNodes(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist nodes: {}", sqle.getMessage()); } } + private void batchSaveNodes(Database database, PreparedStatement prep) throws SQLException { + sqlite.getConnection().setAutoCommit(false); + for (Node node : database.getNodes()) { + prep.setString(1, node.getId()); + prep.setDouble(2, node.getPosition().getLongitude()); + prep.setDouble(3, node.getPosition().getLatitude()); + prep.setDouble(4, node.getPosition().getAltitude()); + prep.setBoolean(5, node.getClass().equals(TrafficLightNode.class)); + prep.setBoolean(6, node.isIntersection()); + prep.setBoolean(7, node.isGenerated()); + prep.executeUpdate(); + } + sqlite.getConnection().commit(); + } + /** * Saves all {@link Way}s to the SQLite file. Be aware that references(/relations) to other * objects are saved separately! @@ -270,24 +294,28 @@ private void saveWays(Database database) { String statement = "INSERT INTO " + TABLES.WAY + "(" + columns + ") VALUES (?, ?, ?, ?, ?, ?, ?)"; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Way way : database.getWays()) { - prep.setString(1, way.getId()); - prep.setString(2, way.getName()); - prep.setString(3, way.getType()); - prep.setDouble(4, way.getMaxSpeedInMs()); - prep.setInt(5, way.getNumberOfLanesForward()); - prep.setInt(6, way.getNumberOfLanesBackward()); - prep.setBoolean(7, way.isOneway()); - prep.executeUpdate(); - } - sqlite.getConnection().commit(); + batchSaveWays(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist ways: {}", sqle.getMessage()); } } + private void batchSaveWays(Database database, PreparedStatement prep) throws SQLException { + sqlite.getConnection().setAutoCommit(false); + for (Way way : database.getWays()) { + prep.setString(1, way.getId()); + prep.setString(2, way.getName()); + prep.setString(3, way.getType()); + prep.setDouble(4, way.getMaxSpeedInMs()); + prep.setInt(5, way.getNumberOfLanesForward()); + prep.setInt(6, way.getNumberOfLanesBackward()); + prep.setBoolean(7, way.isOneway()); + prep.executeUpdate(); + } + sqlite.getConnection().commit(); + } + /** * Saves all {@link Roundabout}s to the SQLite file. References(/relations) to other * objects NOT are saved separately! @@ -341,21 +369,9 @@ private void saveRoundabouts(Database database) { private void saveWayNodes(Database database) { String columns = "way_id, node_id, sequence_number"; String statement = "INSERT INTO " + TABLES.WAY_CONSISTS_OF + "(" + columns + ") VALUES (?, ?, ?)"; - int sequenceNumber; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Way way : database.getWays()) { - sequenceNumber = 0; - for (Node node : way.getNodes()) { - prep.setString(1, way.getId()); - prep.setString(2, node.getId()); - prep.setInt(3, sequenceNumber); - prep.executeUpdate(); - sequenceNumber++; - } - } - sqlite.getConnection().commit(); + batchSaveWayNodes(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist ways <--> node relations: {}", @@ -363,6 +379,22 @@ private void saveWayNodes(Database database) { } } + private void batchSaveWayNodes(Database database, PreparedStatement prep) throws SQLException { + int sequenceNumber; + sqlite.getConnection().setAutoCommit(false); + for (Way way : database.getWays()) { + sequenceNumber = 0; + for (Node node : way.getNodes()) { + prep.setString(1, way.getId()); + prep.setString(2, node.getId()); + prep.setInt(3, sequenceNumber); + prep.executeUpdate(); + sequenceNumber++; + } + } + sqlite.getConnection().commit(); + } + /** * Saves all {@link Connection}s to the SQLite file. Be aware that references(/relations) to * other objects are saved separately! @@ -374,21 +406,25 @@ private void saveConnections(Database database) { String statement = "INSERT INTO " + TABLES.CONNECTION + "(" + columns + ") VALUES (?, ?, ?, ?)"; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Connection connection : database.getConnections()) { - prep.setString(1, connection.getId()); - prep.setString(2, connection.getWay().getId()); - prep.setInt(3, connection.getLanes()); - prep.setDouble(4, connection.getLength()); - prep.executeUpdate(); - } - sqlite.getConnection().commit(); + batchSaveConnections(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist connections: {}", sqle.getMessage()); } } + private void batchSaveConnections(Database database, PreparedStatement prep) throws SQLException { + sqlite.getConnection().setAutoCommit(false); + for (Connection connection : database.getConnections()) { + prep.setString(1, connection.getId()); + prep.setString(2, connection.getWay().getId()); + prep.setInt(3, connection.getLanes()); + prep.setDouble(4, connection.getLength()); + prep.executeUpdate(); + } + sqlite.getConnection().commit(); + } + /** * Saves all references/relations between {@link Connection}s and {@link Node}s to the SQLite * file. @@ -398,21 +434,9 @@ private void saveConnections(Database database) { private void saveConnectionNodes(Database database) { String columns = "connection_id, node_id, sequence_number"; String statement = "INSERT INTO " + TABLES.CONNECTION_CONSISTS_OF + "(" + columns + ") VALUES (?, ?, ?)"; - int sequenceNumber; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Connection connection : database.getConnections()) { - sequenceNumber = 0; - for (Node node : connection.getNodes()) { - prep.setString(1, connection.getId()); - prep.setString(2, node.getId()); - prep.setInt(3, sequenceNumber); - prep.executeUpdate(); - sequenceNumber++; - } - } - sqlite.getConnection().commit(); + batchSaveConnectionNoes(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist connection <--> node relations: {}", @@ -420,6 +444,22 @@ private void saveConnectionNodes(Database database) { } } + private void batchSaveConnectionNoes(Database database, PreparedStatement prep) throws SQLException { + int sequenceNumber; + sqlite.getConnection().setAutoCommit(false); + for (Connection connection : database.getConnections()) { + sequenceNumber = 0; + for (Node node : connection.getNodes()) { + prep.setString(1, connection.getId()); + prep.setString(2, node.getId()); + prep.setInt(3, sequenceNumber); + prep.executeUpdate(); + sequenceNumber++; + } + } + sqlite.getConnection().commit(); + } + /** * Save all {@link Restriction}s to the SQLite file. * @@ -431,22 +471,26 @@ private void saveRestrictions(Database database) { try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Restriction restriction : database.getRestrictions()) { - prep.setString(1, restriction.getId()); - prep.setString(2, restriction.getSource().getId()); - prep.setString(3, restriction.getVia().getId()); - prep.setString(4, restriction.getTarget().getId()); - prep.setString(5, restriction.getType().name()); - prep.executeUpdate(); - } - sqlite.getConnection().commit(); + batchSaveRestrictions(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist restriction; {}", sqle.getMessage()); } } + private void batchSaveRestrictions(Database database, PreparedStatement prep) throws SQLException { + sqlite.getConnection().setAutoCommit(false); + for (Restriction restriction : database.getRestrictions()) { + prep.setString(1, restriction.getId()); + prep.setString(2, restriction.getSource().getId()); + prep.setString(3, restriction.getVia().getId()); + prep.setString(4, restriction.getTarget().getId()); + prep.setString(5, restriction.getType().name()); + prep.executeUpdate(); + } + sqlite.getConnection().commit(); + } + /** * Saves all {@link Building}s to the SQLite file. Basic attributes are stored in the table `Building`. * Furthermore, for each building, a list of corner points are stored in the table `BuildingConsistsOf`. @@ -475,7 +519,8 @@ private void saveBuildings(Database database) { } // Store corner list of building in database - final String cornerStatement = "INSERT INTO " + TABLES.BUILDING_CONSISTS_OF + "(building_id, lat, lon, sequence_number) VALUES (?, ?, ?, ?)"; + final String cornerStatement = "INSERT INTO " + TABLES.BUILDING_CONSISTS_OF + + "(building_id, lat, lon, sequence_number) VALUES (?, ?, ?, ?)"; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(cornerStatement)) { final boolean autoCommit = sqlite.getConnection().getAutoCommit(); @@ -507,26 +552,30 @@ private void saveBuildings(Database database) { private void saveRoutes(Database database) { String columns = "id, sequence_number, connection_id"; String statement = "INSERT INTO " + TABLES.ROUTE + "(" + columns + ") VALUES (?, ?, ?)"; - int sequenceNumber; try (PreparedStatement prep = sqlite.getConnection().prepareStatement(statement)) { boolean autoCommit = sqlite.getConnection().getAutoCommit(); - sqlite.getConnection().setAutoCommit(false); - for (Route route : database.getRoutes()) { - sequenceNumber = 0; - for (Connection connection : route.getConnections()) { - prep.setString(1, route.getId()); - prep.setInt(2, sequenceNumber); - prep.setString(3, connection.getId()); - - prep.executeUpdate(); - sequenceNumber++; - } - } - sqlite.getConnection().commit(); + batchSaveRoutes(database, prep); sqlite.getConnection().setAutoCommit(autoCommit); } catch (SQLException sqle) { log.error("error while trying to persist routes: {}", sqle.getMessage()); } } + private void batchSaveRoutes(Database database, PreparedStatement prep) throws SQLException { + int sequenceNumber; + sqlite.getConnection().setAutoCommit(false); + for (Route route : database.getRoutes()) { + sequenceNumber = 0; + for (Connection connection : route.getConnections()) { + prep.setString(1, route.getId()); + prep.setInt(2, sequenceNumber); + prep.setString(3, connection.getId()); + + prep.executeUpdate(); + sequenceNumber++; + } + } + sqlite.getConnection().commit(); + } + } diff --git a/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/spatial/Edge.java b/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/spatial/Edge.java index 1aab70e21..350e95274 100644 --- a/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/spatial/Edge.java +++ b/lib/mosaic-database/src/main/java/org/eclipse/mosaic/lib/database/spatial/Edge.java @@ -68,7 +68,8 @@ public Node getNextNode() { return nextNode; } - public static class InRadius> extends SpatialTreeTraverser.InRadius { + public static class InRadius> + extends SpatialTreeTraverser.InRadius { @Override protected double getCenterDistanceSqr(E item, SpatialTree tree) { return item.getNearestPointOnEdge(center).distanceSqrTo(center); diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/math/Vector3d.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/math/Vector3d.java index fae546eba..f07b26837 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/math/Vector3d.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/math/Vector3d.java @@ -32,24 +32,63 @@ public class Vector3d implements Serializable { public double y; public double z; + /** + * Constructor for {@link Vector3d}, which initializes it as V_0. + *
+     *     |0|
+     * v = |0|
+     *     |0|
+     * 
+ */ public Vector3d() { x = 0; y = 0; z = 0; } + /** + * Constructor for {@link Vector3d}, initializing it with the given coordinates. + *
+     *     |x|
+     * v = |y|
+     *     |z|
+     * 
+ * + * @param x X-Coordinate + * @param y Y-Coordinate + * @param z Z-Coordinate + */ public Vector3d(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } + /** + * Constructor for {@link Vector3d}, + * initializing it with a copy of the coordinates from another given {@link Vector3d}. + *
+     *  Vector3d(v_j):
+     *         |x_j|
+     *     v = |y_j|
+     *         |z_j|
+     * 
+ * + * @param v {@link Vector3d} to be copied + **/ public Vector3d(Vector3d v) { x = v.x; y = v.y; z = v.z; } + /** + * Sets the coordinates of the {@link Vector3d} to the given value, + * setting it to a copy of the coordinates from another given {@link Vector3d}. + * + * @param v {@link Vector3d} to be copied + * @return the vector on which {@code set} has been called + */ public Vector3d set(Vector3d v) { x = v.x; y = v.y; @@ -57,6 +96,14 @@ public Vector3d set(Vector3d v) { return this; } + /** + * Sets the coordinates of the {@link Vector3d} to the given values. + * + * @param x X-Coordinate + * @param y Y-Coordinate + * @param z Z-Coordinate + * @return the vector on which {@code set} has been called + */ public Vector3d set(double x, double y, double z) { this.x = x; this.y = y; @@ -64,6 +111,12 @@ public Vector3d set(double x, double y, double z) { return this; } + /** + * Sets all entries of the {@link Vector3d} to the given value. + * + * @param f given value + * @return the vector on which {@code set} has been called + */ public Vector3d set(double f) { x = f; y = f; @@ -71,6 +124,18 @@ public Vector3d set(double f) { return this; } + /** + * Multiplies a scalar to the {@link Vector3d}. + *
+     *  v_i.multiply(f):
+     *      x_i = x_i * f
+     *      y_i = y_i * f
+     *      z_i = z_i * f
+     * 
+ * + * @param f scalar of type double + * @return the vector on which {@code multiply} has been called + */ public Vector3d multiply(double f) { x *= f; y *= f; @@ -78,6 +143,20 @@ public Vector3d multiply(double f) { return this; } + /** + * Multiplies a scalar to a {@link Vector3d}, + * storing the multiplication-result into a given vector. + *
+     *  v_i.multiply(f, v_r):
+     *      x_r = x_i * f
+     *      y_r = y_i * f
+     *      z_r = z_i * f
+     * 
+ * + * @param f scalar of type double + * @param result the {@link Vector3d} where the multiplication result should be saved to + * @return the result-vector + */ public Vector3d multiply(double f, Vector3d result) { result.x = x * f; result.y = y * f; @@ -85,6 +164,18 @@ public Vector3d multiply(double f, Vector3d result) { return result; } + /** + * Coordinate-wise multiplication of two {@link Vector3d vectors}. + *
+     *  v_i.scale(v_j):
+     *      x_i = x_i * x_j
+     *      y_i = y_i * y_j
+     *      z_i = z_i * z_j
+     * 
+ * + * @param scale the {@link Vector3d} to be scaled with + * @return the vector on which {@code scale} has been called + */ public Vector3d scale(Vector3d scale) { x *= scale.x; y *= scale.y; @@ -92,6 +183,20 @@ public Vector3d scale(Vector3d scale) { return this; } + /** + * Coordinate-wise multiplication of two {@link Vector3d vectors}, + * storing the scale-result into a given vector. + *
+     *  v_i.scale(v_j, v_r):
+     *      x_r = x_i * x_j
+     *      y_r = y_i * y_j
+     *      z_r = z_i * z_j
+     * 
+ * + * @param scale the {@link Vector3d} to be scaled with + * @param result the {@link Vector3d} where the scale-result should be saved to + * @return the result-vector + */ public Vector3d scale(Vector3d scale, Vector3d result) { result.x = x * scale.x; result.y = y * scale.y; @@ -99,6 +204,18 @@ public Vector3d scale(Vector3d scale, Vector3d result) { return result; } + /** + * Coordinate-wise addition of two {@link Vector3d vectors}. + *
+     *  v_i.add(v_j):
+     *      x_i = x_i + x_j
+     *      y_i = y_i + y_j
+     *      z_i = z_i + z_j
+     * 
+ * + * @param v the {@link Vector3d} to be added + * @return the vector on which {@code add} has been called + */ public Vector3d add(Vector3d v) { x += v.x; y += v.y; @@ -106,6 +223,20 @@ public Vector3d add(Vector3d v) { return this; } + /** + * Coordinate-wise addition of two {@link Vector3d vectors}, + * storing the addition-result into a given vector. + *
+     *  v_i.add(v_j, v_r):
+     *      x_r = x_i + x_j
+     *      y_r = y_i + y_j
+     *      z_r = z_i + z_j
+     * 
+ * + * @param v the {@link Vector3d} to be added + * @param result the {@link Vector3d} where the addition-result should be saved to + * @return the result-vector + */ public Vector3d add(Vector3d v, Vector3d result) { result.x = x + v.x; result.y = y + v.y; @@ -113,6 +244,18 @@ public Vector3d add(Vector3d v, Vector3d result) { return result; } + /** + * Coordinate-wise subtraction of two {@link Vector3d vectors}. + *
+     *  v_i.subtract(v_j):
+     *      x_i = x_i - x_j
+     *      y_i = y_i - y_j
+     *      z_i = z_i - z_j
+     * 
+ * + * @param v the {@link Vector3d} to be subtracted + * @return the vector on which {@code subtract} has been called + */ public Vector3d subtract(Vector3d v) { x -= v.x; y -= v.y; @@ -120,6 +263,20 @@ public Vector3d subtract(Vector3d v) { return this; } + /** + * Coordinate-wise subtraction of two {@link Vector3d vectors}, + * storing the subtraction-result into a given vector. + *
+     *  v_i.subtract(v_j, v_r):
+     *      x_r = x_i - x_j
+     *      y_r = y_i - y_j
+     *      z_r = z_i - z_j
+     * 
+ * + * @param v the {@link Vector3d} to be subtracted + * @param result the {@link Vector3d} where the subtraction-result should be saved to + * @return the result-vector + */ public Vector3d subtract(Vector3d v, Vector3d result) { result.x = x - v.x; result.y = y - v.y; @@ -128,10 +285,33 @@ public Vector3d subtract(Vector3d v, Vector3d result) { } + /** + * The dot product of two {@link Vector3d} resulting in a scalar. + *
+     *  v_i.dot(v_j): = x_i * x_j + y_i * y_j + z_i * z_j
+     * 
+ * + * @param v the {@link Vector3d} to be used for the dot product + * @return the resulting scalar + */ public double dot(Vector3d v) { return x * v.x + y * v.y + z * v.z; } + /** + * The cross-product of two {@link Vector3d}, + * storing the subtraction-result into a given vector. + *
+     *  v_i.cross(v_j, v_r):
+     *      x_r = y_i * z_j - z_i * y_j
+     *      y_r = z_i * x_j - x_i * z_j
+     *      z_r = x_i * y_j - y_i * x_j
+     * 
+ * + * @param v the {@link Vector3d} to be used for the cross-product + * @param result the {@link Vector3d} where the cross-product should be saved to + * @return the resulting {@link Vector3d} + */ public Vector3d cross(Vector3d v, Vector3d result) { result.x = y * v.z - z * v.y; result.y = z * v.x - x * v.z; @@ -142,7 +322,7 @@ public Vector3d cross(Vector3d v, Vector3d result) { /** * Calculates and returns the angle between the current and the given vector in radians. * - * @param v + * @param v the given vector * @return angle in radians */ public double angle(Vector3d v) { @@ -150,6 +330,11 @@ public double angle(Vector3d v) { return Math.acos(a); } + /** + * Normalizes the {@link Vector3d} by dividing it by its {@link #magnitude()}. + * + * @return the normalized {@link Vector3d} + */ public Vector3d norm() { double mag = magnitude(); if (!MathUtils.isFuzzyZero(mag)) { @@ -159,6 +344,13 @@ public Vector3d norm() { } } + /** + * Normalizes the {@link Vector3d} by dividing it by its {@link #magnitude()}, + * storing the result into a given vector. + * + * @param result the {@link Vector3d} where the normalization should be saved to + * @return the normalized {@link Vector3d} + */ public Vector3d norm(Vector3d result) { double mag = magnitude(); if (!MathUtils.isFuzzyZero(mag)) { @@ -176,10 +368,30 @@ public double magnitudeSqr() { return x * x + y * y + z * z; } + /** + * Method to determine the Euclidean distance between the two points represented by two {@link Vector3d Vector3ds}, + * resulting in a scalar value. + *
+     * v_i.distanceTo(v_j) = sqrt((x_j - x_i)^2 + (y_j - y_i)^2 + (z_j - z_i)^2)
+     * 
+ * + * @param v the {@link Vector3d} to which the distance should be determined + * @return the resulting Euclidean distance + */ public double distanceTo(Vector3d v) { return Math.sqrt(distanceSqrTo(v)); } + /** + * Method to determine the sqquared Euclidean distance between the two points represented by two {@link Vector3d Vector3ds}, + * resulting in a scalar value. + *
+     * v_i.distanceSqrTo(v_j) = (x_j - x_i)^2 + (y_j - y_i)^2 + (z_j - z_i)^2
+     * 
+ * + * @param v the {@link Vector3d} to which the squared distance should be determined + * @return the resulting squared Euclidean distance + */ public double distanceSqrTo(Vector3d v) { double dx = (v.x - x); double dy = (v.y - y); @@ -188,32 +400,35 @@ public double distanceSqrTo(Vector3d v) { } /** - * Rotates this vector by the specified angle (in degrees) around the given axis. + * Rotates this {@link Vector3d} by the specified angle (in degrees) around the given axis. * * @param angleDeg Rotation angle in degrees * @param axis Rotation axis + * @return the rotated {@link Vector3d} */ public Vector3d rotateDeg(double angleDeg, Vector3d axis) { return rotate(Math.toRadians(angleDeg), axis.x, axis.y, axis.z); } /** - * Rotates this vector by the specified angle (in radians) around the given axis. + * Rotates this {@link Vector3d} by the specified angle (in radians) around the given axis. * * @param angle Rotation angle in radians * @param axis Rotation axis + * @return the rotated {@link Vector3d} */ public Vector3d rotate(double angle, Vector3d axis) { return rotate(angle, axis.x, axis.y, axis.z); } /** - * Rotates this vector by the specified angle (in radians) around the given axis. + * Rotates this {@link Vector3d} by the specified angle (in radians) around the given axis. * * @param angle Rotation angle in radians * @param axisX Rotation axis x-component * @param axisY Rotation axis y-component * @param axisZ Rotation axis z-component + * @return the rotated {@link Vector3d} */ public Vector3d rotate(double angle, double axisX, double axisY, double axisZ) { double c = Math.cos(angle); @@ -232,38 +447,82 @@ public Vector3d rotate(double angle, double axisX, double axisY, double axisZ) { return this; } + /** + * Writes the {@link Vector3d} to an array using doubles, + * given an offset as start-index. + * + * @param result the array where the result should be saved to + * @param offset the start-index for writing + */ public void toArray(double[] result, int offset) { result[offset] = x; result[offset + 1] = y; result[offset + 2] = z; } + /** + * Writes the {@link Vector3d} to an array using floats, + * given an offset as start-index. + * + * @param result the array where the result should be saved to + * @param offset the start-index for writing + */ public void toArray(float[] result, int offset) { result[offset] = (float) x; result[offset + 1] = (float) y; result[offset + 2] = (float) z; } + /** + * Conversion of {@link Vector3d} to a {@link CartesianPoint} within MOSAIC's coordinate system. + * + * @return the resulting {@link CartesianPoint} + */ public CartesianPoint toCartesian() { return toCartesian(new MutableCartesianPoint()); } + /** + * Conversion of {@link Vector3d} to a {@link CartesianPoint} within MOSAIC's coordinate system, + * storing the results in a given {@link MutableCartesianPoint}. + * + * @param result a {@link MutableCartesianPoint} where the conversion will be saved to + * @return the resulting {@link CartesianPoint} + */ public MutableCartesianPoint toCartesian(MutableCartesianPoint result) { return result.set(x, -z, y); } + /** + * Conversion of {@link Vector3d} to a {@link GeoPoint} using the underlying {@link GeoProjection}. + * + * @return the resulting {@link GeoPoint} + */ public GeoPoint toGeo() { return GeoProjection.getInstance().vectorToGeographic(this); } + /** + * Projection of {@link Vector3d} to a {@link GeoPoint} using the underlying {@link GeoProjection}, + * storing the result in a given {@link MutableGeoPoint}. + * + * @param result the {@link MutableGeoPoint} where the projection will be saved to + * @return the resulting {@link MutableGeoPoint} + */ public MutableGeoPoint toGeo(MutableGeoPoint result) { return GeoProjection.getInstance().vectorToGeographic(this, result); } + /** + * Equal-check for two {@link Vector3d Vector3ds} using {@link MathUtils#isFuzzyEqual(double, double)}. + * + * @param other the {@link Vector3d} to be compared + * @return {@code true} if all coordinates of both {@link Vector3d Vector3ds} are fuzzy-equal, else {@link false} + */ public boolean isFuzzyEqual(Vector3d other) { - return MathUtils.isFuzzyEqual(x, other.x) && - MathUtils.isFuzzyEqual(y, other.y) && - MathUtils.isFuzzyEqual(z, other.z); + return MathUtils.isFuzzyEqual(x, other.x) + && MathUtils.isFuzzyEqual(y, other.y) + && MathUtils.isFuzzyEqual(z, other.z); } @Override diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/AStar.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/AStar.java index 2ff0064bd..4628a590e 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/AStar.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/AStar.java @@ -37,6 +37,9 @@ public class AStar, P extends Point

> { private final Map, CostNode> openListNodes = new HashMap<>(); private final Set> closedList = new HashSet<>(); + /** + * Generates a route from FROM-Node to TO-Node using the A-Star algorithm. + */ public List route(Node from, Node to) { CostNode destinationNode = null; closedList.clear(); @@ -113,11 +116,11 @@ private void expandNode(CostNode node, Node dest) { private class CostNode implements Comparable { /** - * cost of the cheapest path from start to node + * Cost of the cheapest path from start to node. */ private double costs; /** - * best guess of total cost of path from start to destination if it goes through node + * Best guess of total cost of path from start to destination if it goes through node. */ private double estimate; @@ -152,7 +155,7 @@ public interface Node, P extends Point

> { /** * Returns the exact cost between adjacent network nodes. - *

+ *

* Costs are typically based on distance: traveling from one node to another is cheap if the nodes are * very close and expensive if they are far apart. However there might be other factors influencing the * cost: e.g. travel speed, road capacity, etc. @@ -163,11 +166,11 @@ default double getCost(Node nextNode) { /** * Returns the estimated cost in order to reach the final destination node from this node. - *

+ *

* The estimated cost must be lower or equal to the exact cost. If the returned value is higher than the final * exact cost would be this node might be excluded from the routing graph before the exact cost is known * and a potentially more expensive route might win. - *

+ *

* Typically, the cost is estimated by using the straight line distance between this node and the destination * node. However, care must be taken if exact costs between nodes do not only depend on distance but consider * other factors (travel speed, ...) as well. diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/BoundingBox.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/BoundingBox.java index 33760e752..c305b9c4b 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/BoundingBox.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/BoundingBox.java @@ -34,6 +34,9 @@ public boolean isEmpty() { return isEmpty; } + /** + * Resets the {@link BoundingBox}, by setting all fields to their default values. + */ public void clear() { min.set(0.0); max.set(0.0); @@ -74,11 +77,21 @@ private void addPoint(Vector3d point) { } } + /** + * Adds a {@link Vector3d} to the {@link BoundingBox} and updates total bounds. + * + * @param point a single {@link Vector3d} + */ public void add(Vector3d point) { addPoint(point); updateSizeAndCenter(); } + /** + * Adds an arbitrary amount of {@link Vector3d Vector3ds} to the {@link BoundingBox} and updates total bounds. + * + * @param points an arbitrary amount of {@link Vector3d Vector3ds} + */ public void add(Vector3d... points) { for (Vector3d point : points) { addPoint(point); @@ -86,6 +99,11 @@ public void add(Vector3d... points) { updateSizeAndCenter(); } + /** + * Adds a list of {@link Vector3d Vector3ds} to the {@link BoundingBox} and updates total bounds. + * + * @param points a list of {@link Vector3d Vector3ds} + */ public void add(List points) { for (Vector3d point : points) { addPoint(point); @@ -126,13 +144,15 @@ public double distanceSqrToPoint(Vector3d pt) { return distanceSqrToPoint(pt.x, pt.y, pt.z); } + + /** + * Calculates the squared distance to a given point defined by x, y, and z coordinates. + */ public double distanceSqrToPoint(double px, double py, double pz) { if (contains(px, py, pz)) { return 0; } - - double x = 0.0, y = 0.0, z = 0.0; - + double x = 0.0; double tmp = px - min.x; if (tmp < 0) { // px < minX @@ -144,7 +164,7 @@ public double distanceSqrToPoint(double px, double py, double pz) { x = tmp; } } - + double y = 0.0; tmp = py - min.y; if (tmp < 0) { // py < minY @@ -156,7 +176,7 @@ public double distanceSqrToPoint(double px, double py, double pz) { y = tmp; } } - + double z = 0.0; tmp = pz - min.z; if (tmp < 0) { // pz < minZ @@ -168,10 +188,12 @@ public double distanceSqrToPoint(double px, double py, double pz) { z = tmp; } } - return x * x + y * y + z * z; } + /** + * Calculates the distance a {@link Ray} travels until it hits a bounding box. + */ public double hitDistance(Ray r) { double sqr = hitDistanceSqr(r); if (sqr != Double.MAX_VALUE) { @@ -181,8 +203,17 @@ public double hitDistance(Ray r) { return Double.MAX_VALUE; } + /** + * Calculates the squared distance a {@link Ray} travels until it hits a bounding box. + */ public double hitDistanceSqr(Ray r) { - double tmin, tmax, tymin, tymax, tzmin, tzmax, div; + double tMin; + double tMax; + double tyMin; + double tyMax; + double tzMin; + double tzMax; + double div; if (contains(r.origin)) { return 0.0; @@ -190,57 +221,57 @@ public double hitDistanceSqr(Ray r) { div = 1.0 / r.direction.x; if (div >= 0.0) { - tmin = (min.x - r.origin.x) * div; - tmax = (max.x - r.origin.x) * div; + tMin = (min.x - r.origin.x) * div; + tMax = (max.x - r.origin.x) * div; } else { - tmin = (max.x - r.origin.x) * div; - tmax = (min.x - r.origin.x) * div; + tMin = (max.x - r.origin.x) * div; + tMax = (min.x - r.origin.x) * div; } div = 1.0 / r.direction.y; if (div >= 0.0) { - tymin = (min.y - r.origin.y) * div; - tymax = (max.y - r.origin.y) * div; + tyMin = (min.y - r.origin.y) * div; + tyMax = (max.y - r.origin.y) * div; } else { - tymin = (max.y - r.origin.y) * div; - tymax = (min.y - r.origin.y) * div; + tyMin = (max.y - r.origin.y) * div; + tyMax = (min.y - r.origin.y) * div; } - if ((tmin > tymax) || (tymin > tmax)) { + if ((tMin > tyMax) || (tyMin > tMax)) { // no intersection return Double.MAX_VALUE; } - if (tymin > tmin) { - tmin = tymin; + if (tyMin > tMin) { + tMin = tyMin; } - if (tymax < tmax) { - tmax = tymax; + if (tyMax < tMax) { + tMax = tyMax; } div = 1.0 / r.direction.z; if (div >= 0.0) { - tzmin = (min.z - r.origin.z) * div; - tzmax = (max.z - r.origin.z) * div; + tzMin = (min.z - r.origin.z) * div; + tzMax = (max.z - r.origin.z) * div; } else { - tzmin = (max.z - r.origin.z) * div; - tzmax = (min.z - r.origin.z) * div; + tzMin = (max.z - r.origin.z) * div; + tzMax = (min.z - r.origin.z) * div; } - if ((tmin > tzmax) || (tzmin > tmax)) { + if (tMin > tzMax || tzMin > tMax) { // no intersection return Double.MAX_VALUE; } - if (tzmin > tmin) { - tmin = tzmin; + if (tzMin > tMin) { + tMin = tzMin; } - if (tmin > 0) { + if (tMin > 0) { // hit! calculate square distance between ray origin and hit point - double comp = r.direction.x * tmin; + double comp = r.direction.x * tMin; double dist = comp * comp; - comp = r.direction.y * tmin; + comp = r.direction.y * tMin; dist += comp * comp; - comp = r.direction.z * tmin; + comp = r.direction.z * tMin; dist += comp * comp; return dist; } else { diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/KdTree.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/KdTree.java index 85ae8decd..a32f5c943 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/KdTree.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/KdTree.java @@ -24,6 +24,10 @@ public class KdTree extends SpatialTree { private final KdNode root; + private final Comparator xCmp = Comparator.comparingDouble(itemAdapter::getCenterX); + private final Comparator yCmp = Comparator.comparingDouble(itemAdapter::getCenterY); + private final Comparator zCmp = Comparator.comparingDouble(itemAdapter::getCenterZ); + public KdTree(SpatialItemAdapter itemAdapter, List items) { this(itemAdapter, items, 20); } @@ -42,6 +46,7 @@ private class KdNode extends Node { private List children = null; private List items = null; + KdNode(List items, int bucketSz, int depth) { super(depth); @@ -64,8 +69,8 @@ private class KdNode extends Node { right.add(items.get(i)); } children = new ArrayList<>(); - children.add(new KdNode(left, bucketSz, depth+1)); - children.add(new KdNode(right, bucketSz, depth+1)); + children.add(new KdNode(left, bucketSz, depth + 1)); + children.add(new KdNode(right, bucketSz, depth + 1)); } } @@ -94,8 +99,4 @@ public List getItems() { return items; } } - - private final Comparator xCmp = Comparator.comparingDouble(itemAdapter::getCenterX); - private final Comparator yCmp = Comparator.comparingDouble(itemAdapter::getCenterY); - private final Comparator zCmp = Comparator.comparingDouble(itemAdapter::getCenterZ); } diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/LineString.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/LineString.java index 1e9b5b8d2..1bf4e7b2b 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/LineString.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/LineString.java @@ -36,7 +36,8 @@ public interface Walker { } public static class Vecs extends LineString { - public Vecs() { } + public Vecs() { + } public Vecs(List copyFrom) { super(copyFrom); @@ -52,7 +53,8 @@ protected Vector3d newPoint() { } } - public LineString() { } + public LineString() { + } public LineString(List copyFrom) { super(copyFrom); @@ -131,6 +133,7 @@ public double getLength() { /** * Moves the first point along {@link #getStartDirection(Vector3d)} by the given distance. + * * @param len Distance to move the first point by. */ public void extendStart(double len) { @@ -139,6 +142,7 @@ public void extendStart(double len) { /** * Moves the last point along {@link #getEndDirection(Vector3d)} by the given distance. + * * @param len Distance to move the last point by. */ public void extendEnd(double len) { diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/QuickHull2d.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/QuickHull2d.java index bcd708fe1..8b30dc7af 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/QuickHull2d.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/spatial/QuickHull2d.java @@ -24,7 +24,6 @@ /** * This class implements the QuickHull algorithm to compute the convex hull from a set of points. * FIXME: For now the algorithm is 2D and considers only the X- and Z-coordinates. Modified version - * from http://read.pudn.com/downloads50/sourcecode/graph/172533/QuickHull.java__.htm */ public class QuickHull2d { private ArrayList hullEdges; @@ -81,15 +80,13 @@ private double angle(Line l1, Line l2) { private void quickHull(Line ab, int l, int r) { if (l <= r) { - int i, s1, s2, pivot; - double maxDist = 0.0; - double dist; - Vector3d P, q; Vector3d a = ab.p1; Vector3d b = ab.p2; - Line aP, Pb; - - pivot = l; + Vector3d q; + int pivot = l; + double dist; + double maxDist = 0.0; + int i; for (i = l; i <= r; i++) { q = points.get(i); aq.set(a, q); @@ -101,18 +98,18 @@ private void quickHull(Line ab, int l, int r) { } Collections.swap(points, l, pivot); - P = points.get(l); + Vector3d P = points.get(l); - aP = new Line(a, P); - Pb = new Line(P, b); + Line aP = new Line(a, P); + Line Pb = new Line(P, b); hullEdges.add(aP); hullEdges.add(Pb); hullEdges.remove(ab); i = l + 1; - s1 = l; - s2 = r + 1; + int s1 = l; + int s2 = r + 1; while (i < s2) { q = points.get(i); @@ -131,17 +128,15 @@ private void quickHull(Line ab, int l, int r) { } private void computeConvexHull() { - Vector3d a, b, q; - double minX, maxX, x; - int i, j, iLeft, iRight, iLower, iUpper; - Line ab, ba; - hullEdges = new ArrayList<>(); - - // find the left and right extrema. These define the chord that separates the upper and - // lower sets - minX = maxX = points.get(0).x; - iLeft = iRight = 0; + // find the left and right extrema. These define the chord that separates the upper and lower sets + Vector3d q; + double x; + double minX = points.get(0).x; + double maxX = points.get(0).x; + int iLeft = 0; + int iRight = 0; + int i; for (i = 1; i < points.size(); i++) { q = points.get(i); x = q.x; @@ -161,17 +156,12 @@ private void computeConvexHull() { if (iLeft == 0) { iLeft = iRight; } + Vector3d a = points.get(0); + Vector3d b = points.get(iLeft); - a = points.get(0); - b = points.get(iLeft); - - ab = new Line(a, b); - ba = new Line(b, a); - - iUpper = 0; - iLower = points.size(); + int iUpper = 0; + int iLower = points.size(); i = 1; - while (i < iLower) { q = points.get(i); if (ccw(b, a, q) < 0.0) { @@ -183,6 +173,8 @@ private void computeConvexHull() { } } + Line ab = new Line(a, b); + Line ba = new Line(b, a); hullEdges.add(ab); hullEdges.add(ba); @@ -194,6 +186,7 @@ private void computeConvexHull() { Line curEdge = hullEdges.get(0); Line nextEdge; orderedEdges[0] = curEdge; + int j; for (i = 1; i < hullSize; i++) { for (j = 1; j < hullSize; j++) { nextEdge = hullEdges.get(j); diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/LazyGeoProjection.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/LazyGeoProjection.java index 258d5359f..7a1384f33 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/LazyGeoProjection.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/LazyGeoProjection.java @@ -106,8 +106,11 @@ public MutableGeoPoint vectorToGeographic(Vector3d vector3d, MutableGeoPoint mut public interface ProjectionFactory { GeoProjection initializeFromGeo(GeoPoint origin); + GeoProjection initializeFromUtm(UtmPoint origin); + GeoProjection initializeFromCartesian(CartesianPoint origin); + GeoProjection initializeFromVector3d(Vector3d origin); } @@ -133,9 +136,9 @@ public GeoProjection initializeFromVector3d(Vector3d origin) { } private GeoProjection failInitialization() { - throw new IllegalStateException("Cannot initialize LazyGeoProjection from a local coordinate! " + - "LazyGeoProjection was used to translate a local coordinate to global coordinate before " + - "a global origin was set."); + throw new IllegalStateException("Cannot initialize LazyGeoProjection from a local coordinate! " + + "LazyGeoProjection was used to translate a local coordinate to global coordinate before " + + "a global origin was set."); } } diff --git a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/Wgs84Projection.java b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/Wgs84Projection.java index bd45da3f9..f6d45ec85 100644 --- a/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/Wgs84Projection.java +++ b/lib/mosaic-geomath/src/main/java/org/eclipse/mosaic/lib/transform/Wgs84Projection.java @@ -32,11 +32,10 @@ * Converts WGS84 based coordinates (lat,lon) to cartesian coordinates (x,y) * using a WGS84 to UTM conversion algorithm. The conversion is based on * the algorithm written by Chuck Gantz (chuck.gantz@globalstar.com). - * - * @author Chuck Gantz - chuck.gantz@globalstar.com */ public class Wgs84Projection extends GeoProjection { + public static final double K_0 = 0.9996; private final ReferenceEllipsoid ellipsoid = ReferenceEllipsoid.WGS_84; private final GeoPoint geoOrigin; @@ -70,8 +69,11 @@ public Wgs84Projection(UtmPoint origin) { } /** + * This is a legacy constructor, still used internally. + * * @deprecated Legacy constructor. */ + @Deprecated public Wgs84Projection(GeoPoint playgroundCenter, CartesianPoint cartesianOffset) { final UtmZone zone = UtmZone.from(playgroundCenter); this.utmOrigin = new MutableUtmPoint( @@ -136,32 +138,55 @@ public MutableUtmPoint vectorToUtm(Vector3d vector, MutableUtmPoint result) { return geographicToUtm(vectorToGeographic(vector), result); } + /** + * Converts lat/long to UTM coords. Equations from USGS Bulletin 1532 + * East Longitudes are positive, West longitudes are negative. + * North latitudes are positive, South latitudes are negative + * Lat and Long are in decimal degrees + * Written by Chuck Gantz- chuck.gantz@globalstar.com + */ + @SuppressWarnings("checkstyle:localvariablename") @Override public MutableUtmPoint geographicToUtm(GeoPoint geoPoint, MutableUtmPoint result) { - double resultEasting; - double resultNorthing; + double latRad = Math.toRadians(geoPoint.getLatitude()); + // Make sure the longitude is between -180.00 .. 179.9 + double longTemp = (geoPoint.getLongitude() + 180) - (int) ((geoPoint.getLongitude() + 180) / 360) * 360 - 180; + double longRad = Math.toRadians(longTemp); + int zoneNumber = extractZoneNumber(geoPoint, longTemp); - /* Converts lat/long to UTM coords. Equations from USGS Bulletin 1532 - East Longitudes are positive, West longitudes are negative. - North latitudes are positive, South latitudes are negative - Lat and Long are in decimal degrees - Written by Chuck Gantz- chuck.gantz@globalstar.com - */ + double longOrigin = (zoneNumber - 1) * 6 - 180 + 3; //+3 puts origin in middle of zone + double longOriginRad = Math.toRadians(longOrigin); - double a = ellipsoid.equatorialRadius; double eccSquared = ellipsoid.eccentricitySquared; - double k0 = 0.9996; + double eccToTheFourth = eccSquared * eccSquared; + double eccToTheSixth = eccSquared * eccSquared * eccSquared; + double eccPrimeSquared = (eccSquared) / (1 - eccSquared); - double longOrigin; - double eccPrimeSquared; - double N, T, C, A, M; + double a = ellipsoid.equatorialRadius; + double N = a / Math.sqrt(1 - eccSquared * Math.sin(latRad) * Math.sin(latRad)); + double T = Math.tan(latRad) * Math.tan(latRad); + double C = eccPrimeSquared * Math.cos(latRad) * Math.cos(latRad); + double A = Math.cos(latRad) * (longRad - longOriginRad); - // Make sure the longitude is between -180.00 .. 179.9 - double longTemp = (geoPoint.getLongitude() + 180) - (int) ((geoPoint.getLongitude() + 180) / 360) * 360 - 180; + double M = a * ((1 - eccSquared / 4 - 3 * eccToTheFourth / 64 - 5 * eccToTheSixth / 256) * latRad + - (3 * eccSquared / 8 + 3 * eccToTheFourth / 32 + 45 * eccToTheSixth / 1024) * Math.sin(2 * latRad) + + (15 * eccToTheFourth / 256 + 45 * eccToTheSixth / 1024) * Math.sin(4 * latRad) + - (35 * eccToTheSixth / 3072) * Math.sin(6 * latRad)); - double latRad = Math.toRadians(geoPoint.getLatitude()); - double longRad = Math.toRadians(longTemp); - double longOriginRad; + double resultEasting = K_0 * N * (A + (1 - T + C) * A * A * A / 6 + + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120) + + 500000.0; + + double resultNorthing = K_0 * (M + N * Math.tan(latRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24 + + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720)); + if (geoPoint.getLatitude() < 0) { + resultNorthing += 10000000.0; //10000000 meter offset for southern hemisphere + } + final UtmZone zone = UtmZone.from(zoneNumber, UtmZone.getLetter(zoneNumber, geoPoint.getLatitude())); + return result.set(resultEasting, resultNorthing, geoPoint.getAltitude(), zone); + } + + private int extractZoneNumber(GeoPoint geoPoint, double longTemp) { int zoneNumber; if (useZoneOfUtmOrigin && utmOrigin != null) { @@ -186,85 +211,50 @@ public MutableUtmPoint geographicToUtm(GeoPoint geoPoint, MutableUtmPoint result } } } - - - longOrigin = (zoneNumber - 1) * 6 - 180 + 3; //+3 puts origin in middle of zone - longOriginRad = Math.toRadians(longOrigin); - - eccPrimeSquared = (eccSquared) / (1 - eccSquared); - - N = a / Math.sqrt(1 - eccSquared * Math.sin(latRad) * Math.sin(latRad)); - T = Math.tan(latRad) * Math.tan(latRad); - C = eccPrimeSquared * Math.cos(latRad) * Math.cos(latRad); - A = Math.cos(latRad) * (longRad - longOriginRad); - - M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * latRad - - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * latRad) - + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * latRad) - - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * latRad)); - - resultEasting = k0 * N * (A + (1 - T + C) * A * A * A / 6 - + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120) - + 500000.0; - - resultNorthing = k0 * (M + N * Math.tan(latRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24 - + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720)); - if (geoPoint.getLatitude() < 0) { - resultNorthing += 10000000.0; //10000000 meter offset for southern hemisphere - } - final UtmZone zone = UtmZone.from(zoneNumber, UtmZone.getLetter(zoneNumber, geoPoint.getLatitude())); - return result.set(resultEasting, resultNorthing, geoPoint.getAltitude(), zone); + return zoneNumber; } + @SuppressWarnings("checkstyle:localvariablename") @Override public MutableGeoPoint utmToGeographic(UtmPoint utmPoint, MutableGeoPoint result) { - double resultLatitude; - double resultLongitude; - - double k0 = 0.9996; - double a = ellipsoid.equatorialRadius; - double eccSquared = ellipsoid.eccentricitySquared; - double eccPrimeSquared; - double e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared)); - double N1, T1, C1, R1, D, M; - double longOrigin; - double mu, phi1Rad; - double x, y; - // remove 500,000 meter offset for longitude - x = utmPoint.getEasting() - 500000.0; - y = utmPoint.getNorthing(); + double x = utmPoint.getEasting() - 500000.0; + double y = utmPoint.getNorthing(); if (!utmPoint.getZone().isNorthernHemisphere()) { y -= 10000000.0; } - longOrigin = (utmPoint.getZone().getNumber() - 1) * 6 - 180 + 3; //+3 puts origin in middle of zone + double a = ellipsoid.equatorialRadius; + double longOrigin = (utmPoint.getZone().getNumber() - 1) * 6 - 180 + 3; //+3 puts origin in middle of zone - eccPrimeSquared = (eccSquared) / (1 - eccSquared); + double eccSquared = ellipsoid.eccentricitySquared; + double e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared)); + double eccPrimeSquared = (eccSquared) / (1 - eccSquared); - M = y / k0; - mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256)); + double M = y / K_0; + double mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256)); - phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + double phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu); double a1 = 1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad); - N1 = a / Math.sqrt(a1); - T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad); - C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad); - R1 = a * (1 - eccSquared) / Math.pow(a1, 1.5); - D = x / (N1 * k0); + double N1 = a / Math.sqrt(a1); + double T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad); + double C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad); + double R1 = a * (1 - eccSquared) / Math.pow(a1, 1.5); + double D = x / (N1 * K_0); - double lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + double lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) + * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720); - resultLatitude = Math.toDegrees(lat); + double resultLatitude = Math.toDegrees(lat); double lng = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad); - resultLongitude = longOrigin + Math.toDegrees(lng); + double resultLongitude = longOrigin + Math.toDegrees(lng); if (!failIfOutsideWorld) { resultLatitude = MathUtils.clamp(resultLatitude, -90.0, 90.0); diff --git a/lib/mosaic-network/src/main/java/org/eclipse/mosaic/lib/coupling/ClientServerChannel.java b/lib/mosaic-network/src/main/java/org/eclipse/mosaic/lib/coupling/ClientServerChannel.java index abe356f4f..051da003c 100644 --- a/lib/mosaic-network/src/main/java/org/eclipse/mosaic/lib/coupling/ClientServerChannel.java +++ b/lib/mosaic-network/src/main/java/org/eclipse/mosaic/lib/coupling/ClientServerChannel.java @@ -128,6 +128,7 @@ public static final class CMD { /** * Allowed address types. + * FIXME: Is this still needed? */ public static final class ADDRESSTYPE { @@ -163,7 +164,7 @@ public static final class ADDRESSTYPE { final private OutputStream out; /** - * Logger + * Logger (not yet used). *///TODO: implement usage final private Logger log; @@ -206,8 +207,6 @@ public ClientServerChannel(InetAddress host, int port, Logger log) throws IOExce /** * Closes the channel. - * - * @throws java.io.IOException */ public void close() throws IOException { this.socket.close(); @@ -223,10 +222,10 @@ private ReceiveMessage readMessage() throws IOException { /** * Reads a message from the incoming channel. + * TODO: ChannelID (and length) not yet treated * * @return The read message. - * @throws java.io.IOException - */ //TODO: ChannelID (and length) not yet treated + */ public ReceiveMessageContainer readMessage(IdTransformer idTransformer) throws IOException { ReceiveMessage receiveMessage = this.readMessage(); V2xReceiverInformation recInfo = new V2xReceiverInformation(receiveMessage.getTime()).signalStrength(receiveMessage.getRssi()); @@ -241,7 +240,6 @@ public ReceiveMessageContainer readMessage(IdTransformer idTran * Reads a port from the incoming stream. * * @return the read port as int - * @throws java.io.IOException */ public int readPortBody() throws IOException { PortExchange portExchange = Validate.notNull(PortExchange.parseDelimitedFrom(in), "Could not read port."); @@ -252,7 +250,6 @@ public int readPortBody() throws IOException { * Reads a time from the incoming stream. * * @return the read time as long - * @throws java.io.IOException */ public long readTimeBody() throws IOException { TimeMessage timeMessage = Validate.notNull(TimeMessage.parseDelimitedFrom(in), "Could not read time."); @@ -260,15 +257,13 @@ public long readTimeBody() throws IOException { } /** - * Reads a single command from the input stream - * blocking + * Reads a single command from the input stream blocking. * * @return the read command - * @throws java.io.IOException */ public int readCommand() throws IOException { CommandMessage commandMessage = Validate.notNull(CommandMessage.parseDelimitedFrom(in), "Could not read command."); - return ProtobufCMDToCMD(commandMessage.getCommandType()); + return protobufCmdToCmd(commandMessage.getCommandType()); } //#################################################################### @@ -281,7 +276,6 @@ public int readCommand() throws IOException { * @param startTime the first point in time simulated by the simulator * @param endTime the last timestep simulated by the simulator * @return command returned by the federate - * @throws IOException Communication error. */ public int writeInitBody(long startTime, long endTime) throws IOException { writeCommand(CMD.INIT); //Announce INIT message @@ -297,7 +291,6 @@ public int writeInitBody(long startTime, long endTime) throws IOException { * @param time time at which the node is added * @param nodes a list of ids and positions * @return command returned by the federate - * @throws IOException Communication error. */ public int writeAddNodeMessage(long time, List nodes) throws IOException { writeCommand(CMD.UPDATE_NODE); //Announce UPDATE_NODE message @@ -318,7 +311,6 @@ public int writeAddNodeMessage(long time, List nodes) throws * @param time the time at which he RSU is added * @param rsus list of ids and positions * @return command returned by the federate - * @throws IOException Communication error. */ public int writeAddRsuNodeMessage(long time, List rsus) throws IOException { writeCommand(CMD.UPDATE_NODE); @@ -340,7 +332,6 @@ public int writeAddRsuNodeMessage(long time, List rsus) throw * @param time time at which the positions are updated * @param nodes a list of ids and positions * @return command returned by the federate - * @throws IOException Communication error. */ public int writeUpdatePositionsMessage(long time, List nodes) throws IOException { writeCommand(CMD.UPDATE_NODE); @@ -361,7 +352,6 @@ public int writeUpdatePositionsMessage(long time, List nodes) * @param time time at which the nodes are removed * @param ids list of IDs to remove * @return command returned by the federate - * @throws IOException Communication error. */ public int writeRemoveNodesMessage(long time, List ids) throws IOException { writeCommand(CMD.UPDATE_NODE); @@ -377,7 +367,7 @@ public int writeRemoveNodesMessage(long time, List ids) throws IOExcept return readCommand(); } - // @param channelId the channelID //TODO:make enum from + // @param channelId the channelID //TODO: make enum from /** * Write send message header to stream. @@ -389,13 +379,17 @@ public int writeRemoveNodesMessage(long time, List ids) throws IOExcept * @param msgLength length of the message * @param dac DestinationAddressContainer with the destination address of the sender and additional information * @return command returned by the federate - * @throws IOException Communication error. */ public int writeSendMessage(long time, int srcNodeId, int msgId, long msgLength, DestinationAddressContainer dac) throws IOException { writeCommand(CMD.MSG_SEND); - SendMessageMessage.Builder sendMess = SendMessageMessage.newBuilder(); //Add message details to the builder - sendMess.setTime(time).setNodeId(srcNodeId).setChannelId(translateChannel(dac.getAdhocChannelId())).setMessageId(msgId).setLength(msgLength); + //Add message details to the builder + SendMessageMessage.Builder sendMess = SendMessageMessage.newBuilder() + .setTime(time) + .setNodeId(srcNodeId) + .setChannelId(translateChannel(dac.getAdhocChannelId())) + .setMessageId(msgId) + .setLength(msgLength); ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE); buffer.put(dac.getAddress().getIPv4Address().getAddress()); //make an int32 out of the byte array @@ -448,7 +442,6 @@ public int writeSendMessage(long time, int srcNodeId, * @param externalId the external (federate-internal) ID of the node * @param configuration the actual configuration * @return command returned by the federate - * @throws IOException */ public int writeConfigMessage(long time, int msgID, int externalId, AdHocConfiguration configuration) throws IOException { writeCommand(CMD.CONF_RADIO); @@ -467,7 +460,8 @@ public int writeConfigMessage(long time, int msgID, int externalId, AdHocConfigu default: throw new RuntimeException("Illegal number of radios in configuration: " + configuration.getRadioMode().toString()); } - if (configuration.getRadioMode() == AdHocConfiguration.RadioMode.SINGLE || configuration.getRadioMode() == AdHocConfiguration.RadioMode.DUAL) { + if (configuration.getRadioMode() == AdHocConfiguration.RadioMode.SINGLE + || configuration.getRadioMode() == AdHocConfiguration.RadioMode.DUAL) { ConfigureRadioMessage.RadioConfiguration.Builder radioConfig1 = ConfigureRadioMessage.RadioConfiguration.newBuilder(); radioConfig1.setReceivingMessages(false); //!!Semantic in Java: true -> only routing radioConfig1.setIpAddress(inet4ToInt(configuration.getConf0().getNewIP())); //Semantic in federates: false -> only routing @@ -505,7 +499,6 @@ public int writeConfigMessage(long time, int msgID, int externalId, AdHocConfigu * Command: advance time. * * @param time point in time up to which advance is granted - * @throws IOException Communication error. */ public void writeAdvanceTimeMessage(long time) throws IOException { writeCommand(CMD.ADVANCE_TIME); @@ -521,12 +514,12 @@ public void writeAdvanceTimeMessage(long time) throws IOException { * @throws IOException Communication error. */ public void writeCommand(int cmd) throws IOException { - CommandType protobufCMD = cmdToProtobufCMD(cmd); - if (protobufCMD == CommandType.UNDEF) { + CommandType protobufCmd = cmdToProtobufCmd(cmd); + if (protobufCmd == CommandType.UNDEF) { return; } CommandMessage.Builder commandMessage = CommandMessage.newBuilder(); - commandMessage.setCommandType(protobufCMD); + commandMessage.setCommandType(protobufCmd); commandMessage.build().writeDelimitedTo(out); } @@ -548,8 +541,8 @@ private int inet4ToInt(Inet4Address ip) { return buffer.getInt(); } - private int ProtobufCMDToCMD(CommandType protoCMD) { - switch (protoCMD) { + private int protobufCmdToCmd(CommandType protoCmd) { + switch (protoCmd) { case INIT: return CMD.INIT; case SHUT_DOWN: @@ -581,7 +574,7 @@ private int ProtobufCMDToCMD(CommandType protoCMD) { } } - private CommandType cmdToProtobufCMD(int cmd) { + private CommandType cmdToProtobufCmd(int cmd) { switch (cmd) { case CMD.INIT: return CommandType.INIT; @@ -637,7 +630,7 @@ private ClientServerChannelProtos.RadioChannel translateChannel(AdHocChannel cha case SCH6: return ClientServerChannelProtos.RadioChannel.PROTO_SCH6; default: - throw new RuntimeException("Channel " + channel.toString() + " does not exist in MOSAIC"); + throw new RuntimeException("Channel " + channel + " does not exist in MOSAIC"); } } diff --git a/lib/mosaic-objects/src/main/java/org/eclipse/mosaic/lib/objects/addressing/IpResolver.java b/lib/mosaic-objects/src/main/java/org/eclipse/mosaic/lib/objects/addressing/IpResolver.java index 6a7470672..fe824da5a 100644 --- a/lib/mosaic-objects/src/main/java/org/eclipse/mosaic/lib/objects/addressing/IpResolver.java +++ b/lib/mosaic-objects/src/main/java/org/eclipse/mosaic/lib/objects/addressing/IpResolver.java @@ -128,6 +128,8 @@ public Inet4Address getNetMask() { } /** + * Method to look up an {@link Inet4Address} for a given MOSAIC-style host name. + * * @param hostname the units ID veh_0; rsu_1; tl_2; cs_3 etc. * @return the hosts Inet4Address if it is registered or null if not */ @@ -138,6 +140,7 @@ public Inet4Address lookup(String hostname) { } /** + * Method to look up a MOSAIC-style host name for a given {@link Inet4Address}. * @param address the Inet4Address to lookup * @return name of the host belonging to the given address or null if none found */ diff --git a/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/ClassUtils.java b/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/ClassUtils.java index 8d72be6c3..8464d55de 100644 --- a/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/ClassUtils.java +++ b/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/ClassUtils.java @@ -66,6 +66,7 @@ private static void setSysPathsToNull() throws NoSuchFieldException, SecurityExc /** * Add a URL to the system class loader. + * @throws IllegalStateException */ public static void addUrlToClassloader(File jar) throws Exception { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); diff --git a/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/VehicleReferenceUtils.java b/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/VehicleReferenceUtils.java index 5dcd977c7..b135f1fff 100644 --- a/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/VehicleReferenceUtils.java +++ b/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/VehicleReferenceUtils.java @@ -46,6 +46,7 @@ public static CartesianPoint fromCenterToFrontBumper(CartesianPoint pos, double public static GeoPoint fromCenterToFrontBumper(GeoPoint pos, double heading, double length) { return fromCenterToFrontBumper(pos.toVector3d(), heading, length).toGeo(); } + /** * Moves the position reference of a vehicle from the center of the front bumper to its bounding box center. */ diff --git a/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/cli/CommandLineParser.java b/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/cli/CommandLineParser.java index 9df31d471..848fcd96f 100644 --- a/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/cli/CommandLineParser.java +++ b/lib/mosaic-utils/src/main/java/org/eclipse/mosaic/lib/util/cli/CommandLineParser.java @@ -74,12 +74,13 @@ public CommandLineParser(final Class parameterClass) { Map optionGroups = new HashMap<>(); - // build Options out of declared fields of parameter object + // build Options out of declared fields of the parameter object for (Field field : FieldUtils.getAllFields(parameterClass)) { if (field.isAnnotationPresent(CommandLineOption.class)) { final CommandLineOption cliAnnotation = field.getAnnotation(CommandLineOption.class); - final Option option = new Option(StringUtils.defaultIfBlank(cliAnnotation.shortOption(), null), cliAnnotation.description()); + final Option option = + new Option(StringUtils.defaultIfBlank(cliAnnotation.shortOption(), null), cliAnnotation.description()); option.setLongOpt(cliAnnotation.longOption()); if (StringUtils.isNotEmpty(cliAnnotation.argName())) { option.setArgs(1); @@ -158,7 +159,7 @@ public final T parseArguments(final String[] args, final T parameters) throws Pa private List filterSystemProperties(String[] args) { final List argumentsToParse = new ArrayList<>(); - for (String arg: args) { + for (String arg : args) { if (arg.startsWith("-D") && arg.contains("=")) { String[] systemProperty = arg.substring(2).split("="); System.setProperty(systemProperty[0], systemProperty[1]); @@ -172,6 +173,9 @@ private List filterSystemProperties(String[] args) { /** * Transforms the object, which holds the parameter values into a list of arguments, which can be * used to start MOSAIC processes with valid arguments. + * + * @throws UnsupportedOperationException if parameter is not in the list of supported arguments + * @throws RuntimeException if parameter could not be parsed */ public final List transformToArguments(final T parameters) { final List arguments = new LinkedList<>(); @@ -195,7 +199,9 @@ public final List transformToArguments(final T parameters) { arguments.add(((File) field.get(parameters)).getAbsolutePath()); } } else { - throw new UnsupportedOperationException(String.format("Could not transform %s to argument. Unsupported type.", field.getName())); + throw new UnsupportedOperationException( + String.format("Could not transform %s to argument. Unsupported type.", field.getName()) + ); } } @@ -205,6 +211,11 @@ public final List transformToArguments(final T parameters) { return arguments; } + /** + * Prints the help. + * + * @param printWriter writer to output help to + */ public void printHelp(PrintWriter printWriter) { HelpFormatter helpFormatter = new HelpFormatter(); @@ -225,12 +236,20 @@ public void printHelp() { } /** - * @return all options declared in the parameter object this parser has been initialized with + * This method provides all options declared in the parameter object this parser has been initialized with. */ public final Options getOptions() { return this.options; } + /** + * This method is used to define a usage hint for the respective {@link CommandLineParser}. + * + * @param usageHint the hint to be set + * @param header header for the hint + * @param footer footer for the hint + * @return the object to chain further methods + */ public CommandLineParser usageHint(String usageHint, String header, String footer) { this.header = ObjectUtils.defaultIfNull(header, this.header); this.footer = ObjectUtils.defaultIfNull(footer, this.footer); diff --git a/pom.xml b/pom.xml index 736c3c0bd..adbcb1eaa 100644 --- a/pom.xml +++ b/pom.xml @@ -590,12 +590,12 @@ to specify the checkstyle-version. report plugins do not allow to change versions of plugin dependencies.--> org.apache.maven.plugins maven-checkstyle-plugin - 3.1.1 + 3.3.1 com.puppycrawl.tools checkstyle - 8.30 + 10.15.0 diff --git a/rti/mosaic-rti-api/src/main/java/org/eclipse/mosaic/rti/api/RtiAmbassador.java b/rti/mosaic-rti-api/src/main/java/org/eclipse/mosaic/rti/api/RtiAmbassador.java index a304dfed6..5b7841405 100644 --- a/rti/mosaic-rti-api/src/main/java/org/eclipse/mosaic/rti/api/RtiAmbassador.java +++ b/rti/mosaic-rti-api/src/main/java/org/eclipse/mosaic/rti/api/RtiAmbassador.java @@ -23,7 +23,7 @@ /** * This interface is offered to each FederateAmbassador to allow - * communication to the RTI. Therefore the RTI has to implement this interface. + * communication to the RTI. Therefore, the RTI has to implement this interface. */ public interface RtiAmbassador extends Interactable { @@ -56,8 +56,8 @@ public interface RtiAmbassador extends Interactable { void requestAdvanceTime(long time, long lookahead, byte priority) throws IllegalValueException; /** - * @return - * @throws IllegalValueException + * Provides the timestamp of them next scheduled event. [ns] + * @throws IllegalValueException if */ long getNextEventTimestamp() throws IllegalValueException; @@ -77,7 +77,7 @@ public interface RtiAmbassador extends Interactable { RandomNumberGenerator createRandomNumberGenerator(); /** - * Provides the monitor instance to log specific events, such as begin of + * Provides the monitor instance to log specific events, such as the start of * the simulation or event triggers. * * @return the monitor instance to log specific events diff --git a/rti/mosaic-rti-core/src/main/java/org/eclipse/mosaic/rti/time/SequentialTimeManagement.java b/rti/mosaic-rti-core/src/main/java/org/eclipse/mosaic/rti/time/SequentialTimeManagement.java index 4ea710ae8..7c56caf68 100644 --- a/rti/mosaic-rti-core/src/main/java/org/eclipse/mosaic/rti/time/SequentialTimeManagement.java +++ b/rti/mosaic-rti-core/src/main/java/org/eclipse/mosaic/rti/time/SequentialTimeManagement.java @@ -34,8 +34,9 @@ public class SequentialTimeManagement extends AbstractTimeManagement { /** * Creates a new instance of the sequential time management. * - * @param federation reference to the ComponentFactory to access simulation components - * @param componentParameters parameters specifically for this {@link TimeManagement, e.g. the target realtime factor for the simulation. + * @param federation reference to the ComponentFactory to access simulation components + * @param componentParameters parameters specifically for this {@link TimeManagement}, + * e.g., the target realtime factor for the simulation. */ public SequentialTimeManagement(ComponentProvider federation, MosaicComponentParameters componentParameters) { super(federation, componentParameters); @@ -55,7 +56,6 @@ public void runSimulation() throws InternalFederateException, IllegalValueExcept this.prepareSimulationRun(); - final PerformanceCalculator performanceCalculator = new PerformanceCalculator(); final RealtimeSynchronisation realtimeSync = new RealtimeSynchronisation(realtimeBrake); diff --git a/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicSimulation.java b/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicSimulation.java index ccfcbc08f..46d50ae98 100644 --- a/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicSimulation.java +++ b/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicSimulation.java @@ -34,6 +34,7 @@ import org.eclipse.mosaic.rti.api.MosaicVersion; import org.eclipse.mosaic.rti.api.TimeManagement; import org.eclipse.mosaic.rti.api.WatchDog; +import org.eclipse.mosaic.rti.api.federatestarter.DockerFederateExecutor; import org.eclipse.mosaic.rti.api.parameters.AmbassadorParameter; import org.eclipse.mosaic.rti.api.parameters.FederateDescriptor; import org.eclipse.mosaic.rti.api.parameters.FederatePriority; @@ -220,7 +221,7 @@ private void initializeSingletons(CScenario scenarioConfiguration) { protected void printMosaicVersion() { LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME).info("Running Eclipse MOSAIC {} on Java JRE v{} ({})", - MosaicVersion.get().toString(), + MosaicVersion.get(), System.getProperty("java.version"), System.getProperty("java.vendor") ); @@ -382,9 +383,9 @@ private void initializeFederate(CRuntime.CFederate federate, FederateDescriptor if (StringUtils.isNotEmpty(federate.dockerImage)) { final String container = federate.id + '-' + simulationId; - descriptor.setFederateExecutor( - descriptor.getAmbassador().createDockerFederateExecutor(federate.dockerImage, host.operatingSystem).setContainerName(container) - ); + DockerFederateExecutor dockerFederateExecutor = descriptor.getAmbassador() + .createDockerFederateExecutor(federate.dockerImage, host.operatingSystem).setContainerName(container); + descriptor.setFederateExecutor(dockerFederateExecutor); } else { int port = federate.port; if (port == 0) { @@ -490,7 +491,6 @@ private void prepareLogging(String simulationId) { logDirectory = Paths.get(logDirectoryValue); } - // actually apply directory to context and init configuration LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator jc = new JoranConfigurator(); @@ -571,7 +571,6 @@ public void run() { * * @param logbackConfigPath logback configuration from which the logDirectory property is read from * @return path to the log directory as String - * @throws Exception in case the log directory could not be read */ private String readLogFolderFromLogback(Path logbackConfigPath) { diff --git a/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicStarter.java b/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicStarter.java index 439c87d84..f604cab05 100644 --- a/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicStarter.java +++ b/rti/mosaic-starter/src/main/java/org/eclipse/mosaic/starter/MosaicStarter.java @@ -146,7 +146,7 @@ protected MosaicSimulation createSimulation() { } protected void printVersionAndCopyrightInfo() { - System.out.println("Eclipse MOSAIC [Version " + MosaicVersion.get().toString() + "]"); + System.out.println("Eclipse MOSAIC [Version " + MosaicVersion.get() + "]"); System.out.println("Copyright (c) 2024 Fraunhofer FOKUS and others. All rights reserved."); System.out.println("License EPL-2.0: Eclipse Public License Version 2 [https://eclipse.org/legal/epl-v20.html]."); System.out.println(); @@ -220,6 +220,7 @@ private T loadJsonConfiguration(Path configurationFile, Class clazz) thro } } + @SuppressWarnings("unchecked") private T loadJsonConfiguration(Path configurationFile, T defaultObject) { try (InputStream inputStream = loadResource(configurationFile)) { return new ObjectInstantiation<>((Class) defaultObject.getClass()).read(inputStream); @@ -274,7 +275,7 @@ protected void printUsage(CommandLineParser cli, String error) { try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(baos, StandardCharsets.UTF_8))) { cli.printHelp(writer); } - String usage = new String(baos.toByteArray(), StandardCharsets.UTF_8); + String usage = baos.toString(StandardCharsets.UTF_8); System.out.format("Invalid command line arguments: %s%n%s", error, usage); }