├── .gitignore ├── CONTRIBUTORS.txt ├── README.md ├── pom.xml └── src ├── main ├── java │ └── cz │ │ └── certicon │ │ └── routing │ │ ├── GlobalOptions.java │ │ ├── application │ │ └── algorithm │ │ │ ├── NodeDataStructure.java │ │ │ ├── Route.java │ │ │ ├── RouteBuilder.java │ │ │ ├── RouteNotFoundException.java │ │ │ ├── RoutingAlgorithm.java │ │ │ ├── algorithms │ │ │ ├── AstarRoutingAlgorithm.java │ │ │ ├── ContractionHierarchiesRoutingAlgorithm.java │ │ │ ├── ContractionHierarchiesUbRoutingAlgorithm.java │ │ │ └── DijkstraRoutingAlgorithm.java │ │ │ ├── common │ │ │ ├── SimpleRoute.java │ │ │ └── SimpleRouteBuilder.java │ │ │ ├── datastructures │ │ │ ├── JgraphtFibonacciDataStructure.java │ │ │ └── TrivialNodeDataStructure.java │ │ │ └── preprocessing │ │ │ └── ch │ │ │ ├── ContractionHierarchiesPreprocessor.java │ │ │ ├── EdgeDifferenceCalculator.java │ │ │ ├── NodeRecalculationStrategy.java │ │ │ ├── Preprocessor.java │ │ │ ├── calculators │ │ │ ├── BasicEdgeDifferenceCalculator.java │ │ │ └── SpatialHeuristicEdgeDifferenceCalculator.java │ │ │ └── strategies │ │ │ ├── LazyRecalculationStrategy.java │ │ │ └── NeighboursOnlyRecalculationStrategy.java │ │ ├── data │ │ ├── DataDestination.java │ │ ├── DataSource.java │ │ ├── Database.java │ │ ├── IoFactory.java │ │ ├── Reader.java │ │ ├── TemporaryMemory.java │ │ ├── Writer.java │ │ ├── basic │ │ │ ├── FileDestination.java │ │ │ ├── FileSource.java │ │ │ ├── FileTemporaryMemory.java │ │ │ ├── StringDestination.java │ │ │ ├── database │ │ │ │ ├── AbstractDatabase.java │ │ │ │ ├── AbstractEmbeddedDatabase.java │ │ │ │ ├── AbstractServerDatabase.java │ │ │ │ ├── EdgeResultHelper.java │ │ │ │ └── impl │ │ │ │ │ ├── AbstractSqliteDatabase.java │ │ │ │ │ └── StringSqliteReader.java │ │ │ └── xml │ │ │ │ ├── AbstractXmlReader.java │ │ │ │ └── AbstractXmlWriter.java │ │ ├── ch │ │ │ ├── ContractionHierarchiesDataRW.java │ │ │ ├── NotPreprocessedException.java │ │ │ └── sqlite │ │ │ │ └── SqliteContractionHierarchiesRW.java │ │ ├── coordinates │ │ │ ├── CoordinateReader.java │ │ │ └── sqlite │ │ │ │ └── SqliteCoordinateReader.java │ │ ├── graph │ │ │ ├── GraphReader.java │ │ │ └── sqlite │ │ │ │ └── SqliteGraphReader.java │ │ ├── nodesearch │ │ │ ├── EvaluableOnlyException.java │ │ │ ├── NodeSearcher.java │ │ │ └── sqlite │ │ │ │ └── SqliteNodeSearcher.java │ │ └── path │ │ │ ├── PathReader.java │ │ │ └── sqlite │ │ │ └── SqlitePathReader.java │ │ ├── model │ │ ├── basic │ │ │ ├── Length.java │ │ │ ├── LengthUnits.java │ │ │ ├── Pair.java │ │ │ ├── Quaternion.java │ │ │ ├── Time.java │ │ │ ├── TimeUnits.java │ │ │ └── Trinity.java │ │ ├── entity │ │ │ ├── CartesianCoords.java │ │ │ ├── Coordinate.java │ │ │ ├── CoordinateSetBuilder.java │ │ │ ├── CoordinateSetBuilderFactory.java │ │ │ ├── DistanceType.java │ │ │ ├── Graph.java │ │ │ ├── GraphBuilder.java │ │ │ ├── GraphBuilderFactory.java │ │ │ ├── NodeSet.java │ │ │ ├── NodeSetBuilder.java │ │ │ ├── NodeSetBuilderFactory.java │ │ │ ├── Path.java │ │ │ ├── PathBuilder.java │ │ │ ├── ch │ │ │ │ ├── ChDataBuilder.java │ │ │ │ ├── ChDataExtractor.java │ │ │ │ ├── ChDataFactory.java │ │ │ │ ├── PreprocessedData.java │ │ │ │ ├── SimpleChDataBuilder.java │ │ │ │ ├── SimpleChDataExtractor.java │ │ │ │ └── SimpleChDataFactory.java │ │ │ ├── common │ │ │ │ ├── SimpleCoordinateSetBuilder.java │ │ │ │ ├── SimpleCoordinateSetBuilderFactory.java │ │ │ │ ├── SimpleGraphBuilder.java │ │ │ │ ├── SimpleGraphBuilderFactory.java │ │ │ │ ├── SimpleNodeSet.java │ │ │ │ ├── SimpleNodeSetBuilder.java │ │ │ │ ├── SimpleNodeSetBuilderFactory.java │ │ │ │ ├── SimplePath.java │ │ │ │ └── SimplePathBuilder.java │ │ │ └── neighbourlist │ │ │ │ ├── NeighbourlistDirectedGraph.java │ │ │ │ └── NeighbourlistGraph.java │ │ └── utility │ │ │ ├── ProgressListener.java │ │ │ ├── iterator │ │ │ ├── DoubleArrayIterator.java │ │ │ ├── IntArrayIterator.java │ │ │ └── LongIterator.java │ │ │ └── progress │ │ │ ├── EmptyProgressListener.java │ │ │ └── SimpleProgressListener.java │ │ ├── presentation │ │ ├── PathDisplayer.java │ │ └── jxmapviewer │ │ │ ├── JxMapViewerFrame.java │ │ │ ├── JxNodeViewer.java │ │ │ ├── LabelWaypoint.java │ │ │ ├── LabelWaypointOverlayPainter.java │ │ │ ├── NodePainter.java │ │ │ └── RoutePainter.java │ │ └── utils │ │ ├── CollectionUtils.java │ │ ├── CommunicationUtils.java │ │ ├── CoordinateUtils.java │ │ ├── DoubleComparator.java │ │ ├── EffectiveUtils.java │ │ ├── GeometryUtils.java │ │ ├── SpeedUtils.java │ │ ├── cor │ │ ├── AbstractChainGroup.java │ │ ├── AbstractHandler.java │ │ ├── ChainGroup.java │ │ ├── ChainLink.java │ │ ├── ChainOfResponsibility.java │ │ ├── Handler.java │ │ ├── LinkedChainOfResponsibility.java │ │ ├── OrChainGroup.java │ │ └── XorChainGroup.java │ │ ├── debug │ │ ├── Log.java │ │ └── PlainTextFormatter.java │ │ ├── efficient │ │ ├── BitArray.java │ │ ├── IntLinkedList.java │ │ └── LongBitArray.java │ │ └── measuring │ │ ├── MemoryMeasurement.java │ │ ├── MemoryUnits.java │ │ ├── StatsLogger.java │ │ ├── TimeLogger.java │ │ └── TimeMeasurement.java └── resources │ └── cz │ └── certicon │ └── routing │ └── data │ ├── basic │ └── database │ │ └── database_connection.properties │ └── osm │ ├── osm_defaultspeed_zone_type.properties │ └── osm_maxspeed_source_zones.properties └── test └── java └── cz └── certicon └── routing ├── algorithm ├── algorithms │ ├── AstarRoutingAlgorithmTest.java │ ├── ContractionHierarchiesRoutingAlgorithmTest.java │ ├── ContractionHierarchiesUbRoutingAlgorithmTest.java │ └── DijkstraRoutingAlgorithmTest.java └── preprocessing │ └── ch │ └── ContractionHierarchiesPreprocessorTest.java └── model ├── basic ├── LengthTest.java └── TimeTest.java └── entity └── ch └── SimpleChDataBuilderTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # autogen.sh-generated files 2 | target 3 | nbproject 4 | *.log 5 | -------------------------------------------------------------------------------- /CONTRIBUTORS.txt: -------------------------------------------------------------------------------- 1 | Michael Bláha -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Routing platform # 2 | 3 | ## Overview ## 4 | 5 | Used for routing from A to B via OSM maps. 6 | 7 | ## Dependencies ## 8 | 9 | - JDK 1.7 or later 10 | - [JUnit](http://www.junit.org) 11 | - [JGraphT](https://github.com/jgrapht/jgrapht) 12 | - [JXMapViewer2](https://github.com/msteiger/jxmapviewer2) 13 | - [OSM-binary](https://github.com/openstreetmap/osmosis/tree/master/osmosis-osm-binary) 14 | - [Protocol buffers](https://github.com/google/protobuf) 15 | - [GraphStream](http://graphstream-project.org/) 16 | - [Trove](http://trove.starlight-systems.com/) 17 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/GlobalOptions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing; 7 | 8 | /** 9 | * Global options defining mostly debugging and measuring (on/off). These 10 | * settings may slow the application down, mostly insignificantly. They may also 11 | * overwhelm the standard output. 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public class GlobalOptions { 16 | 17 | /** 18 | * Defines whether debug time should be measured and displayed 19 | */ 20 | public static boolean DEBUG_TIME = false; 21 | /** 22 | * Defines whether debug checks should be evaluated and displayed 23 | */ 24 | public static boolean DEBUG_CORRECTNESS = false; 25 | /** 26 | * Defines whether time should be measured 27 | */ 28 | public static boolean MEASURE_TIME = false; 29 | /** 30 | * Defines whether statistics should be measured 31 | */ 32 | public static boolean MEASURE_STATS = false; 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/NodeDataStructure.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm; 7 | 8 | import java.util.Iterator; 9 | 10 | /** 11 | * The root interface for various data structures used by algorithms. 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public interface NodeDataStructure { 16 | 17 | /** 18 | * Extract node with the minimal distance. Should be as fast as possible. 19 | * 20 | * @return node with the minimal distance 21 | */ 22 | public T extractMin(); 23 | 24 | /** 25 | * Adds node to the structure. 26 | * 27 | * @param node node to be added 28 | * @param value value to be associated with the node 29 | */ 30 | public void add( T node, double value ); 31 | 32 | /** 33 | * Removes node from the structure. 34 | * 35 | * @param node node to be removed 36 | */ 37 | public void remove( T node ); 38 | 39 | /** 40 | * Notifies the structure about distance change (invoking so called 41 | * decrease-key operation). 42 | * 43 | * @param node node to change 44 | * @param value value to be associated with the node 45 | */ 46 | public void notifyDataChange( T node, double value ); 47 | 48 | /** 49 | * Wipes out the data from this structure. 50 | */ 51 | public void clear(); 52 | 53 | /** 54 | * Returns true or false whether this structure contains nodes or not. 55 | * 56 | * @return boolean value 57 | */ 58 | public boolean isEmpty(); 59 | 60 | /** 61 | * Returns amount of nodes left in the structure. 62 | * 63 | * @return integer value 64 | */ 65 | public int size(); 66 | 67 | /** 68 | * Returns true if the structure contains the given node. 69 | * 70 | * @param node element whose presence is to be tested 71 | * @return true if this structure contains the specified element 72 | */ 73 | public boolean contains( T node ); 74 | 75 | /** 76 | * Returns node with the minimal value. Does not remove it. 77 | * 78 | * @return node with the minimal value 79 | */ 80 | public T peek(); 81 | 82 | /** 83 | * Returns the minimal value in this structure 84 | * 85 | * @return the minimal value 86 | */ 87 | public double minValue(); 88 | 89 | /** 90 | * Returns iterator over all the elements in this structure 91 | * 92 | * @return iterator over the elements 93 | */ 94 | public Iterator iterator(); 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/Route.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm; 7 | 8 | import cz.certicon.routing.application.algorithm.common.SimpleRoute; 9 | import cz.certicon.routing.model.basic.Pair; 10 | import java.util.Iterator; 11 | import java.util.LinkedList; 12 | 13 | /** 14 | * An interface defining the route - a sequence of edges with a source and a 15 | * target 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public interface Route { 20 | 21 | /** 22 | * Returns edge iterator, which traverses edges in the sequence order 23 | * 24 | * @return edge iterator 25 | */ 26 | public Iterator> getEdgeIterator(); 27 | 28 | /** 29 | * Returns id of the target node 30 | * 31 | * @return id of the target node 32 | */ 33 | public long getTarget(); 34 | 35 | /** 36 | * Returns id of the source node 37 | * 38 | * @return id of the source node 39 | */ 40 | public long getSource(); 41 | 42 | /** 43 | * Factory for SimpleRoute 44 | */ 45 | public static class Factory { 46 | 47 | /** 48 | * Creates a simple implementation object of the route 49 | * 50 | * @param edges 51 | * @param source 52 | * @param target 53 | * @return 54 | */ 55 | public static Route createSimpleRoute( LinkedList> edges, long source, long target ) { 56 | return new SimpleRoute( edges, source, target ); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/RouteBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm; 7 | 8 | /** 9 | * An interface defining the functionality of a route builder - where route and 10 | * graphs can be defined later in the implementation. 11 | * 12 | * @author Michael Blaha {@literal } 13 | * @param the route class to be built 14 | * @param the graph to be built upon 15 | */ 16 | public interface RouteBuilder { 17 | 18 | /** 19 | * Sets the source node of this route. It is recommended to set source or 20 | * target before adding edges, so that the other one can be determined 21 | * automatically and the edges can be set appropriately. 22 | * 23 | * @param graph a graph to be built upon 24 | * @param nodeId an id of the source node 25 | */ 26 | public void setSourceNode( G graph, long nodeId ); 27 | 28 | /** 29 | * Sets the target node of this route. It is recommended to set source or 30 | * target before adding edges, so that the other one can be determined 31 | * automatically and the edges can be set appropriately. 32 | * 33 | * @param graph a graph to be built upon 34 | * @param nodeId an id of the target node 35 | */ 36 | public void setTargetNode( G graph, long nodeId ); 37 | 38 | /** 39 | * Adds edge to the beginning of this sequence. Moves the source to the 40 | * other end of added edge. Checks the connection (one node of this edge 41 | * must match the current source node). 42 | * 43 | * @param graph a graph to be built upon 44 | * @param edgeId an id of the added edge 45 | */ 46 | public void addEdgeAsFirst( G graph, long edgeId ); 47 | 48 | /** 49 | * Adds edge to the end of this sequence. Moves the target to the other end 50 | * of added edge. Checks the connection (one node of this edge must match 51 | * the current target node). 52 | * 53 | * @param graph a graph to be built upon 54 | * @param edgeId an id of the added edge 55 | */ 56 | public void addEdgeAsLast( G graph, long edgeId ); 57 | 58 | /** 59 | * Clears the builder for later use 60 | */ 61 | public void clear(); 62 | 63 | /** 64 | * Builds the route 65 | * 66 | * @return the built route 67 | */ 68 | public R build(); 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/RouteNotFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm; 7 | 8 | /** 9 | * Thrown when a route has not been found by the algorithm. Route should always 10 | * be found, therefore this means an implementation or data error. Solution for 11 | * nodes, which are not connected by any path: create maximal connected 12 | * components from the graph. When searching for nodes, make sure they are in 13 | * the same component - select the first/bigger/closer and then map the second 14 | * node inside that component (to the closest node). This ensures the route 15 | * existence. 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class RouteNotFoundException extends Exception { 20 | 21 | public RouteNotFoundException() { 22 | } 23 | 24 | public RouteNotFoundException( String message ) { 25 | super( message ); 26 | } 27 | 28 | public RouteNotFoundException( String message, Throwable cause ) { 29 | super( message, cause ); 30 | } 31 | 32 | public RouteNotFoundException( Throwable cause ) { 33 | super( cause ); 34 | } 35 | 36 | public RouteNotFoundException( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace ) { 37 | super( message, cause, enableSuppression, writableStackTrace ); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/RoutingAlgorithm.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm; 7 | 8 | import java.util.Map; 9 | 10 | /** 11 | * The root interface for routing algorithms. It's purpose is to find the 12 | * shortest path between two points. The distance between two points is abstract 13 | * (geographical distance, time, etc.). 14 | * 15 | * 16 | * @author Michael Blaha {@literal } 17 | * @param the graph class to be routed upon 18 | */ 19 | public interface RoutingAlgorithm { 20 | 21 | /** 22 | * Find the shortest route (R) between a set of source points to a set of 23 | * target points 24 | * 25 | * @param route return type, see {@link RouteBuilder} 26 | * @param routeBuilder builder for the result route 27 | * @param from a set of source points (and their initial distances) 28 | * @param to a set of target points (and their initial distances) 29 | * @return the shortest route of type R 30 | * @throws RouteNotFoundException thrown when no route was found between the 31 | * two points, see the {@link RouteNotFoundException} for more information 32 | */ 33 | public R route( RouteBuilder routeBuilder, Map from, Map to ) throws RouteNotFoundException; 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/common/SimpleRoute.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.common; 7 | 8 | import cz.certicon.routing.application.algorithm.Route; 9 | import cz.certicon.routing.model.basic.Pair; 10 | import java.util.Iterator; 11 | import java.util.LinkedList; 12 | 13 | /** 14 | * Basic implementation of the {@link Route} interface. 15 | * 16 | * @author Michael Blaha {@literal } 17 | */ 18 | public class SimpleRoute implements Route { 19 | 20 | private final LinkedList> edges; 21 | private final long source; 22 | private final long target; 23 | 24 | public SimpleRoute( LinkedList> edges, long source, long target ) { 25 | this.edges = edges; 26 | this.source = source; 27 | this.target = target; 28 | } 29 | 30 | @Override 31 | public Iterator> getEdgeIterator() { 32 | return edges.iterator(); 33 | } 34 | 35 | @Override 36 | public long getTarget() { 37 | return target; 38 | } 39 | 40 | @Override 41 | public long getSource() { 42 | return source; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/common/SimpleRouteBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.common; 7 | 8 | import cz.certicon.routing.application.algorithm.Route; 9 | import cz.certicon.routing.application.algorithm.RouteBuilder; 10 | import cz.certicon.routing.model.entity.Graph; 11 | import cz.certicon.routing.model.basic.Pair; 12 | import java.util.LinkedList; 13 | 14 | /** 15 | * Simple implementation of the {@link RouteBuilder} interface. 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class SimpleRouteBuilder implements RouteBuilder { 20 | 21 | private long source; 22 | private long target; 23 | private LinkedList> edges; 24 | 25 | public SimpleRouteBuilder() { 26 | clear(); 27 | } 28 | 29 | @Override 30 | public void setSourceNode( Graph graph, long nodeId ) { 31 | source = nodeId; 32 | target = nodeId; 33 | } 34 | 35 | @Override 36 | public void setTargetNode( Graph graph, long nodeId ) { 37 | // System.out.println( "target node = " + nodeId ); 38 | target = nodeId; 39 | source = nodeId; 40 | } 41 | 42 | @Override 43 | public void addEdgeAsFirst( Graph graph, long edgeId ) { 44 | int edge = graph.getEdgeByOrigId( edgeId ); 45 | long sourceNode = graph.getNodeOrigId( graph.getSource( edge ) ); 46 | long targetNode = graph.getNodeOrigId( graph.getTarget( edge ) ); 47 | if ( edges.isEmpty() && source == -1 && target == -1 ) { 48 | edges.add( new Pair<>( edgeId, true ) ); 49 | source = sourceNode; 50 | target = targetNode; 51 | } else if ( source == targetNode ) { 52 | edges.addFirst( new Pair<>( edgeId, true ) ); 53 | source = sourceNode; 54 | } else if ( source == sourceNode ) { 55 | edges.addFirst( new Pair<>( edgeId, false ) ); 56 | source = targetNode; 57 | } else { 58 | throw new IllegalArgumentException( "Cannot connect edge: " + edgeId 59 | + " with source: " + sourceNode 60 | + " and target: " + targetNode 61 | + " to: " + source ); 62 | } 63 | } 64 | 65 | @Override 66 | public void addEdgeAsLast( Graph graph, long edgeId ) { 67 | int edge = graph.getEdgeByOrigId( edgeId ); 68 | long sourceNode = graph.getNodeOrigId( graph.getSource( edge ) ); 69 | long targetNode = graph.getNodeOrigId( graph.getTarget( edge ) ); 70 | if ( edges.isEmpty() && source == -1 && target == -1 ) { 71 | edges.add( new Pair<>( edgeId, true ) ); 72 | source = sourceNode; 73 | target = targetNode; 74 | } else if ( target == sourceNode ) { 75 | edges.addLast( new Pair<>( edgeId, true ) ); 76 | target = targetNode; 77 | } else if ( target == targetNode ) { 78 | edges.addLast( new Pair<>( edgeId, false ) ); 79 | target = sourceNode; 80 | } else { 81 | throw new IllegalArgumentException( "Cannot connect edge: " + edgeId 82 | + " with source: " + sourceNode 83 | + " and target: " + targetNode 84 | + " to: " + target ); 85 | } 86 | } 87 | 88 | @Override 89 | public Route build() { 90 | return new SimpleRoute( edges, source, target ); 91 | } 92 | 93 | @Override 94 | public final void clear() { 95 | source = -1; 96 | target = -1; 97 | edges = new LinkedList<>(); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/datastructures/JgraphtFibonacciDataStructure.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.datastructures; 7 | 8 | import cz.certicon.routing.application.algorithm.NodeDataStructure; 9 | import java.util.HashMap; 10 | import java.util.Iterator; 11 | import java.util.Map; 12 | import org.jgrapht.util.FibonacciHeap; 13 | import org.jgrapht.util.FibonacciHeapNode; 14 | 15 | /** 16 | * {@link NodeDataStructure} implementation using Fibonacci's heap (adapter to 17 | * JGraphT lib. Fibonacci). 18 | * 19 | * @author Michael Blaha {@literal } 20 | * @param node type 21 | */ 22 | public class JgraphtFibonacciDataStructure implements NodeDataStructure { 23 | 24 | private final Map> nodeMap; 25 | private final org.jgrapht.util.FibonacciHeap fibonacciHeap; 26 | 27 | public JgraphtFibonacciDataStructure() { 28 | this.fibonacciHeap = new FibonacciHeap<>(); 29 | this.nodeMap = new HashMap<>(); 30 | } 31 | 32 | @Override 33 | public T extractMin() { 34 | FibonacciHeapNode min = fibonacciHeap.removeMin(); 35 | nodeMap.remove( min.getData() ); 36 | return min.getData(); 37 | } 38 | 39 | @Override 40 | public void add( T node, double value ) { 41 | // System.out.println( "Adding " + node + " with value " + value ); 42 | FibonacciHeapNode n = new FibonacciHeapNode<>( node ); 43 | nodeMap.put( node, n ); 44 | fibonacciHeap.insert( n, value ); 45 | } 46 | 47 | @Override 48 | public void remove( T node ) { 49 | FibonacciHeapNode n = nodeMap.get( node ); 50 | nodeMap.remove( node ); 51 | fibonacciHeap.delete( n ); 52 | } 53 | 54 | @Override 55 | public void notifyDataChange( T node, double value ) { 56 | // System.out.println( "Changing " + node + " to value " + value ); 57 | FibonacciHeapNode n = nodeMap.get( node ); 58 | if ( n == null ) { 59 | add( node, value ); 60 | } else if ( value < n.getKey() ) { 61 | fibonacciHeap.decreaseKey( n, value ); 62 | } else if ( value > n.getKey() ) { 63 | remove( node ); 64 | add( node, value ); 65 | } 66 | } 67 | 68 | @Override 69 | public void clear() { 70 | nodeMap.clear(); 71 | fibonacciHeap.clear(); 72 | } 73 | 74 | @Override 75 | public boolean isEmpty() { 76 | return fibonacciHeap.isEmpty(); 77 | } 78 | 79 | @Override 80 | public int size() { 81 | return fibonacciHeap.size(); 82 | } 83 | 84 | @Override 85 | public boolean contains( T node ) { 86 | return nodeMap.containsKey( node ); 87 | } 88 | 89 | @Override 90 | public T peek() { 91 | if ( !fibonacciHeap.isEmpty() ) { 92 | return fibonacciHeap.min().getData(); 93 | } else { 94 | return null; 95 | } 96 | } 97 | 98 | @Override 99 | public double minValue() { 100 | if ( !fibonacciHeap.isEmpty() ) { 101 | return fibonacciHeap.min().getKey(); 102 | } else { 103 | return Double.MAX_VALUE; 104 | } 105 | } 106 | 107 | @Override 108 | public Iterator iterator() { 109 | return nodeMap.keySet().iterator(); 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/datastructures/TrivialNodeDataStructure.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.datastructures; 7 | 8 | import cz.certicon.routing.application.algorithm.NodeDataStructure; 9 | import java.util.Iterator; 10 | import java.util.LinkedList; 11 | import java.util.List; 12 | 13 | /** 14 | * Basic {@link NodeDataStructure} implementation using an array. 15 | * 16 | * @author Michael Blaha {@literal } 17 | * @param node type 18 | */ 19 | public class TrivialNodeDataStructure implements NodeDataStructure { 20 | 21 | private final List> nodes; 22 | 23 | public TrivialNodeDataStructure() { 24 | this.nodes = new LinkedList<>(); 25 | } 26 | 27 | @Override 28 | public T extractMin() { 29 | if ( nodes.isEmpty() ) { 30 | throw new IllegalStateException( "NodeStructure is empty." ); 31 | } 32 | NodeContainer min = nodes.get( 0 ); 33 | for ( NodeContainer node : nodes ) { 34 | if ( node.value < min.value ) { 35 | min = node; 36 | } 37 | } 38 | nodes.remove( min ); 39 | return min.node; 40 | } 41 | 42 | @Override 43 | public void add( T node, double value ) { 44 | nodes.add( new NodeContainer<>( node, value ) ); 45 | } 46 | 47 | @Override 48 | public void remove( T node ) { 49 | for ( int i = 0; i < nodes.size(); i++ ) { 50 | if ( nodes.get( i ).node == node ) { 51 | nodes.remove( i ); 52 | } 53 | } 54 | } 55 | 56 | @Override 57 | public void notifyDataChange( T node, double value ) { 58 | for ( int i = 0; i < nodes.size(); i++ ) { 59 | if ( nodes.get( i ).node == node ) { 60 | nodes.get( i ).value = value; 61 | } 62 | } 63 | } 64 | 65 | @Override 66 | public void clear() { 67 | nodes.clear(); 68 | } 69 | 70 | @Override 71 | public boolean isEmpty() { 72 | return nodes.isEmpty(); 73 | } 74 | 75 | @Override 76 | public int size() { 77 | return nodes.size(); 78 | } 79 | 80 | @Override 81 | public boolean contains( T node ) { 82 | return nodes.contains( node ); 83 | } 84 | 85 | @Override 86 | public T peek() { 87 | if ( nodes.isEmpty() ) { 88 | throw new IllegalStateException( "NodeStructure is empty." ); 89 | } 90 | NodeContainer min = nodes.get( 0 ); 91 | for ( NodeContainer node : nodes ) { 92 | if ( node.value < min.value ) { 93 | min = node; 94 | } 95 | } 96 | return min.node; 97 | } 98 | 99 | @Override 100 | public double minValue() { 101 | if ( nodes.isEmpty() ) { 102 | throw new IllegalStateException( "NodeStructure is empty." ); 103 | } 104 | NodeContainer min = nodes.get( 0 ); 105 | for ( NodeContainer node : nodes ) { 106 | if ( node.value < min.value ) { 107 | min = node; 108 | } 109 | } 110 | return min.value; 111 | } 112 | 113 | @Override 114 | public Iterator iterator() { 115 | return new NodeIterator(); 116 | } 117 | 118 | private static class NodeContainer { 119 | 120 | public final T node; 121 | public double value; 122 | 123 | public NodeContainer( T node, double value ) { 124 | this.node = node; 125 | this.value = value; 126 | } 127 | } 128 | 129 | private class NodeIterator implements Iterator { 130 | 131 | private int counter = -1; 132 | 133 | @Override 134 | public boolean hasNext() { 135 | return counter + 1 < nodes.size(); 136 | } 137 | 138 | @Override 139 | public T next() { 140 | return nodes.get( ++counter ).node; 141 | } 142 | 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/preprocessing/ch/EdgeDifferenceCalculator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.preprocessing.ch; 7 | 8 | /** 9 | * Edge difference is an indicator used as a part of priority queue key. It 10 | * helps to determine the next contracted node. This interface offers 11 | * calculation edge difference function for a given node. 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public interface EdgeDifferenceCalculator { 16 | 17 | /** 18 | * Calculates the ED (edge difference) for the given node N based on the 19 | * node degrees, number of shortcuts and also previously contracted node. 20 | * 21 | * @param contractedNode the node that was just contracted, input -1 if none 22 | * was 23 | * @param nodeDegrees array of node degrees 24 | * @param node the node N for which the edge difference is calculated 25 | * @param numberOfShortcuts number of shortcuts for the node N 26 | * @return edge difference of the node N 27 | */ 28 | public int calculate( int contractedNode, int[] nodeDegrees, int node, int numberOfShortcuts ); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/preprocessing/ch/NodeRecalculationStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.preprocessing.ch; 7 | 8 | import cz.certicon.routing.application.algorithm.NodeDataStructure; 9 | import cz.certicon.routing.application.algorithm.preprocessing.ch.strategies.LazyRecalculationStrategy; 10 | import cz.certicon.routing.model.entity.Graph; 11 | import gnu.trove.iterator.TIntIterator; 12 | 13 | /** 14 | * Interface offering iterator of the nodes to be recalculated as well as 15 | * methods for the recalculation. Principle: once the node is contracted, it is 16 | * necessary to determine the next node to be contracted. This is done via a 17 | * recalculation phase, where all the relevant nodes (based on the 18 | * implementation) are recalculated. At first, these nodes are chosen via 19 | * iterator. While iterating the nodes, each should have its shortcuts 20 | * calculated and after calculation, the onShortcutsCalculated method should be 21 | * called. This is important to perform BEFORE the iterators next operation, 22 | * because in can change the following node (see 23 | * {@link LazyRecalculationStrategy} for example) 24 | * 25 | * @author Michael Blaha {@literal } 26 | */ 27 | public interface NodeRecalculationStrategy { 28 | 29 | /** 30 | * Iterator supplying the caller with nodes requiring recalculation (based 31 | * on the implementation) 32 | * 33 | * @param graph an input graph 34 | * @param data processing data (graph wrapper) 35 | * @param contractedNode recently/last contracted node or -1 if none such 36 | * exists 37 | * @param priorityQueue simple integer priority queue 38 | * @return node iterator 39 | */ 40 | public TIntIterator recalculationIterator( Graph graph, ContractionHierarchiesPreprocessor.ProcessingData data, int contractedNode, NodeDataStructure priorityQueue ); 41 | 42 | /** 43 | * Call when shortcuts get calculated for the node N 44 | * 45 | * @param graph an input graph 46 | * @param nodeDegrees an array of node degrees 47 | * @param node the node N to be recalculated 48 | * @param priorityQueue simple integer priority queue 49 | * @param shortcuts number of shortcuts for this node N 50 | * @param contractedNode recently/last contracted node or -1 if none such 51 | * exists 52 | */ 53 | public void onShortcutsCalculated( Graph graph, int[] nodeDegrees, int node, NodeDataStructure priorityQueue, int shortcuts, int contractedNode ); 54 | 55 | /** 56 | * Setter 57 | * 58 | * @param edgeDifferenceCalculator {@link EdgeDifferenceCalculator} 59 | */ 60 | public void setEdgeDifferenceCalculator( EdgeDifferenceCalculator edgeDifferenceCalculator ); 61 | 62 | /** 63 | * Getter 64 | * 65 | * @return {@link EdgeDifferenceCalculator} 66 | */ 67 | public EdgeDifferenceCalculator getEdgeDifferenceCalculator(); 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/preprocessing/ch/Preprocessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.preprocessing.ch; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.entity.Graph; 10 | import cz.certicon.routing.model.entity.ch.ChDataBuilder; 11 | import cz.certicon.routing.model.utility.ProgressListener; 12 | 13 | /** 14 | * Preprocessor class for creating the {@link PreprocessedData} 15 | * 16 | * @author Michael Blaha {@literal } 17 | * @param data as a result of preprocessing 18 | */ 19 | public interface Preprocessor { 20 | 21 | /** 22 | * Returns preprocessed data based on the implementation 23 | * 24 | * @param dataBuilder an instance of {@link ChDataBuilder} 25 | * @param graphInput an instance of {@link Graph} to calculate on 26 | * @param distanceType distance metric 27 | * @return an instance of {@link PreprocessedData} 28 | * @param minimalShortcutId minimal shortcut ID to be set for new shortcuts 29 | * => current max + 1 30 | */ 31 | public PreprocessedData preprocess( ChDataBuilder dataBuilder, Graph graphInput, DistanceType distanceType, long minimalShortcutId ); 32 | 33 | /** 34 | * Returns preprocessed data based on the implementation 35 | * 36 | * @param dataBuilder an instance of {@link ChDataBuilder} 37 | * @param graph an instance of {@link Graph} to calculate on 38 | * @param distanceType distance metric 39 | * @param minimalShortcutId minimal shortcut ID to be set for new shortcuts 40 | * => current max + 1 41 | * @param progressListener listener for progress update 42 | * @return an instance of {@link PreprocessedData} 43 | */ 44 | public PreprocessedData preprocess( ChDataBuilder dataBuilder, Graph graph, DistanceType distanceType, long minimalShortcutId, ProgressListener progressListener ); 45 | 46 | public void setNodeRecalculationStrategy( NodeRecalculationStrategy nodeRecalculationStrategy ); 47 | 48 | public void setEdgeDifferenceCalculator( EdgeDifferenceCalculator edgeDifferenceCalculator ); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/preprocessing/ch/calculators/BasicEdgeDifferenceCalculator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.preprocessing.ch.calculators; 7 | 8 | import cz.certicon.routing.application.algorithm.preprocessing.ch.EdgeDifferenceCalculator; 9 | 10 | /** 11 | * Basic implementation of the {@link EdgeDifferenceCalculator} interface. Uses 12 | * difference of the number of shortcuts and the degree of node. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public class BasicEdgeDifferenceCalculator implements EdgeDifferenceCalculator { 17 | 18 | @Override 19 | public int calculate( int contractedNode, int[] nodeDegrees, int node, int numberOfShortcuts ) { 20 | return numberOfShortcuts - nodeDegrees[node]; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/preprocessing/ch/calculators/SpatialHeuristicEdgeDifferenceCalculator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.preprocessing.ch.calculators; 7 | 8 | import cz.certicon.routing.application.algorithm.preprocessing.ch.EdgeDifferenceCalculator; 9 | import cz.certicon.routing.utils.EffectiveUtils; 10 | 11 | /** 12 | * Advanced implementation of the {@link EdgeDifferenceCalculator} interface. 13 | * Takes into account information about the already contracted nodes 14 | * (neighbors). 15 | * 16 | * @author Michael Blaha {@literal } 17 | */ 18 | public class SpatialHeuristicEdgeDifferenceCalculator implements EdgeDifferenceCalculator { 19 | 20 | private final int[] contractedNeighboursCountArray; 21 | private final int[] lastNodeContractedArray; 22 | 23 | // DEBUG 24 | // public ContractionHierarchiesPreprocessor preprocessor; 25 | public SpatialHeuristicEdgeDifferenceCalculator( int nodeCount ) { 26 | contractedNeighboursCountArray = new int[nodeCount]; 27 | lastNodeContractedArray = new int[nodeCount]; 28 | // EffectiveUtils.fillArray( contractedNeighboursCountArray, -1 ); 29 | EffectiveUtils.fillArray( lastNodeContractedArray, -1 ); 30 | } 31 | 32 | @Override 33 | public int calculate( int contractedNode, int[] nodeDegrees, int node, int numberOfShortcuts ) { 34 | if ( contractedNode != -1 ) { 35 | if ( contractedNode != lastNodeContractedArray[node] ) { 36 | contractedNeighboursCountArray[node]++; 37 | lastNodeContractedArray[node] = contractedNode; 38 | } 39 | } 40 | // if ( preprocessor != null && preprocessor.graph.getNodeOrigId( node ) == preprocessor.nodeOfInterest || preprocessor.nodeOfInterest < 0 ) { 41 | // preprocessor.out.println( "#" + preprocessor.graph.getNodeOrigId( node ) + " - calculate: " + contractedNeighboursCountArray[node] + " + " + numberOfShortcuts + " - " + nodeDegrees[node] ); 42 | // } 43 | return contractedNeighboursCountArray[node] + numberOfShortcuts - nodeDegrees[node]; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/application/algorithm/preprocessing/ch/strategies/LazyRecalculationStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.application.algorithm.preprocessing.ch.strategies; 7 | 8 | import cz.certicon.routing.application.algorithm.NodeDataStructure; 9 | import cz.certicon.routing.application.algorithm.preprocessing.ch.ContractionHierarchiesPreprocessor; 10 | import cz.certicon.routing.application.algorithm.preprocessing.ch.EdgeDifferenceCalculator; 11 | import cz.certicon.routing.application.algorithm.preprocessing.ch.NodeRecalculationStrategy; 12 | import cz.certicon.routing.application.algorithm.preprocessing.ch.calculators.BasicEdgeDifferenceCalculator; 13 | import cz.certicon.routing.model.entity.Graph; 14 | import gnu.trove.iterator.TIntIterator; 15 | 16 | /** 17 | * Lazy update implementation of the {@link NodeRecalculationStrategy} 18 | * interface. The node is recalculated on demand, then the evaluation repeats. 19 | * 20 | * @deprecated not working yet 21 | * 22 | * @author Michael Blaha {@literal } 23 | */ 24 | public class LazyRecalculationStrategy implements NodeRecalculationStrategy, TIntIterator { 25 | // DEBUG 26 | public ContractionHierarchiesPreprocessor preprocessor; 27 | 28 | private EdgeDifferenceCalculator edgeDifferenceCalculator = new BasicEdgeDifferenceCalculator(); 29 | 30 | private NodeDataStructure priorityQueue; 31 | private ContractionHierarchiesPreprocessor.ProcessingData data; 32 | private boolean calculate; 33 | 34 | @Override 35 | public TIntIterator recalculationIterator( Graph graph, ContractionHierarchiesPreprocessor.ProcessingData data, int contractedNode, NodeDataStructure priorityQueue ) { 36 | this.priorityQueue = priorityQueue; 37 | this.data = data; 38 | this.calculate = true; 39 | // return this; 40 | throw new UnsupportedOperationException( "Not supported yet. Does not work with the current concept." ); //To change body of generated methods, choose Tools | Templates. 41 | } 42 | 43 | @Override 44 | public void onShortcutsCalculated( Graph graph, int[] nodeDegrees, int node, NodeDataStructure priorityQueue, int shortcuts, int contractedNode ) { 45 | int ed = edgeDifferenceCalculator.calculate( contractedNode, nodeDegrees, node, shortcuts ); 46 | calculate = ( ed > priorityQueue.minValue() ); 47 | priorityQueue.add( node, ed ); 48 | } 49 | 50 | @Override 51 | public void setEdgeDifferenceCalculator( EdgeDifferenceCalculator edgeDifferenceCalculator ) { 52 | this.edgeDifferenceCalculator = edgeDifferenceCalculator; 53 | } 54 | 55 | @Override 56 | public EdgeDifferenceCalculator getEdgeDifferenceCalculator() { 57 | return edgeDifferenceCalculator; 58 | } 59 | 60 | @Override 61 | public int next() { 62 | return priorityQueue.extractMin(); 63 | } 64 | 65 | @Override 66 | public boolean hasNext() { 67 | return !priorityQueue.isEmpty() && calculate; 68 | } 69 | 70 | @Override 71 | public void remove() { 72 | throw new UnsupportedOperationException( "Not supported yet." ); //To change body of generated methods, choose Tools | Templates. 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/DataDestination.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | import java.io.IOException; 9 | import java.io.OutputStream; 10 | 11 | /** 12 | * The root interface for data export destination. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public interface DataDestination { 17 | 18 | /** 19 | * Opens the channel for writing into the destination. 20 | * 21 | * @return this instance 22 | * @throws IOException thrown when an error appears while opening 23 | */ 24 | public DataDestination open() throws IOException; 25 | 26 | /** 27 | * Writes data into the destination. 28 | * 29 | * @param str data to be written 30 | * @return this instance 31 | * @throws IOException thrown when an error appears while writing 32 | */ 33 | public DataDestination write( String str ) throws IOException; 34 | 35 | /** 36 | * Returns output stream of this destination 37 | * 38 | * @return an instance of {@link OutputStream} 39 | * @throws IOException thrown when an error appears while obtaining output stream 40 | */ 41 | public OutputStream getOutputStream() throws IOException; 42 | 43 | /** 44 | * Closing the channel. 45 | * 46 | * @return this instance 47 | * @throws IOException thrown when an error appears while closing 48 | */ 49 | public DataDestination close() throws IOException; 50 | 51 | /** 52 | * Flushes the data into the destination, clears the channel. 53 | * 54 | * @return this instance 55 | * @throws IOException thrown when an error appears while flushing 56 | */ 57 | public DataDestination flush() throws IOException; 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/DataSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | 11 | /** 12 | * The root interface for data source. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public interface DataSource { 17 | 18 | /** 19 | * Opens the channel for reading from the source. 20 | * 21 | * @return this instance 22 | * @throws IOException thrown when an error appears while opening 23 | */ 24 | public DataSource open() throws IOException; 25 | 26 | /** 27 | * Reads data from the source. 28 | * 29 | * @return next byte 30 | * @throws IOException thrown when an error appears while reading 31 | */ 32 | public int read() throws IOException; 33 | 34 | /** 35 | * Returns input stream of this source 36 | * 37 | * @return an instance of {@link InputStream} 38 | * @throws IOException thrown when an error appears while obtaining input stream 39 | */ 40 | public InputStream getInputStream() throws IOException; 41 | 42 | /** 43 | * Closing the channel. 44 | * 45 | * @return this instance 46 | * @throws IOException thrown when an error appears while closing 47 | */ 48 | public DataSource close() throws IOException; 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/Database.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | /** 9 | * A database interface 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public interface Database { 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/IoFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | /** 9 | * 10 | * @deprecated it does not make any sense to use this 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public interface IoFactory { 14 | 15 | public R createReader( DataSource dataSource ); 16 | 17 | public W createWriter( DataDestination dataDestination ); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/Reader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * A generic reader interface for additional consistency. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param additional data for the reader (if it requires any) 15 | * @param output of the reader 16 | */ 17 | public interface Reader { 18 | 19 | /** 20 | * Opens the reader for reading. 21 | * 22 | * @throws IOException exception when opening 23 | */ 24 | public void open() throws IOException; 25 | 26 | /** 27 | * Reads the input and returns the output 28 | * 29 | * @param in additional data 30 | * @return read output 31 | * @throws IOException exception when reading 32 | */ 33 | public Out read(In in) throws IOException; 34 | 35 | /** 36 | * Closes the reader. 37 | * 38 | * @throws IOException exception when closing 39 | */ 40 | public void close() throws IOException; 41 | 42 | /** 43 | * Returns true if the reader is open, false otherwise 44 | * 45 | * @return true or false 46 | */ 47 | public boolean isOpen(); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/TemporaryMemory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | /** 9 | * 10 | * @deprecated java osm parsing not supported anymore, use database or other external application 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public interface TemporaryMemory { 14 | 15 | /** 16 | * Returns {@link DataDestination} as a memory for runtime storage 17 | * 18 | * @return memory for runtime storage 19 | */ 20 | public DataDestination getMemoryAsDestination(); 21 | 22 | public DataSource getMemoryAsSource(); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/Writer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * A generic reader interface for additional consistency. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param class to be written 15 | */ 16 | public interface Writer { 17 | 18 | /** 19 | * Opens the writer for writing. 20 | * 21 | * @throws IOException exception when opening 22 | */ 23 | public void open() throws IOException; 24 | 25 | /** 26 | * Closes the writer. 27 | * 28 | * @throws IOException exception when closing 29 | */ 30 | public void close() throws IOException; 31 | 32 | /** 33 | * Reads the input and returns the output 34 | * 35 | * @param out output to be written 36 | * @throws IOException exception when writing 37 | */ 38 | public void write( Out out ) throws IOException; 39 | 40 | /** 41 | * Returns true if the writer is open, false otherwise 42 | * 43 | * @return true or false 44 | */ 45 | public boolean isOpen(); 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/FileDestination.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic; 7 | 8 | import cz.certicon.routing.data.DataDestination; 9 | import java.io.BufferedOutputStream; 10 | import java.io.File; 11 | import java.io.FileOutputStream; 12 | import java.io.IOException; 13 | import java.io.OutputStream; 14 | import java.io.PrintWriter; 15 | 16 | /** 17 | * An implementation of {@link DataDestination} using a {@link File} 18 | * 19 | * @author Michael Blaha {@literal } 20 | */ 21 | public class FileDestination implements DataDestination { 22 | 23 | private final File file; 24 | private PrintWriter writer; 25 | 26 | public FileDestination( File file ) { 27 | this.file = file; 28 | } 29 | 30 | @Override 31 | public DataDestination open() throws IOException { 32 | OutputStream os = new BufferedOutputStream( new FileOutputStream( file ) ); 33 | writer = new PrintWriter( os ); 34 | return this; 35 | } 36 | 37 | @Override 38 | public DataDestination write( String str ) throws IOException { 39 | writer.print( str ); 40 | return this; 41 | } 42 | 43 | @Override 44 | public DataDestination close() throws IOException { 45 | writer.close(); 46 | return this; 47 | } 48 | 49 | @Override 50 | public DataDestination flush() throws IOException { 51 | writer.flush(); 52 | return this; 53 | } 54 | 55 | @Override 56 | public OutputStream getOutputStream() throws IOException { 57 | return new FileOutputStream( file ); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/FileSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic; 7 | 8 | import cz.certicon.routing.data.DataSource; 9 | import java.io.File; 10 | import java.io.FileInputStream; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.util.Scanner; 14 | 15 | /** 16 | * An implementation of {@link DataSource} using a {@link File} 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public class FileSource implements DataSource { 21 | 22 | private final File file; 23 | private Scanner scanner; 24 | 25 | public FileSource( File file ) { 26 | this.file = file; 27 | } 28 | 29 | @Override 30 | public DataSource open() throws IOException { 31 | scanner = new Scanner( file ); 32 | return this; 33 | } 34 | 35 | @Override 36 | public int read() throws IOException { 37 | return scanner.nextByte(); 38 | } 39 | 40 | @Override 41 | public InputStream getInputStream() throws IOException { 42 | return new FileInputStream( file ); 43 | } 44 | 45 | @Override 46 | public DataSource close() throws IOException { 47 | scanner.close(); 48 | return this; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/FileTemporaryMemory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic; 7 | 8 | import cz.certicon.routing.data.DataDestination; 9 | import cz.certicon.routing.data.DataSource; 10 | import cz.certicon.routing.data.TemporaryMemory; 11 | import java.io.File; 12 | 13 | /** 14 | * An implementation of {@link TemporaryMemory} storing data in the {@link File} 15 | * 16 | * @author Michael Blaha {@literal } 17 | */ 18 | public class FileTemporaryMemory implements TemporaryMemory { 19 | 20 | private final File file; 21 | 22 | public FileTemporaryMemory( File file ) { 23 | this.file = file; 24 | } 25 | 26 | @Override 27 | public DataDestination getMemoryAsDestination() { 28 | return new FileDestination( file ); 29 | } 30 | 31 | @Override 32 | public DataSource getMemoryAsSource() { 33 | return new FileSource( file ); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/StringDestination.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic; 7 | 8 | import cz.certicon.routing.data.DataDestination; 9 | import java.io.ByteArrayOutputStream; 10 | import java.io.IOException; 11 | import java.io.OutputStream; 12 | 13 | /** 14 | * An implementation of {@link DataDestination} using a {@link String}. Obtain result via the {@link #getResult() getResult} method. 15 | * 16 | * @author Michael Blaha {@literal } 17 | */ 18 | public class StringDestination implements DataDestination { 19 | 20 | private final StringBuilder sb = new StringBuilder(); 21 | 22 | @Override 23 | public DataDestination open() throws IOException { 24 | sb.delete( 0, sb.length() ); 25 | return this; 26 | } 27 | 28 | @Override 29 | public DataDestination write( String str ) throws IOException { 30 | sb.append( str ); 31 | return this; 32 | } 33 | 34 | @Override 35 | public DataDestination close() throws IOException { 36 | return this; 37 | } 38 | 39 | /** 40 | * Returns the current content of this {@link DataDestination} 41 | * @return {@link String} representation of the content 42 | */ 43 | public String getResult(){ 44 | return sb.toString(); 45 | } 46 | 47 | @Override 48 | public DataDestination flush() throws IOException { 49 | sb.delete( 0, sb.length() ); 50 | return this; 51 | } 52 | 53 | @Override 54 | public OutputStream getOutputStream() throws IOException { 55 | return new StringOutputStream(); 56 | } 57 | 58 | private class StringOutputStream extends OutputStream { 59 | 60 | ByteArrayOutputStream os = new ByteArrayOutputStream(); 61 | 62 | @Override 63 | public void write( int b ) throws IOException { 64 | os.write( b ); 65 | } 66 | 67 | @Override 68 | public void close() throws IOException { 69 | super.close(); 70 | sb.append( new String(os.toByteArray(), "UTF-8")); 71 | } 72 | 73 | @Override 74 | public void flush() throws IOException { 75 | super.flush(); 76 | sb.append( new String(os.toByteArray(), "UTF-8")); 77 | } 78 | 79 | 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/database/AbstractEmbeddedDatabase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic.database; 7 | 8 | import cz.certicon.routing.data.Reader; 9 | import cz.certicon.routing.data.Writer; 10 | import java.sql.Connection; 11 | import java.sql.DriverManager; 12 | import java.sql.SQLException; 13 | import java.util.Properties; 14 | 15 | /** 16 | * An abstract implementation of the {@link Reader}/{@link Writer} interfaces 17 | * for the embedded database access. Encapsulates database access (connection creating), 18 | * controls the state before reading/writing and opens the connection if 19 | * necessary. 20 | * 21 | * @author Michael Blaha {@literal } 22 | * @param entity to be read or written 23 | * @param input data for the read 24 | */ 25 | public abstract class AbstractEmbeddedDatabase extends AbstractDatabase { 26 | 27 | public AbstractEmbeddedDatabase( Properties connectionProperties ) { 28 | super( connectionProperties ); 29 | } 30 | 31 | @Override 32 | protected Connection createConnection( Properties properties ) throws ClassNotFoundException, SQLException { 33 | Class.forName( getDriverClass( properties ) ); 34 | return DriverManager.getConnection( getDatabaseUrl( properties ), properties ); 35 | } 36 | /** 37 | * Returns 'driver' value of the given properties. Overwrite if necessary. 38 | * 39 | * @param properties containing driver class property 40 | * @return driver class 41 | */ 42 | protected String getDriverClass( Properties properties ) { 43 | return properties.getProperty( "driver" ); 44 | } 45 | 46 | /** 47 | * Returns 'url' value of the given properties. Overwrite if necessary. 48 | * 49 | * @param properties containing url property 50 | * @return database url 51 | */ 52 | protected String getDatabaseUrl( Properties properties ) { 53 | return properties.getProperty( "url" ); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/database/AbstractServerDatabase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic.database; 7 | 8 | import cz.certicon.routing.data.Reader; 9 | import cz.certicon.routing.data.Writer; 10 | import java.sql.Connection; 11 | import java.sql.DriverManager; 12 | import java.sql.SQLException; 13 | import java.util.Properties; 14 | 15 | /** 16 | * An abstract implementation of the {@link Reader}/{@link Writer} interfaces 17 | * for the server database access. Encapsulates database access (connection creating), 18 | * controls the state before reading/writing and opens the connection if 19 | * necessary. 20 | * 21 | * @author Michael Blaha {@literal } 22 | * @param entity to be read or written 23 | * @param input data for the read 24 | */ 25 | public abstract class AbstractServerDatabase extends AbstractDatabase { 26 | 27 | public AbstractServerDatabase( Properties connectionProperties ) { 28 | super( connectionProperties ); 29 | } 30 | 31 | @Override 32 | protected Connection createConnection( Properties properties ) throws ClassNotFoundException, SQLException { 33 | Class.forName( getDriverClass( properties ) ); 34 | return DriverManager.getConnection( getDatabaseUrl( properties ), getUsername( properties ), getPassword( properties ) ); 35 | } 36 | 37 | /** 38 | * Returns 'driver' value of the given properties. Overwrite if necessary. 39 | * 40 | * @param properties containing driver class property 41 | * @return driver class 42 | */ 43 | protected String getDriverClass( Properties properties ) { 44 | return properties.getProperty( "driver" ); 45 | } 46 | 47 | /** 48 | * Returns 'url' value of the given properties. Overwrite if necessary. 49 | * 50 | * @param properties containing url property 51 | * @return database url 52 | */ 53 | protected String getDatabaseUrl( Properties properties ) { 54 | return properties.getProperty( "url" ); 55 | } 56 | 57 | /** 58 | * Returns 'user' value of the given properties. Overwrite if necessary. 59 | * 60 | * @param properties containing user property 61 | * @return database username 62 | */ 63 | protected String getUsername( Properties properties ) { 64 | return properties.getProperty( "user" ); 65 | } 66 | 67 | /** 68 | * Returns 'password' value of the given properties. Overwrite if necessary. 69 | * 70 | * @param properties containing password property 71 | * @return database password 72 | */ 73 | protected String getPassword( Properties properties ) { 74 | return properties.getProperty( "password" ); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/database/impl/AbstractSqliteDatabase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic.database.impl; 7 | 8 | import cz.certicon.routing.data.basic.database.AbstractEmbeddedDatabase; 9 | import java.io.IOException; 10 | import java.sql.SQLException; 11 | import java.util.Map; 12 | import java.util.Properties; 13 | import org.sqlite.SQLiteConfig; 14 | 15 | /** 16 | * Abstract extension of the embedded database focused on the SQLite database. 17 | * Also adds support for the SpatiaLite extension - the provided Properties must 18 | * contain path to the spatialite library. 19 | * 20 | * @author Michael Blaha {@literal } 21 | * @param entity to be read or written 22 | * @param 23 | */ 24 | public abstract class AbstractSqliteDatabase extends AbstractEmbeddedDatabase { 25 | 26 | private String spatialitePath; 27 | 28 | /** 29 | * Creates an instance of this class. 30 | * 31 | * @param connectionProperties must contain properties (more info in 32 | * {@link AbstractEmbeddedDatabase}) and a path to the spatialite library 33 | * under key: spatialite_path 34 | */ 35 | public AbstractSqliteDatabase( Properties connectionProperties ) { 36 | super( connectionProperties ); 37 | SQLiteConfig config = new SQLiteConfig(); 38 | config.enableLoadExtension( true ); 39 | for ( Map.Entry entry : config.toProperties().entrySet() ) { 40 | connectionProperties.put( entry.getKey(), entry.getValue() ); 41 | } 42 | this.spatialitePath = connectionProperties.getProperty( "spatialite_path" ); 43 | } 44 | 45 | @Override 46 | public void open() throws IOException { 47 | super.open(); 48 | try { 49 | getStatement().execute( "SELECT load_extension('" + spatialitePath + "')" ); 50 | // this.libspatialitePath = libspatialitePath; 51 | } catch ( SQLException ex ) { 52 | throw new IOException( ex ); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/database/impl/StringSqliteReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic.database.impl; 7 | 8 | import java.io.IOException; 9 | import java.sql.ResultSet; 10 | import java.sql.SQLException; 11 | import java.util.Properties; 12 | 13 | /** 14 | * An extension to the {@link StringSqliteReader}, which is read-only and 15 | * returns {@link ResultSet} based on the given query (String). 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class StringSqliteReader { 20 | 21 | private final AbstractSqliteDatabase database; 22 | 23 | public StringSqliteReader( Properties connectionProperties ) { 24 | this.database = new AbstractSqliteDatabase( connectionProperties ) { 25 | @Override 26 | protected ResultSet checkedRead( String in ) throws SQLException { 27 | return getStatement().executeQuery( in ); 28 | } 29 | 30 | @Override 31 | protected void checkedWrite( ResultSet in ) throws SQLException { 32 | throw new UnsupportedOperationException( "Not supported yet." ); //To change body of generated methods, choose Tools | Templates. 33 | } 34 | }; 35 | } 36 | 37 | /** 38 | * Returns {@link ResultSet} based on the given query. 39 | * 40 | * @param sql SQL query 41 | * @return result set 42 | * @throws IOException thrown when an SQL or IO exception appears 43 | */ 44 | public ResultSet read( String sql ) throws IOException { 45 | return database.read( sql ); 46 | } 47 | 48 | /** 49 | * Closes the database connection 50 | * 51 | * @throws IOException thrown when an SQL or IO exception appears 52 | */ 53 | public void close() throws IOException { 54 | database.close(); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/xml/AbstractXmlReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic.xml; 7 | 8 | import cz.certicon.routing.data.DataSource; 9 | import cz.certicon.routing.data.Reader; 10 | import java.io.IOException; 11 | 12 | /** 13 | * An abstract implementation of the Reader interfaces for the XML. Encapsulates access, controls the state before reading and opens the stream if necessary. 14 | * 15 | * @author Michael Blaha {@literal } 16 | * @param additional data 17 | * @param actual output (of reading) 18 | */ 19 | public abstract class AbstractXmlReader implements Reader { 20 | 21 | private final DataSource source; 22 | private boolean isOpen = false; 23 | 24 | public AbstractXmlReader( DataSource source ) { 25 | this.source = source; 26 | } 27 | 28 | @Override 29 | public void open() throws IOException { 30 | this.isOpen = true; 31 | } 32 | 33 | @Override 34 | public Out read( In in ) throws IOException { 35 | if(!isOpen){ 36 | open(); 37 | } 38 | return checkedRead( in ); 39 | } 40 | 41 | /** 42 | * Checks the state before reading and opens the source if necessary. 43 | * 44 | * @param in additional data (passed) 45 | * @return the read output 46 | * @throws IOException reading exception 47 | */ 48 | protected abstract Out checkedRead(In in) throws IOException; 49 | 50 | @Override 51 | public void close() throws IOException { 52 | if(isOpen){ 53 | isOpen = false; 54 | } 55 | } 56 | 57 | protected DataSource getDataSource(){ 58 | return source; 59 | } 60 | 61 | @Override 62 | public boolean isOpen() { 63 | return isOpen; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/basic/xml/AbstractXmlWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.basic.xml; 7 | 8 | import cz.certicon.routing.data.DataDestination; 9 | import cz.certicon.routing.data.Writer; 10 | import java.io.IOException; 11 | import java.io.OutputStream; 12 | import javax.xml.stream.XMLOutputFactory; 13 | import javax.xml.stream.XMLStreamException; 14 | import javax.xml.stream.XMLStreamWriter; 15 | 16 | /** 17 | * An abstract implementation of the {@link Writer} interfaces for the XML. Encapsulates access, controls the state before writing and opens the stream if necessary. 18 | * 19 | * @author Michael Blaha {@literal } 20 | * @param actual input (to be written) 21 | */ 22 | public abstract class AbstractXmlWriter implements Writer { 23 | 24 | private static final String ROOT = "root"; 25 | 26 | private final DataDestination destination; 27 | private OutputStream output; 28 | private XMLStreamWriter writer; 29 | private boolean isOpen = false; 30 | 31 | public AbstractXmlWriter( DataDestination destination ) { 32 | this.destination = destination; 33 | } 34 | 35 | @Override 36 | public void open() throws IOException { 37 | output = destination.getOutputStream(); 38 | XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance(); 39 | try { 40 | writer = xmlOutFact.createXMLStreamWriter( output ); 41 | writer.writeStartDocument(); 42 | writer.writeStartElement( ROOT ); 43 | } catch ( XMLStreamException ex ) { 44 | throw new IOException( ex ); 45 | } 46 | isOpen = true; 47 | } 48 | 49 | @Override 50 | public void close() throws IOException { 51 | if ( isOpen ) { 52 | try { 53 | writer.writeEndElement(); 54 | writer.writeEndDocument(); 55 | writer.close(); 56 | } catch ( XMLStreamException ex ) { 57 | throw new IOException( ex ); 58 | } 59 | output.close(); 60 | isOpen = false; 61 | } 62 | } 63 | 64 | protected XMLStreamWriter getWriter() { 65 | return writer; 66 | } 67 | 68 | @Override 69 | public void write( Out out ) throws IOException { 70 | if ( !isOpen ) { 71 | open(); 72 | } 73 | checkedWrite( out ); 74 | } 75 | 76 | /** 77 | * Checks the state before writing and opens the source if necessary. 78 | * 79 | * @param out output to be written 80 | * @throws IOException reading exception 81 | */ 82 | abstract protected void checkedWrite( Out out ) throws IOException; 83 | 84 | @Override 85 | public boolean isOpen() { 86 | return isOpen; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/ch/ContractionHierarchiesDataRW.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.ch; 7 | 8 | import cz.certicon.routing.application.algorithm.preprocessing.ch.Preprocessor; 9 | import cz.certicon.routing.model.entity.Graph; 10 | import cz.certicon.routing.model.entity.ch.ChDataFactory; 11 | import java.io.IOException; 12 | 13 | /** 14 | * Read/write interface for the data of the ContractionHierarchies algorithm. It 15 | * is type-independent as the data class is determined by the provided 16 | * factories. 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public interface ContractionHierarchiesDataRW { 21 | 22 | /** 23 | * Reads the CH data without a preprocessing option - throws Exception 24 | * instead. Use the 25 | * {@link #read(cz.certicon.routing.model.entity.ch.ChDataFactory, cz.certicon.routing.model.entity.Graph, cz.certicon.routing.application.algorithm.preprocessing.ch.Preprocessor) read(factory, graph, preprocessor)} 26 | * instead if you need the preprocessing option. 27 | * 28 | * 29 | * @param CH data type 30 | * @param chDataFactory factory for the CH data builder and extractor 31 | * @return CH data 32 | * @throws NotPreprocessedException thrown when the data are not present in 33 | * the given data source 34 | * @throws IOException thrown when an IO exception occurs 35 | */ 36 | public T read( ChDataFactory chDataFactory ) throws NotPreprocessedException, IOException; 37 | 38 | /** 39 | * Reads the CH data. If the data are not present, the preprocessing is 40 | * performed on the data source, which is therefore updated with the 41 | * preprocessed data. The preprocessing can take a long time to compute. 42 | * 43 | * @param CH data type 44 | * @param chDataFactory factory for the CH data builder and extractor 45 | * @param graph an instance of {@link Graph} to be preprocessed upon 46 | * @param preprocessor the preprocessor implementation 47 | * @return CH data 48 | * @throws IOException thrown when an IO exception occurs 49 | */ 50 | public T read( ChDataFactory chDataFactory, Graph graph, Preprocessor preprocessor ) throws IOException; 51 | 52 | /** 53 | * Writes the CH data into the data target 54 | * 55 | * @param CH data type 56 | * @param chDataFactory factory for the CH data builder and extractor 57 | * @param entity CH data 58 | * @throws IOException thrown when an IO exception occurs 59 | */ 60 | public void write( ChDataFactory chDataFactory, T entity ) throws IOException; 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/ch/NotPreprocessedException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.ch; 7 | 8 | /** 9 | * This exception is thrown when a read on CH is performed, but the data are not 10 | * present and the preprocessor is not provided. Please, use the preprocessor if 11 | * you want to prepare the data. Do not use the preprocessor, if the data should 12 | * already be present - then this is a valid error. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public class NotPreprocessedException extends Exception { 17 | 18 | public NotPreprocessedException() { 19 | } 20 | 21 | public NotPreprocessedException( String message ) { 22 | super( message ); 23 | } 24 | 25 | public NotPreprocessedException( String message, Throwable cause ) { 26 | super( message, cause ); 27 | } 28 | 29 | public NotPreprocessedException( Throwable cause ) { 30 | super( cause ); 31 | } 32 | 33 | public NotPreprocessedException( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace ) { 34 | super( message, cause, enableSuppression, writableStackTrace ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/coordinates/CoordinateReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.coordinates; 7 | 8 | import cz.certicon.routing.model.entity.CoordinateSetBuilderFactory; 9 | import java.io.IOException; 10 | import java.util.Iterator; 11 | 12 | /** 13 | * Read-only interface for the edge coordinates 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public interface CoordinateReader { 18 | 19 | /** 20 | * Reads coordinates based on the given edge iterator. Creates a result 21 | * using the {@link CoordinateSetBuilderFactory}. 22 | * 23 | * @param coordinates representation 24 | * @param coordinateSetBuilderFactory factory providing builder for the 25 | * coordinates representation 26 | * @param edgeIds iterator providing a sequence of edge ids as they go in 27 | * the path 28 | * @return coordinates 29 | * @throws IOException thrown when an IO exception occurs 30 | */ 31 | public T readCoordinates( CoordinateSetBuilderFactory coordinateSetBuilderFactory, Iterator edgeIds ) throws IOException; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/coordinates/sqlite/SqliteCoordinateReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.coordinates.sqlite; 7 | 8 | import cz.certicon.routing.data.basic.database.impl.StringSqliteReader; 9 | import cz.certicon.routing.data.coordinates.CoordinateReader; 10 | import cz.certicon.routing.model.entity.CoordinateSetBuilder; 11 | import cz.certicon.routing.model.entity.CoordinateSetBuilderFactory; 12 | import cz.certicon.routing.model.entity.Coordinate; 13 | import cz.certicon.routing.utils.GeometryUtils; 14 | import java.io.IOException; 15 | import java.sql.ResultSet; 16 | import java.sql.SQLException; 17 | import java.util.Iterator; 18 | import java.util.List; 19 | import java.util.Properties; 20 | 21 | /** 22 | * An implementation of the {@link CoordinateReader} interface based on the 23 | * SQLite database. 24 | * 25 | * @author Michael Blaha {@literal } 26 | */ 27 | public class SqliteCoordinateReader implements CoordinateReader { 28 | 29 | private final StringSqliteReader reader; 30 | 31 | /** 32 | * See {@link AbstractSqliteDatabase} for further details. 33 | * 34 | * @param connectionProperties use SQLite database properties. 35 | */ 36 | public SqliteCoordinateReader( Properties connectionProperties ) { 37 | this.reader = new StringSqliteReader( connectionProperties ); 38 | } 39 | 40 | // TODO more memory-efficient to search only for a set of data_id, not edge_id, however it requires building sets and maps and more complex operations 41 | @Override 42 | public T readCoordinates( CoordinateSetBuilderFactory coordinateSetBuilderFactory, Iterator edgeIds ) throws IOException { 43 | CoordinateSetBuilder coordinateSetBuilder = coordinateSetBuilderFactory.createCoordinateSetBuilder(); 44 | ResultSet rs; 45 | StringBuilder inArray = new StringBuilder(); 46 | while ( edgeIds.hasNext() ) { 47 | inArray.append( edgeIds.next() ).append( "," ); 48 | } 49 | if ( inArray.length() > 0 ) { 50 | try { 51 | inArray.delete( inArray.length() - 1, inArray.length() ); 52 | rs = reader.read( "SELECT e.id AS edge_id, ST_AsText(d.geom) AS linestring " 53 | + "FROM edges e " 54 | + "JOIN edges_data d " 55 | + "ON e.id = d.data_id " 56 | + "WHERE e.id IN (" 57 | + inArray.toString() 58 | + ")" ); 59 | int idColumnIdx = rs.findColumn( "edge_id" ); 60 | int linestringColumnIdx = rs.findColumn( "linestring" ); 61 | while ( rs.next() ) { 62 | long id = rs.getLong( idColumnIdx ); 63 | List coordinates = GeometryUtils.toCoordinatesFromWktLinestring( rs.getString( linestringColumnIdx ) ); 64 | coordinateSetBuilder.addCoordinates( id, coordinates ); 65 | } 66 | } catch ( SQLException ex ) { 67 | throw new IOException( ex ); 68 | } 69 | } 70 | reader.close(); 71 | return coordinateSetBuilder.build(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/graph/GraphReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.graph; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.entity.GraphBuilderFactory; 10 | import java.io.IOException; 11 | 12 | /** 13 | * Read-only interface for the graph 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public interface GraphReader { 18 | 19 | /** 20 | * Reads the graph based on the given distance type (metric). Creates a 21 | * result using a builder provided by the {@link GraphBuilderFactory}. 22 | * 23 | * @param graph type 24 | * @param GraphBuilderFactory factory providing builder for the graph 25 | * @param distanceType the metric 26 | * @return graph 27 | * @throws IOException thrown when an IO exception occurs 28 | */ 29 | public T readGraph( GraphBuilderFactory GraphBuilderFactory, DistanceType distanceType ) throws IOException; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/nodesearch/EvaluableOnlyException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.nodesearch; 7 | 8 | import cz.certicon.routing.model.entity.Coordinate; 9 | 10 | /** 11 | * Exception thrown when the two coordinates map to a single edge, then routing 12 | * is pointless and only a simple evaluation is necessary. This exception 13 | * therefore provides basic data about the situation for the application to 14 | * solve. This is not a critical exception - it can be solved in runtime. 15 | * 16 | * @author Michael Blaha {@literal } 17 | */ 18 | public class EvaluableOnlyException extends Exception { 19 | 20 | private final long edgeId; 21 | private final Coordinate source; 22 | private final Coordinate target; 23 | 24 | public EvaluableOnlyException( long edgeId, Coordinate source, Coordinate target ) { 25 | this.edgeId = edgeId; 26 | this.source = source; 27 | this.target = target; 28 | } 29 | 30 | public long getEdgeId() { 31 | return edgeId; 32 | } 33 | 34 | public Coordinate getSource() { 35 | return source; 36 | } 37 | 38 | public Coordinate getTarget() { 39 | return target; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/nodesearch/NodeSearcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.nodesearch; 7 | 8 | import cz.certicon.routing.model.entity.Coordinate; 9 | import cz.certicon.routing.model.entity.NodeSetBuilderFactory; 10 | import java.io.IOException; 11 | 12 | /** 13 | * An interface defining the search method for closest nodes to the given 14 | * coordinates. The distance is measured via distance to edge and then the edge 15 | * nodes are considered as sources/targets (edge target for source, edge source 16 | * for target). 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public interface NodeSearcher { 21 | 22 | /** 23 | * Finds the closest nodes to the given coordinates, based on the edge to 24 | * node distance. 25 | * 26 | * @param closest nodes structure type 27 | * @param nodeSetBuilderFactory factory providing a builder for the closest 28 | * nodes structure 29 | * @param source coordinates of source 30 | * @param target coordinates of target 31 | * @return closest nodes structure 32 | * @throws IOException thrown when an IO exception occurs 33 | * @throws EvaluableOnlyException thrown when the closest edge for the 34 | * source is the same as for the target => only simple calculation is 35 | * required then instead of complex routing 36 | */ 37 | public T findClosestNodes( NodeSetBuilderFactory nodeSetBuilderFactory, Coordinate source, Coordinate target ) throws IOException, EvaluableOnlyException; 38 | 39 | public static enum SearchFor { 40 | SOURCE, TARGET; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/data/path/PathReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.data.path; 7 | 8 | import cz.certicon.routing.application.algorithm.Route; 9 | import cz.certicon.routing.model.entity.PathBuilder; 10 | import cz.certicon.routing.model.entity.Coordinate; 11 | import java.io.IOException; 12 | 13 | /** 14 | * An interface defining a functionality for reading path data based on given 15 | * route or other data constructed by the algorithm. 16 | * 17 | * @author Michael Blaha {@literal } 18 | * @param graph type 19 | */ 20 | public interface PathReader { 21 | 22 | /** 23 | * Reads all the necessary data for displaying the route (geometry) and its 24 | * length or time or other metrics in a form of path object T. 25 | * 26 | * @param path type 27 | * @param pathBuilder path builder of T 28 | * @param graph graph 29 | * @param route result of the routing algorithm 30 | * @param origSource original coordinates of the source point 31 | * @param origTarget original coordinates of the target point 32 | * @return path containing all the required data 33 | * @throws IOException thrown when an IO exception occurs 34 | */ 35 | public T readPath( PathBuilder pathBuilder, G graph, Route route, Coordinate origSource, Coordinate origTarget ) throws IOException; 36 | 37 | /** 38 | * Reads all the necessary data for displaying the route (geometry) and its 39 | * length or time or other metrics in a form of path object T. 40 | * 41 | * @param path type 42 | * @param pathBuilder path builder of T 43 | * @param graph graph 44 | * @param edgeId id of the edge which both the source and target map to (the 45 | * closest to both) 46 | * @param origSource original coordinates of the source point 47 | * @param origTarget original coordinates of the target point 48 | * @return path containing all the required data 49 | * @throws IOException thrown when an IO exception occurs 50 | */ 51 | public T readPath( PathBuilder pathBuilder, G graph, long edgeId, Coordinate origSource, Coordinate origTarget ) throws IOException; 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/basic/Length.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | import java.util.Objects; 9 | 10 | /** 11 | * Class representing the length of something. It supports unit conversion, 12 | * formatting and so on. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public class Length { 17 | 18 | private final LengthUnits lengthUnits; 19 | private final long nanometers; 20 | 21 | /** 22 | * Creates an instance via an amount and units 23 | * 24 | * @param lengthUnits the length units in which the length is provided 25 | * @param length actual value 26 | */ 27 | public Length( LengthUnits lengthUnits, long length ) { 28 | this.lengthUnits = lengthUnits; 29 | this.nanometers = lengthUnits.toNano( length ); 30 | } 31 | 32 | /** 33 | * Returns current units 34 | * 35 | * @return current units 36 | */ 37 | public LengthUnits getLengthUnits() { 38 | return lengthUnits; 39 | } 40 | 41 | /** 42 | * Returns length in nanometers 43 | * 44 | * @return length in nanometers 45 | */ 46 | public long getNanometers() { 47 | return nanometers; 48 | } 49 | 50 | /** 51 | * Returns length in the current units 52 | * 53 | * @return length in the current units 54 | */ 55 | public long getLength() { 56 | return lengthUnits.fromNano( nanometers ); 57 | } 58 | 59 | /** 60 | * Returns length in the provided units 61 | * 62 | * @param lengthUnits provided units 63 | * @return length in the provided units 64 | */ 65 | public long getLength( LengthUnits lengthUnits ) { 66 | return lengthUnits.fromNano( nanometers ); 67 | } 68 | 69 | /** 70 | * Returns string representing the length in the provided units 71 | * 72 | * @param lengthUnits provided units 73 | * @return string in format "%d %s", length, unit 74 | */ 75 | public String toString( LengthUnits lengthUnits ) { 76 | return getLength( lengthUnits ) + " " + lengthUnits.getUnit(); 77 | } 78 | 79 | /** 80 | * Returns string representation of the current units 81 | * 82 | * @return string representation of the current units 83 | */ 84 | public String getUnit() { 85 | return lengthUnits.getUnit(); 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return "" + getLength(); 91 | } 92 | 93 | @Override 94 | public int hashCode() { 95 | int hash = 5; 96 | hash = 97 * hash + Objects.hashCode( this.lengthUnits ); 97 | hash = 97 * hash + (int) ( this.nanometers ^ ( this.nanometers >>> 32 ) ); 98 | return hash; 99 | } 100 | 101 | @Override 102 | public boolean equals( Object obj ) { 103 | if ( this == obj ) { 104 | return true; 105 | } 106 | if ( obj == null ) { 107 | return false; 108 | } 109 | if ( getClass() != obj.getClass() ) { 110 | return false; 111 | } 112 | final Length other = (Length) obj; 113 | if ( this.nanometers != other.nanometers ) { 114 | return false; 115 | } 116 | if ( this.lengthUnits != other.lengthUnits ) { 117 | return false; 118 | } 119 | return true; 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/basic/LengthUnits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | /** 9 | * Enumeration representing the possible length units. 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public enum LengthUnits { 14 | NANOMETERS( 1, "nm" ), MICROMETERS( NANOMETERS.getDivisor() * 1000, "mcm" ), MILLIMERERS( MICROMETERS.getDivisor() * 1000, "mm" ), METERS( MILLIMERERS.getDivisor() * 1000, "m" ), KILOMETERS( METERS.getDivisor() * 1000, "km" ); 15 | 16 | private final long nanoDivisor; 17 | private final String unit; 18 | 19 | private LengthUnits( long nanoDivisor, String unit ) { 20 | this.nanoDivisor = nanoDivisor; 21 | this.unit = unit; 22 | } 23 | 24 | private long getDivisor() { 25 | return nanoDivisor; 26 | } 27 | 28 | /** 29 | * Returns nanometers converted to these units. 30 | * 31 | * @param nanometers value in nanometers 32 | * @return converted value in these units 33 | */ 34 | public long fromNano( long nanometers ) { 35 | return nanometers / nanoDivisor; 36 | } 37 | 38 | /** 39 | * Returns nanometers converted from these units 40 | * 41 | * @param length value in these units 42 | * @return converted value in nanometers 43 | */ 44 | public long toNano( long length ) { 45 | return length * nanoDivisor; 46 | } 47 | 48 | /** 49 | * Returns string representation of these units 50 | * 51 | * @return string representation of these units 52 | */ 53 | public String getUnit() { 54 | return unit; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/basic/Pair.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | import java.util.Objects; 9 | 10 | /** 11 | * A generic container class for two objects. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param class of the first object 15 | * @param class of the second object 16 | * 17 | */ 18 | public class Pair { 19 | public final A a; 20 | public final B b; 21 | 22 | public Pair( A a, B b ) { 23 | this.a = a; 24 | this.b = b; 25 | } 26 | 27 | @Override 28 | public int hashCode() { 29 | int hash = 5; 30 | hash = 83 * hash + a.hashCode(); 31 | hash = 83 * hash + b.hashCode(); 32 | return hash; 33 | } 34 | 35 | @Override 36 | public boolean equals( Object obj ) { 37 | if ( this == obj ) { 38 | return true; 39 | } 40 | if ( obj == null ) { 41 | return false; 42 | } 43 | if ( getClass() != obj.getClass() ) { 44 | return false; 45 | } 46 | final Pair other = (Pair) obj; 47 | if ( !Objects.equals( this.a, other.a ) ) { 48 | return false; 49 | } 50 | if ( !Objects.equals( this.b, other.b ) ) { 51 | return false; 52 | } 53 | return true; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "Pair{" + "a=" + a + ", b=" + b + '}'; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/basic/Quaternion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | import java.util.Objects; 9 | 10 | /** 11 | * A generic container class for four objects. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param class of the first object 15 | * @param class of the second object 16 | * @param class of the third object 17 | * @param class of the fourth object 18 | * 19 | */ 20 | public class Quaternion extends Trinity { 21 | 22 | public final D d; 23 | 24 | public Quaternion( A a, B b, C c, D d ) { 25 | super( a, b, c ); 26 | this.d = d; 27 | } 28 | 29 | @Override 30 | public int hashCode() { 31 | int hash = super.hashCode(); 32 | hash = 41 * hash + d.hashCode(); 33 | return hash; 34 | } 35 | 36 | @Override 37 | public boolean equals( Object obj ) { 38 | if ( this == obj ) { 39 | return true; 40 | } 41 | if ( obj == null ) { 42 | return false; 43 | } 44 | if ( getClass() != obj.getClass() ) { 45 | return false; 46 | } 47 | final Quaternion other = (Quaternion) obj; 48 | if ( !Objects.equals( this.d, other.d ) ) { 49 | return false; 50 | } 51 | return true; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "Quaternion{" + "a=" + a + "b=" + b + "c=" + c + "d=" + d + '}'; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/basic/TimeUnits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | /** 9 | * Enumerate containing available time units. 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public enum TimeUnits { 14 | NANOSECONDS( 1, "ns" ), MICROSECONDS( NANOSECONDS.getDivisor() * 1000, "mcs" ), MILLISECONDS( MICROSECONDS.getDivisor() * 1000, "ms" ), SECONDS( MILLISECONDS.getDivisor() * 1000, "s" ), MINUTES( SECONDS.getDivisor() * 60, "min" ), HOURS( MINUTES.getDivisor() * 60, "h" ), DAYS( HOURS.getDivisor() * 24, "days" ); 15 | 16 | private final long nanoDivisor; 17 | private final String unit; 18 | 19 | private TimeUnits( long nanoDivisor, String unit ) { 20 | this.nanoDivisor = nanoDivisor; 21 | this.unit = unit; 22 | } 23 | 24 | private long getDivisor() { 25 | return nanoDivisor; 26 | } 27 | 28 | /** 29 | * Returns nanoseconds converted to these units. 30 | * 31 | * @param nanoseconds value in nanometers 32 | * @return converted value in these units 33 | */ 34 | public long fromNano( long nanoseconds ) { 35 | return nanoseconds / nanoDivisor; 36 | } 37 | 38 | /** 39 | * Returns nanoseconds converted from these units 40 | * 41 | * @param time value in these units 42 | * @return converted value in nanoseconds 43 | */ 44 | public long toNano( long time ) { 45 | return time * nanoDivisor; 46 | } 47 | 48 | /** 49 | * Returns string representation of these units 50 | * 51 | * @return string representation of these units 52 | */ 53 | public String getUnit() { 54 | return unit; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/basic/Trinity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | import java.util.Objects; 9 | 10 | /** 11 | * A generic container class for three objects. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param class of the first object 15 | * @param class of the second object 16 | * @param class of the third object 17 | * 18 | */ 19 | public class Trinity extends Pair { 20 | 21 | public final C c; 22 | 23 | public Trinity( A a, B b, C c ) { 24 | super( a, b ); 25 | this.c = c; 26 | } 27 | 28 | @Override 29 | public int hashCode() { 30 | int hash = super.hashCode(); 31 | hash = 53 * hash + Objects.hashCode( this.c ); 32 | return hash; 33 | } 34 | 35 | @Override 36 | public boolean equals( Object obj ) { 37 | if ( this == obj ) { 38 | return true; 39 | } 40 | if ( obj == null ) { 41 | return false; 42 | } 43 | if ( getClass() != obj.getClass() ) { 44 | return false; 45 | } 46 | final Trinity other = (Trinity) obj; 47 | if ( !Objects.equals( this.c, other.c ) ) { 48 | return false; 49 | } 50 | return true; 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return "Trinity{" + "a=" + a + "b=" + b + "c=" + c + '}'; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/CartesianCoords.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | /** 9 | * Class representation of Cartesian coordinates. 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public class CartesianCoords { 14 | 15 | private final double x; 16 | private final double y; 17 | private final double z; 18 | 19 | /** 20 | * Constructor 21 | * 22 | * @param x x 23 | * @param y y 24 | * @param z z 25 | */ 26 | public CartesianCoords( double x, double y, double z ) { 27 | this.x = x; 28 | this.y = y; 29 | this.z = z; 30 | } 31 | 32 | public double getX() { 33 | return x; 34 | } 35 | 36 | public double getY() { 37 | return y; 38 | } 39 | 40 | public double getZ() { 41 | return z; 42 | } 43 | 44 | public int getXAsInt() { 45 | return Math.round( (float) x ); 46 | } 47 | 48 | public int getYAsInt() { 49 | return Math.round( (float) y ); 50 | } 51 | 52 | public int getZAsInt() { 53 | return Math.round( (float) z ); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/Coordinate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import cz.certicon.routing.utils.DoubleComparator; 9 | 10 | /** 11 | * A class for representing geographical coordinates (latitude, longitude). When 12 | * comparing coordinates, it uses {@link DoubleComparator} with precision of 13 | * 10E-15. 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public class Coordinate { 18 | 19 | private static final double EPS = 10E-6; 20 | 21 | private final double latitude; 22 | private final double longitude; 23 | 24 | /** 25 | * Constructor 26 | * 27 | * @param latitude double representation of latitude 28 | * @param longitude double representation of longitude 29 | */ 30 | public Coordinate( double latitude, double longitude ) { 31 | this.latitude = latitude; 32 | this.longitude = longitude; 33 | } 34 | 35 | /** 36 | * Getter for latitude 37 | * 38 | * @return latitude double representation of latitude 39 | */ 40 | public double getLatitude() { 41 | return latitude; 42 | } 43 | 44 | /** 45 | * Getter for longitude 46 | * 47 | * @return longitude double representation of longitude 48 | */ 49 | public double getLongitude() { 50 | return longitude; 51 | } 52 | 53 | @Override 54 | public String toString() { 55 | return "Coordinates{" + "latitude=" + latitude + ", longitude=" + longitude + '}'; 56 | } 57 | 58 | @Override 59 | public int hashCode() { 60 | int hash = 7; 61 | hash = 97 * hash + (int) ( Double.doubleToLongBits( this.latitude ) ^ ( Double.doubleToLongBits( this.latitude ) >>> 32 ) ); 62 | hash = 97 * hash + (int) ( Double.doubleToLongBits( this.longitude ) ^ ( Double.doubleToLongBits( this.longitude ) >>> 32 ) ); 63 | return hash; 64 | } 65 | 66 | @Override 67 | public boolean equals( Object obj ) { 68 | if ( this == obj ) { 69 | return true; 70 | } 71 | if ( obj == null ) { 72 | return false; 73 | } 74 | if ( getClass() != obj.getClass() ) { 75 | return false; 76 | } 77 | final Coordinate other = (Coordinate) obj; 78 | if ( !DoubleComparator.isEqualTo( this.latitude, other.latitude, EPS ) ) { 79 | return false; 80 | } 81 | if ( !DoubleComparator.isEqualTo( this.longitude, other.longitude, EPS ) ) { 82 | return false; 83 | } 84 | return true; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/CoordinateSetBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Interface defining functionality for coordinate set builder 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param coordinate set type 15 | */ 16 | public interface CoordinateSetBuilder { 17 | 18 | /** 19 | * Add coordinates to the set 20 | * 21 | * @param edgeId id of the edge, whose geometry is being added 22 | * @param coordinates added geometry 23 | */ 24 | public void addCoordinates( long edgeId, List coordinates ); 25 | 26 | /** 27 | * Creates new coordinate set 28 | * 29 | * @return new coordinate set 30 | */ 31 | public T build(); 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/CoordinateSetBuilderFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | /** 9 | * Interface for coordinate set builder factory 10 | * 11 | * @author Michael Blaha {@literal } 12 | * @param coordinate set type 13 | */ 14 | public interface CoordinateSetBuilderFactory { 15 | 16 | /** 17 | * Creates new coordinate set builder 18 | * 19 | * @return new coordinate set builder 20 | */ 21 | public CoordinateSetBuilder createCoordinateSetBuilder(); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/DistanceType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import cz.certicon.routing.utils.CoordinateUtils; 9 | 10 | /** 11 | * Enumeration for available metrics. 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public enum DistanceType { 16 | 17 | TIME { 18 | @Override 19 | public double calculateDistance( double length, double speed ) { // m, km/s 20 | return 3.6 * length / speed; 21 | } 22 | 23 | @Override 24 | public double calculateApproximateDistance( double alat, double alon, double blat, double blon ) { 25 | return calculateDistance( CoordinateUtils.calculateDistance( alat, alon, blat, blon ), MAX_SPEED ); 26 | } 27 | }, LENGTH { 28 | @Override 29 | public double calculateDistance( double length, double speed ) { 30 | return length; 31 | } 32 | 33 | @Override 34 | public double calculateApproximateDistance( double alat, double alon, double blat, double blon ) { 35 | return CoordinateUtils.calculateDistance( alat, alon, blat, blon ); 36 | } 37 | }; 38 | 39 | private static final int MAX_SPEED = 130; 40 | 41 | /** 42 | * Calculates abstract distance from the given length and speed 43 | * 44 | * @param length length 45 | * @param speed speed 46 | * @return abstract distance 47 | */ 48 | public abstract double calculateDistance( double length, double speed ); 49 | 50 | /** 51 | * Calculates approximate abstract distance for the given coordinates 52 | * (between A and B) 53 | * 54 | * @param aLat latitude of the point A 55 | * @param aLon longitude of the point A 56 | * @param bLat latitude of the point B 57 | * @param bLon longitude of the point B 58 | * @return approximate abstract distance between A and B 59 | */ 60 | public abstract double calculateApproximateDistance( double aLat, double aLon, double bLat, double bLon ); 61 | 62 | /** 63 | * Returns integer representation of this distance type 64 | * 65 | * @return integer representation of this distance type 66 | */ 67 | public int toInt() { 68 | return toInt( this ); 69 | } 70 | 71 | /** 72 | * Converts the given distanceType to its integer representation 73 | * 74 | * @param distanceType distance type to be converted 75 | * @return given distanceType to its integer representation 76 | */ 77 | public static int toInt( DistanceType distanceType ) { 78 | switch ( distanceType ) { 79 | case LENGTH: 80 | return 1; 81 | case TIME: 82 | return 2; 83 | default: 84 | throw new AssertionError( "Unknown distance type: " + distanceType.name() ); 85 | } 86 | } 87 | 88 | /** 89 | * Converts the given integer representation to its distanceType 90 | * 91 | * @param n integer representation to be converted 92 | * @return given integer representation to its distanceType 93 | */ 94 | public static DistanceType fromInt( int n ) { 95 | switch ( n ) { 96 | case 1: 97 | return LENGTH; 98 | case 2: 99 | return TIME; 100 | default: 101 | throw new IllegalArgumentException( "Unknown distance type number: " + n ); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/GraphBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | /** 9 | * Builder for the graph. 10 | * 11 | * @author Michael Blaha {@literal } 12 | * @param Graph class 13 | */ 14 | public interface GraphBuilder { 15 | 16 | /** 17 | * Adds node to the graph 18 | * 19 | * @param id node's id 20 | * @param dataId id of the node's data 21 | * @param osmId original node id in OSM 22 | * @param latitude node's latitude 23 | * @param longitude node's longitude 24 | */ 25 | public void addNode( long id, long dataId, long osmId, double latitude, double longitude ); 26 | 27 | /** 28 | * Adds edge to the graph 29 | * 30 | * @param id edge's id 31 | * @param dataId id of the edge's data 32 | * @param osmId original edge's id in OSM 33 | * @param sourceId id of the source node 34 | * @param targetId id of the target node 35 | * @param length edge's length 36 | * @param speed edge's maximal allowed speed 37 | * @param isPaid true if the edge has somehow paid passage, false otherwise 38 | */ 39 | public void addEdge( long id, long dataId, long osmId, long sourceId, long targetId, double length, double speed, boolean isPaid ); 40 | 41 | /** 42 | * Builds and returns the complete graph 43 | * 44 | * @return complete graph 45 | */ 46 | public T build(); 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/GraphBuilderFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | /** 9 | * Interface for the graph builder factory 10 | * 11 | * @author Michael Blaha {@literal } 12 | * @param graph type 13 | */ 14 | public interface GraphBuilderFactory { 15 | 16 | /** 17 | * Creates and returns graph builder. 18 | * 19 | * @param nodeCount amount of nodes in the graph 20 | * @param edgeCount amount of edges in the graph 21 | * @return graph builder 22 | */ 23 | public GraphBuilder createGraphBuilder( int nodeCount, int edgeCount ); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/NodeSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import java.util.Iterator; 9 | import java.util.Map; 10 | 11 | /** 12 | * Interface representing the input set of nodes - closest to the starting 13 | * location and to the ending location. 14 | * 15 | * @author Michael Blaha {@literal } 16 | * @param graph type 17 | */ 18 | public interface NodeSet { 19 | 20 | /** 21 | * Adds given edge and node to the given category (source or target) with 22 | * the given distance (distance of the original location to the end of the 23 | * given edge (to the given node)). 24 | * 25 | * @param nodeCategory category to which this shall be added 26 | * @param edgeId edge's global id 27 | * @param nodeId node's global id 28 | * @param distance distance in meters from node to the original location (on 29 | * the edge) 30 | */ 31 | public void put( NodeCategory nodeCategory, long edgeId, long nodeId, float distance ); 32 | 33 | /** 34 | * Returns iterator over all the entries for the given category 35 | * 36 | * @param nodeCategory category over which the iterator will iterate 37 | * @return iterator over all the entries for the given category 38 | */ 39 | public Iterator iterator( NodeCategory nodeCategory ); 40 | 41 | /** 42 | * Returns map with local ids as keys and distances as values. See 43 | * {@link #put(cz.certicon.routing.model.entity.NodeSet.NodeCategory, long, long, float) put} 44 | * for more information about the distance. 45 | * 46 | * @param graph graph to search local ids from 47 | * @param nodeCategory category of the map 48 | * @return map[local_id, distance] for the given category 49 | */ 50 | public Map getMap( G graph, NodeCategory nodeCategory ); 51 | 52 | /** 53 | * Class representing a single node entry. It contains node's global id, 54 | * edge's global id (the edge close to the original location, on which the 55 | * node lies), distance (distance from point on the edge (closest to the 56 | * original location) to the node). 57 | */ 58 | public static class NodeEntry { 59 | 60 | private final long edgeId; 61 | private final long nodeId; 62 | private final float distance; 63 | 64 | /** 65 | * Constructor 66 | * 67 | * @param edgeId global id of the edge close to the original location 68 | * @param nodeId global id of the node related to the edge 69 | * @param distance distance of the node to the original location (mapped 70 | * to edge) 71 | */ 72 | public NodeEntry( long edgeId, long nodeId, float distance ) { 73 | this.edgeId = edgeId; 74 | this.nodeId = nodeId; 75 | this.distance = distance; 76 | } 77 | 78 | public long getEdgeId() { 79 | return edgeId; 80 | } 81 | 82 | public long getNodeId() { 83 | return nodeId; 84 | } 85 | 86 | public float getDistance() { 87 | return distance; 88 | } 89 | 90 | } 91 | 92 | /** 93 | * Enumeration of possible node categories: category for nodes around the 94 | * source location and category for nodes around the target location. 95 | */ 96 | public static enum NodeCategory { 97 | SOURCE, TARGET; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/NodeSetBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import cz.certicon.routing.data.nodesearch.EvaluableOnlyException; 9 | import cz.certicon.routing.model.entity.NodeSet.NodeCategory; 10 | 11 | /** 12 | * Builder for node set. 13 | * 14 | * @author Michael Blaha {@literal } 15 | * @param type of NodeSet 16 | */ 17 | public interface NodeSetBuilder { 18 | 19 | /** 20 | * Adds given edge and node to the given category (source or target) with 21 | * the given distance (distance of the original location to the end of the 22 | * given edge (to the given node)). 23 | * 24 | * @param nodeCategory category to which this shall be added 25 | * @param edgeId edge's global id 26 | * @param nodeId node's global id 27 | * @param length distance in meters from node to the original location (on 28 | * the edge) 29 | * @param speed edge's maximal speed 30 | */ 31 | public void addNode( NodeCategory nodeCategory, long nodeId, long edgeId, float length, float speed ); 32 | 33 | /** 34 | * Adds node as a crossroad (without edge). The distance is implicitly zero. 35 | * 36 | * @param nodeCategory category to which this shall be added 37 | * @param nodeId node's global id 38 | */ 39 | public void addCrossroad( NodeCategory nodeCategory, long nodeId ); 40 | 41 | /** 42 | * Creates and returns the node set 43 | * 44 | * @return node set 45 | * @throws EvaluableOnlyException thrown when all the edges are the same, 46 | * therefore it is not a routing issue, just simple calculation. 47 | */ 48 | public T build() throws EvaluableOnlyException; 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/NodeSetBuilderFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | /** 9 | * Factory for {@link NodeSetBuilder} 10 | * 11 | * @author Michael Blaha {@literal } 12 | * @param node set type 13 | */ 14 | public interface NodeSetBuilderFactory { 15 | 16 | /** 17 | * Creates and returns {@link NodeSetBuilder} 18 | * 19 | * @return {@link NodeSetBuilder} 20 | */ 21 | public NodeSetBuilder createNodeSetBuilder(); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/Path.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import cz.certicon.routing.model.basic.Length; 9 | import cz.certicon.routing.model.basic.Time; 10 | import java.util.List; 11 | 12 | /** 13 | * Interface defining the path - path from source to target with all the 14 | * required data, such as geometry, length, time, etc. 15 | * 16 | * @author Michael Blaha {@literal } 17 | */ 18 | public interface Path { 19 | 20 | /** 21 | * Returns {@link Length} of the path 22 | * 23 | * @return {@link Length} of the path 24 | */ 25 | public Length getLength(); 26 | 27 | /** 28 | * Returns {@link Time} of the path (time required to travel from source to 29 | * target) 30 | * 31 | * @return {@link Time} of the path 32 | */ 33 | public Time getTime(); 34 | 35 | /** 36 | * Returns path's geometry (list of coordinates) 37 | * 38 | * @return path's geometry 39 | */ 40 | public List getCoordinates(); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/PathBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Builder for paths 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param path type 15 | * @param graph type 16 | */ 17 | public interface PathBuilder { 18 | 19 | /** 20 | * Adds start edge, which is usually found independently of routing - it is 21 | * the closest edge to the original source location. 22 | * 23 | * @param graph related graph 24 | * @param edgeId global edge id 25 | * @param isForward whether this edge is the forward one in relation to data 26 | * (for example, if it is not forward, the geometry (coordinates) should be 27 | * reversed 28 | * @param coordinates edge's coordinates (geometry) 29 | * @param length edge's length in meters 30 | * @param time time to travel pass the edge in seconds 31 | */ 32 | public void addStartEdge( G graph, long edgeId, boolean isForward, List coordinates, double length, double time ); 33 | 34 | /** 35 | * Adds end edge, which is usually found independently of routing - it is 36 | * the closest edge to the original target location. 37 | * 38 | * @param graph related graph 39 | * @param edgeId global edge id 40 | * @param isForward whether this edge is the forward one in relation to data 41 | * (for example, if it is not forward, the geometry (coordinates) should be 42 | * reversed 43 | * @param coordinates edge's coordinates (geometry) 44 | * @param length edge's length in meters 45 | * @param time time to travel pass the edge in seconds 46 | */ 47 | public void addEndEdge( G graph, long edgeId, boolean isForward, List coordinates, double length, double time ); 48 | 49 | /** 50 | * Adds an edge (to the end of list) 51 | * 52 | * @param graph related graph 53 | * @param edgeId global edge id 54 | * @param isForward whether this edge is the forward one in relation to data 55 | * (for example, if it is not forward, the geometry (coordinates) should be 56 | * reversed 57 | * @param coordinates edge's coordinates (geometry) 58 | * @param length edge's length in meters 59 | * @param time time to travel pass the edge in seconds 60 | */ 61 | public void addEdge( G graph, long edgeId, boolean isForward, List coordinates, double length, double time ); 62 | 63 | /** 64 | * Adds coordinate (single pair of latitude and longitude - a point) 65 | * 66 | * @param coordinate given coordinate 67 | */ 68 | public void addCoordinates( Coordinate coordinate ); 69 | 70 | /** 71 | * Adds length to the current length (additional length) 72 | * 73 | * @param length given length in meters 74 | */ 75 | public void addLength( double length ); 76 | 77 | /** 78 | * Adds time to the current time (additional time) 79 | * 80 | * @param time given time in seconds 81 | */ 82 | public void addTime( double time ); 83 | 84 | /** 85 | * Clears this builder 86 | */ 87 | public void clear(); 88 | 89 | /** 90 | * Creates and returns the path from the given data 91 | * 92 | * @param graph related graph 93 | * @param sourceCoordinate original location of the source 94 | * @param targetCoordinate original location of the target 95 | * @return path based on the accumulated data 96 | */ 97 | public T build( Graph graph, Coordinate sourceCoordinate, Coordinate targetCoordinate ); 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/ch/ChDataBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.ch; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | 10 | /** 11 | * Interface defining functionality of the CH data builder 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param CH data type 15 | */ 16 | public interface ChDataBuilder { 17 | 18 | /** 19 | * Setter for the startId. StartId is the id of the first shortcut to be 20 | * created - all the shortcuts created will be equal or greater to this 21 | * startId. 22 | * 23 | * @param startId ideally last edge id + 1 24 | */ 25 | public void setStartId( long startId ); 26 | 27 | /** 28 | * Sets rank to a node 29 | * 30 | * @param nodeId id of the node 31 | * @param rank new rank of the node 32 | */ 33 | public void setRank( long nodeId, int rank ); 34 | 35 | /** 36 | * Adds shortcut - pair of two consequent shortcuts/edges, which together 37 | * create another shortcut 38 | * 39 | * @param shortcutId new shortcut id (greater or equal to startId) 40 | * @param sourceEdgeId id of the source edge/shortcut 41 | * @param targetEdgeId id of the target edge/shortcut 42 | */ 43 | public void addShortcut( long shortcutId, long sourceEdgeId, long targetEdgeId ); 44 | 45 | /** 46 | * Returns distance type of the data 47 | * 48 | * @return distance type of the data 49 | */ 50 | public DistanceType getDistanceType(); 51 | 52 | /** 53 | * Builds the data and returns them 54 | * 55 | * @return built data 56 | */ 57 | public T build(); 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/ch/ChDataExtractor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.ch; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.basic.Pair; 10 | import cz.certicon.routing.model.basic.Trinity; 11 | import java.util.Iterator; 12 | 13 | /** 14 | * Interface defining functionality of the CH data extractor - iterators for 15 | * ranks and shortcuts 16 | * 17 | * @author Michael Blaha {@literal } 18 | * @param CH data type 19 | */ 20 | public interface ChDataExtractor { 21 | 22 | /** 23 | * Creates and returns iterator over nodes and their ranks - returning pairs 24 | * [nodeId, rank] 25 | * 26 | * @return iterator over [nodeId,rank] 27 | */ 28 | public Iterator> getRankIterator(); 29 | 30 | /** 31 | * Creates and returns iterator over shortcuts - returning trinities 32 | * [nodeId, startEdgeId, endEdgeId] 33 | * 34 | * @return iterator over [nodeId, startEdgeId, endEdgeId] 35 | */ 36 | public Iterator> getShortcutIterator(); 37 | 38 | /** 39 | * Returns distance type 40 | * 41 | * @return distance type 42 | */ 43 | public DistanceType getDistanceType(); 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/ch/ChDataFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.ch; 7 | 8 | /** 9 | * Interface defining factory for CH data builder and extractor 10 | * 11 | * @author Michael Blaha {@literal } 12 | * @param CH data type 13 | */ 14 | public interface ChDataFactory { 15 | 16 | /** 17 | * Returns new CH data builder 18 | * 19 | * @return new CH data builder 20 | */ 21 | public ChDataBuilder createChDataBuilder(); 22 | 23 | /** 24 | * Returns new CH data extractor for the given data 25 | * 26 | * @param extracted given data 27 | * @return new CH data extractor 28 | */ 29 | public ChDataExtractor createChDataExtractor( T extracted ); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/ch/SimpleChDataExtractor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.ch; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.entity.Graph; 10 | import cz.certicon.routing.model.basic.Pair; 11 | import cz.certicon.routing.model.basic.Trinity; 12 | import java.util.Iterator; 13 | 14 | /** 15 | * Simple implementation of the {@link ChDataExtractor} using the 16 | * {@link PreprocessedData} as a representation of CH data 17 | * 18 | * 19 | * @author Michael Blaha {@literal } 20 | */ 21 | public class SimpleChDataExtractor implements ChDataExtractor { 22 | 23 | private final Graph graph; 24 | private final DistanceType distanceType; 25 | private final PreprocessedData data; 26 | 27 | public SimpleChDataExtractor( Graph graph, DistanceType distanceType, PreprocessedData data ) { 28 | this.graph = graph; 29 | this.distanceType = distanceType; 30 | this.data = data; 31 | } 32 | 33 | @Override 34 | public Iterator> getRankIterator() { 35 | return new RankIterator(); 36 | } 37 | 38 | @Override 39 | public Iterator> getShortcutIterator() { 40 | return new ShortcutIterator(); 41 | } 42 | 43 | @Override 44 | public DistanceType getDistanceType() { 45 | return distanceType; 46 | } 47 | 48 | private class RankIterator implements Iterator> { 49 | 50 | private int counter = -1; 51 | 52 | @Override 53 | public boolean hasNext() { 54 | return counter + 1 < data.getRanks().length; 55 | } 56 | 57 | @Override 58 | public Pair next() { 59 | counter++; 60 | return new Pair<>( graph.getNodeOrigId( counter ), data.getRank( counter ) ); 61 | } 62 | 63 | } 64 | 65 | private class ShortcutIterator implements Iterator> { 66 | 67 | private int counter = -1; 68 | 69 | @Override 70 | public boolean hasNext() { 71 | return counter + 1 < data.getShortcutCount(); 72 | } 73 | 74 | @Override 75 | public Trinity next() { 76 | counter++; 77 | long startEdge; 78 | if ( data.getStartEdge( counter ) < graph.getEdgeCount() ) { 79 | startEdge = graph.getEdgeOrigId( data.getStartEdge( counter ) ); 80 | } else { 81 | startEdge = data.getStartId() + data.getStartEdge( counter ) - graph.getEdgeCount(); 82 | } 83 | long endEdge; 84 | if ( data.getEndEdge( counter ) < graph.getEdgeCount() ) { 85 | endEdge = graph.getEdgeOrigId( data.getEndEdge( counter ) ); 86 | } else { 87 | endEdge = data.getStartId() + data.getEndEdge( counter ) - graph.getEdgeCount(); 88 | } 89 | // if ( data.getStartId() + counter == 127945 ) { 90 | // System.out.println( "writing: " + ( data.getStartId() + counter ) + " = " + startEdge + " -> " + endEdge ); 91 | // System.out.println( "from: " + counter + " = " + data.getStartEdge( counter ) + " -> " + data.getEndEdge( counter ) ); 92 | // System.out.println( "data: startId = " + data.getStartId() + ", counter = " + counter + ", edgeCount = " + graph.getEdgeCount() ); 93 | // } 94 | return new Trinity<>( data.getStartId() + counter, startEdge, endEdge ); 95 | } 96 | 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/ch/SimpleChDataFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.ch; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.entity.Graph; 10 | 11 | /** 12 | * Simple implementation of the {@link ChDataFactory} using the 13 | * {@link PreprocessedData} as a representation of CH data 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public class SimpleChDataFactory implements ChDataFactory { 18 | 19 | private final Graph graph; 20 | private final DistanceType distanceType; 21 | 22 | public SimpleChDataFactory( Graph graph, DistanceType distanceType ) { 23 | this.graph = graph; 24 | this.distanceType = distanceType; 25 | } 26 | 27 | @Override 28 | public ChDataBuilder createChDataBuilder() { 29 | return new SimpleChDataBuilder( graph, distanceType ); 30 | } 31 | 32 | @Override 33 | public ChDataExtractor createChDataExtractor( PreprocessedData extracted ) { 34 | return new SimpleChDataExtractor( graph, distanceType, extracted ); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimpleCoordinateSetBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.CoordinateSetBuilder; 9 | import cz.certicon.routing.model.entity.Coordinate; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | /** 15 | * Simple implementation of the {@link CoordinateSetBuilder} interface. Uses map 16 | * internally. 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public class SimpleCoordinateSetBuilder implements CoordinateSetBuilder>> { 21 | 22 | private final Map> coordinatesMap; 23 | 24 | /** 25 | * Constructor for {@link SimpleCoordinateSetBuilder} 26 | */ 27 | public SimpleCoordinateSetBuilder() { 28 | this.coordinatesMap = new HashMap<>(); 29 | } 30 | 31 | @Override 32 | public void addCoordinates( long edgeId, List coordinates ) { 33 | coordinatesMap.put( edgeId, coordinates ); 34 | } 35 | 36 | @Override 37 | public Map> build() { 38 | return coordinatesMap; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimpleCoordinateSetBuilderFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.CoordinateSetBuilder; 9 | import cz.certicon.routing.model.entity.CoordinateSetBuilderFactory; 10 | import cz.certicon.routing.model.entity.Coordinate; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | /** 15 | * Simple implementation of the {@link CoordinateSetBuilderFactory} interface. 16 | * Uses maps internally. 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public class SimpleCoordinateSetBuilderFactory implements CoordinateSetBuilderFactory>> { 21 | 22 | @Override 23 | public CoordinateSetBuilder>> createCoordinateSetBuilder() { 24 | return new SimpleCoordinateSetBuilder(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimpleGraphBuilderFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.entity.Graph; 10 | import cz.certicon.routing.model.entity.GraphBuilder; 11 | import cz.certicon.routing.model.entity.GraphBuilderFactory; 12 | 13 | /** 14 | * Simple implementation of the {@link GraphBuilderFactory} interface. Uses maps 15 | * internally. 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class SimpleGraphBuilderFactory implements GraphBuilderFactory { 20 | 21 | private final DistanceType distanceType; 22 | 23 | /** 24 | * Constructor of {@link SimpleGraphBuilderFactory} 25 | * 26 | * @param distanceType metric 27 | */ 28 | public SimpleGraphBuilderFactory( DistanceType distanceType ) { 29 | this.distanceType = distanceType; 30 | } 31 | 32 | @Override 33 | public GraphBuilder createGraphBuilder( int nodeCount, int edgeCount ) { 34 | return new SimpleGraphBuilder( nodeCount, edgeCount, distanceType ); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimpleNodeSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.Graph; 9 | import cz.certicon.routing.model.entity.NodeSet; 10 | import java.util.HashMap; 11 | import java.util.HashSet; 12 | import java.util.Iterator; 13 | import java.util.Map; 14 | import java.util.Set; 15 | 16 | /** 17 | * Simple implementation of the {@link NodeSet} interface. Uses maps internally. 18 | * 19 | * @author Michael Blaha {@literal } 20 | */ 21 | public class SimpleNodeSet implements NodeSet { 22 | 23 | private Map> nodeEntriesMap = new HashMap<>(); 24 | 25 | @Override 26 | public void put( NodeCategory nodeCategory, long edgeId, long nodeId, float distance ) { 27 | getSet( nodeCategory ).add( new NodeEntry( edgeId, nodeId, distance ) ); 28 | } 29 | 30 | @Override 31 | public Iterator iterator( NodeCategory nodeCategory ) { 32 | return getSet( nodeCategory ).iterator(); 33 | } 34 | 35 | private Set getSet( NodeCategory nodeCategory ) { 36 | Set set = nodeEntriesMap.get( nodeCategory ); 37 | if ( set == null ) { 38 | set = new HashSet<>(); 39 | nodeEntriesMap.put( nodeCategory, set ); 40 | } 41 | return set; 42 | } 43 | 44 | @Override 45 | public Map getMap( Graph graph, NodeCategory nodeCategory ) { 46 | Map map = new HashMap<>(); 47 | Iterator it = iterator( nodeCategory ); 48 | while ( it.hasNext() ) { 49 | NodeEntry entry = it.next(); 50 | map.put( graph.getNodeByOrigId( entry.getNodeId() ), entry.getDistance() ); 51 | } 52 | return map; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimpleNodeSetBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.data.nodesearch.EvaluableOnlyException; 9 | import cz.certicon.routing.model.entity.DistanceType; 10 | import cz.certicon.routing.model.entity.Graph; 11 | import cz.certicon.routing.model.entity.NodeSet; 12 | import cz.certicon.routing.model.entity.NodeSet.NodeCategory; 13 | import cz.certicon.routing.model.entity.NodeSet.NodeEntry; 14 | import cz.certicon.routing.model.entity.Coordinate; 15 | import cz.certicon.routing.model.entity.NodeSetBuilder; 16 | import cz.certicon.routing.utils.CoordinateUtils; 17 | import cz.certicon.routing.utils.DoubleComparator; 18 | import java.util.Iterator; 19 | 20 | /** 21 | * Simple implementation of the {@link NodeSetBuilder} interface. Uses maps 22 | * internally. 23 | * 24 | * @author Michael Blaha {@literal } 25 | */ 26 | public class SimpleNodeSetBuilder implements NodeSetBuilder> { 27 | 28 | private final DistanceType distanceType; 29 | private final Graph graph; 30 | private final NodeSet nodeSet; 31 | 32 | /** 33 | * Constructor of {@link NodeSetBuilder} 34 | * 35 | * @param graph graph 36 | * @param distanceType metric 37 | */ 38 | public SimpleNodeSetBuilder( Graph graph, DistanceType distanceType ) { 39 | this.distanceType = distanceType; 40 | this.graph = graph; 41 | this.nodeSet = new SimpleNodeSet(); 42 | } 43 | 44 | @Override 45 | public NodeSet build() throws EvaluableOnlyException { 46 | Iterator itSource = nodeSet.iterator( NodeCategory.SOURCE ); 47 | while ( itSource.hasNext() ) { 48 | Iterator itTarget = nodeSet.iterator( NodeCategory.TARGET ); 49 | NodeEntry sourceEntry = itSource.next(); 50 | while ( itTarget.hasNext() ) { 51 | NodeEntry targetEntry = itTarget.next(); 52 | if ( sourceEntry.getEdgeId() == targetEntry.getEdgeId() ) { 53 | float edgeLength = graph.getLength( graph.getEdgeByOrigId( sourceEntry.getEdgeId() ) ); 54 | float sourceDist = edgeLength - sourceEntry.getDistance(); 55 | float targetDist = targetEntry.getDistance(); 56 | System.out.println( "comparing: " + sourceDist + " vs " + targetDist ); 57 | if ( DoubleComparator.isLowerOrEqualTo( sourceDist, targetDist, CoordinateUtils.DISTANCE_PRECISION_METERS ) ) { 58 | int srcNode = graph.getNodeByOrigId( sourceEntry.getNodeId() ); 59 | int tarNode = graph.getNodeByOrigId( targetEntry.getNodeId() ); 60 | Coordinate src = new Coordinate( graph.getLatitude( srcNode ), graph.getLongitude( srcNode ) ); 61 | Coordinate tar = new Coordinate( graph.getLatitude( tarNode ), graph.getLongitude( tarNode ) ); 62 | throw new EvaluableOnlyException( sourceEntry.getEdgeId(), src, tar ); 63 | } 64 | } 65 | } 66 | } 67 | return nodeSet; 68 | } 69 | 70 | @Override 71 | public void addNode( NodeCategory nodeCategory, long nodeId, long edgeId, float length, float speed ) { 72 | float dist = (float) distanceType.calculateDistance( length, speed ); 73 | nodeSet.put( nodeCategory, edgeId, nodeId, dist ); 74 | } 75 | 76 | @Override 77 | public void addCrossroad( NodeCategory nodeCategory, long nodeId ) { 78 | nodeSet.put( nodeCategory, -1, nodeId, 0 ); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimpleNodeSetBuilderFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.DistanceType; 9 | import cz.certicon.routing.model.entity.Graph; 10 | import cz.certicon.routing.model.entity.NodeSet; 11 | import cz.certicon.routing.model.entity.NodeSetBuilder; 12 | import cz.certicon.routing.model.entity.NodeSetBuilderFactory; 13 | 14 | /** 15 | * Simple implementation of the {@link NodeSetBuilderFactory} interface. Uses 16 | * maps internally. 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public class SimpleNodeSetBuilderFactory implements NodeSetBuilderFactory> { 21 | 22 | private final DistanceType distanceType; 23 | private final Graph graph; 24 | 25 | /** 26 | * Constructor of {@link SimpleNodeSetBuilderFactory} 27 | * 28 | * @param graph graph 29 | * @param distanceType metric 30 | */ 31 | public SimpleNodeSetBuilderFactory( Graph graph, DistanceType distanceType ) { 32 | this.graph = graph; 33 | this.distanceType = distanceType; 34 | } 35 | 36 | @Override 37 | public NodeSetBuilder> createNodeSetBuilder() { 38 | return new SimpleNodeSetBuilder( graph, distanceType ); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimplePath.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.Path; 9 | import cz.certicon.routing.model.basic.Length; 10 | import cz.certicon.routing.model.basic.Time; 11 | import cz.certicon.routing.model.entity.Coordinate; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | /** 16 | * Simple implementation of the {@link Path} interface. Uses maps internally. 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public class SimplePath implements Path { 21 | 22 | private final ArrayList coordinates; 23 | private final Length length; 24 | private final Time time; 25 | 26 | /** 27 | * Constructor of {@link SimplePath} 28 | * 29 | * @param coordinates path coordinates sequence 30 | * @param length path length 31 | * @param time path time 32 | */ 33 | public SimplePath( ArrayList coordinates, Length length, Time time ) { 34 | this.coordinates = coordinates; 35 | this.length = length; 36 | this.time = time; 37 | } 38 | 39 | @Override 40 | public Length getLength() { 41 | return length; 42 | } 43 | 44 | @Override 45 | public Time getTime() { 46 | return time; 47 | } 48 | 49 | @Override 50 | public List getCoordinates() { 51 | return coordinates; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/common/SimplePathBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.common; 7 | 8 | import cz.certicon.routing.model.entity.Graph; 9 | import cz.certicon.routing.model.entity.Path; 10 | import cz.certicon.routing.model.entity.PathBuilder; 11 | import cz.certicon.routing.model.basic.Length; 12 | import cz.certicon.routing.model.basic.LengthUnits; 13 | import cz.certicon.routing.model.basic.Time; 14 | import cz.certicon.routing.model.basic.TimeUnits; 15 | import cz.certicon.routing.model.entity.Coordinate; 16 | import java.util.ArrayList; 17 | import java.util.Collections; 18 | import java.util.List; 19 | 20 | /** 21 | * Simple implementation of the {@link PathBuilder} interface. Uses maps 22 | * internally. 23 | * 24 | * @author Michael Blaha {@literal } 25 | */ 26 | public class SimplePathBuilder implements PathBuilder { 27 | 28 | private ArrayList coordinates = new ArrayList<>(); 29 | private List start = null; 30 | private List end = null; 31 | private double time = 0; 32 | private double length = 0; 33 | 34 | @Override 35 | public void addEdge( Graph graph, long edgeId, boolean isForward, List edgeCoordinates, double length, double time ) { 36 | if ( !isForward ) { 37 | Collections.reverse( edgeCoordinates ); 38 | } 39 | this.coordinates.addAll( edgeCoordinates ); 40 | addLength( length ); 41 | addTime( time ); 42 | } 43 | 44 | @Override 45 | public void addStartEdge( Graph graph, long edgeId, boolean isForward, List coordinates, double length, double time ) { 46 | if ( !isForward ) { 47 | Collections.reverse( coordinates ); 48 | } 49 | if ( this.coordinates.isEmpty() ) { 50 | this.coordinates.addAll( coordinates ); 51 | } else { 52 | start = coordinates; 53 | } 54 | addLength( length ); 55 | addTime( time ); 56 | } 57 | 58 | @Override 59 | public void addEndEdge( Graph graph, long edgeId, boolean isForward, List coordinates, double length, double time ) { 60 | if ( !isForward ) { 61 | Collections.reverse( coordinates ); 62 | } 63 | end = coordinates; 64 | addLength( length ); 65 | addTime( time ); 66 | } 67 | 68 | @Override 69 | public void addCoordinates( Coordinate coords ) { 70 | this.coordinates.add( coords ); 71 | } 72 | 73 | @Override 74 | public void addLength( double length ) { 75 | this.length += length; 76 | // System.out.println( "adding length: " + length ); 77 | } 78 | 79 | @Override 80 | public void addTime( double time ) { 81 | this.time += time; 82 | // System.out.println( "adding time: " + time ); 83 | } 84 | 85 | @Override 86 | public void clear() { 87 | coordinates.clear(); 88 | start = null; 89 | end = null; 90 | time = 0; 91 | length = 0; 92 | } 93 | 94 | @Override 95 | public Path build( Graph graph, Coordinate sourceCoordinate, Coordinate targetCoordinate ) { 96 | ArrayList coords; 97 | if ( start != null ) { 98 | coords = new ArrayList<>( start ); 99 | coords.addAll( coordinates ); 100 | } else { 101 | coords = coordinates; 102 | } 103 | if ( end != null ) { 104 | coords.addAll( end ); 105 | } 106 | if ( coords.isEmpty() ) { 107 | coords.add( sourceCoordinate ); 108 | coords.add( targetCoordinate ); 109 | } 110 | return new SimplePath( coords, new Length( LengthUnits.METERS, (long) length ), new Time( TimeUnits.SECONDS, (long) time ) ); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/entity/neighbourlist/NeighbourlistDirectedGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.entity.neighbourlist; 7 | 8 | /** 9 | * 10 | * @deprecated use {@link NeighbourlistGraph} instead, it can be used as 11 | * Directed as well 12 | * @author Michael Blaha {@literal } 13 | */ 14 | public class NeighbourlistDirectedGraph { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/utility/ProgressListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.utility; 7 | 8 | /** 9 | * Interface defining the progress listener functionality. It can be adjusted 10 | * via number of updates (number steps taken from 0 to number of updates) or 11 | * size and calculation ratio ({@link #init(int, double) init}). 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public interface ProgressListener { 16 | 17 | /** 18 | * Returns number of updates 19 | * 20 | * @return number of updates 21 | */ 22 | public int getNumOfUpdates(); 23 | 24 | /** 25 | * Sets number of updates. Number of updates is the amount of steps taken 26 | * from the beginning to the end. 27 | * 28 | * @param numOfUpdates number of updates 29 | */ 30 | public void setNumOfUpdates( int numOfUpdates ); 31 | 32 | /** 33 | * Initializes the progress listener. Can be called multiple times - sum of 34 | * the calculation ratios of multiple calls must add up to 1. 35 | * 36 | * @param size amount of operations - calls to next step 37 | * @param calculationRatio ratio of the current set of updates - for 38 | * example, having size = 100 and calculation ratio = 0.5 and number of 39 | * updates = 100, progress update is performed every 2 steps, since size 100 40 | * is related to only 50 updates (100 * 0.5). 41 | */ 42 | public void init( int size, double calculationRatio ); 43 | 44 | /** 45 | * Method called when enough progress has been made to call an update. 46 | * 47 | * @param done ratio of finished operations to all the operations 48 | */ 49 | public void onProgressUpdate( double done ); 50 | 51 | /** 52 | * Returns true when the progress update was called, false otherwise 53 | * 54 | * @return boolean value indicating, whether the progress update was called 55 | * or not 56 | */ 57 | public boolean nextStep(); 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/utility/iterator/DoubleArrayIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.utility.iterator; 7 | 8 | import java.util.Iterator; 9 | 10 | /** 11 | * Simple iterator of primitive double array 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public class DoubleArrayIterator implements Iterator { 16 | 17 | private final double[] array; 18 | private int position = -1; 19 | 20 | public DoubleArrayIterator( double[] array ) { 21 | this.array = array; 22 | } 23 | 24 | @Override 25 | public boolean hasNext() { 26 | return position + 1 < array.length; 27 | } 28 | 29 | @Override 30 | public Double next() { 31 | return array[++position]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/utility/iterator/IntArrayIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.utility.iterator; 7 | 8 | import java.util.Iterator; 9 | 10 | /** 11 | * Simple iterator of primitive integer array 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public class IntArrayIterator implements Iterator { 16 | 17 | private final int[] array; 18 | private int position = -1; 19 | 20 | public IntArrayIterator( int[] array ) { 21 | this.array = array; 22 | } 23 | 24 | @Override 25 | public boolean hasNext() { 26 | return position + 1 < array.length; 27 | } 28 | 29 | @Override 30 | public Integer next() { 31 | return array[++position]; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/utility/iterator/LongIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.utility.iterator; 7 | 8 | import java.util.Iterator; 9 | 10 | /** 11 | * Simple iterator of primitive long array 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public class LongIterator implements Iterator { 16 | 17 | private final long[] array; 18 | private int position = -1; 19 | 20 | public LongIterator( long[] array ) { 21 | this.array = array; 22 | } 23 | 24 | @Override 25 | public boolean hasNext() { 26 | return position + 1 < array.length; 27 | } 28 | 29 | @Override 30 | public Long next() { 31 | return array[++position]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/utility/progress/EmptyProgressListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.utility.progress; 7 | 8 | import cz.certicon.routing.model.utility.ProgressListener; 9 | 10 | /** 11 | * Empty implementation of {@link ProgressListener}, which does nothing on 12 | * progress (this serves for the algorithm to call the progress listener anyway 13 | * and not do anything, if not required). 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public class EmptyProgressListener implements ProgressListener { 18 | 19 | @Override 20 | public void onProgressUpdate( double done ) { 21 | } 22 | 23 | @Override 24 | public boolean nextStep() { 25 | return false; 26 | } 27 | 28 | @Override 29 | public int getNumOfUpdates() { 30 | return 0; 31 | } 32 | 33 | @Override 34 | public void setNumOfUpdates( int numOfUpdates ) { 35 | } 36 | 37 | @Override 38 | public void init( int size, double calculationRatio ) { 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/model/utility/progress/SimpleProgressListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.utility.progress; 7 | 8 | import cz.certicon.routing.model.utility.ProgressListener; 9 | import cz.certicon.routing.utils.DoubleComparator; 10 | 11 | /** 12 | * Simple implementation of the {@link ProgressListener}. Implicitly it travels 13 | * over percentages: from 0 to 100 via steps of size 1. It can be adjusted via 14 | * number of updates (number steps taken from 0 to number of updates) or size 15 | * and calculation ratio ({@link #init(int, double) init}). 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public abstract class SimpleProgressListener implements ProgressListener { 20 | 21 | private static final double PRECISION = 10E-9; 22 | 23 | private int numOfUpdates = 100; 24 | private long counter = 0; 25 | private int size = 1; 26 | private double calculationRatio = 0.0; 27 | 28 | private double last = 0.0; 29 | private double add = 0.0; 30 | private double step = 1.0; 31 | 32 | public SimpleProgressListener() { 33 | } 34 | 35 | public SimpleProgressListener( int numberOfUpdates ) { 36 | this.numOfUpdates = numberOfUpdates; 37 | } 38 | 39 | @Override 40 | public int getNumOfUpdates() { 41 | return numOfUpdates; 42 | } 43 | 44 | @Override 45 | public void setNumOfUpdates( int numOfUpdates ) { 46 | this.numOfUpdates = numOfUpdates; 47 | } 48 | 49 | @Override 50 | public boolean nextStep() { 51 | double current = (double) ++counter / size; 52 | if ( DoubleComparator.isLowerOrEqualTo( last + step, current, PRECISION ) ) { 53 | last = current; 54 | onProgressUpdate( add + ( last * calculationRatio ) ); 55 | return true; 56 | } 57 | if ( counter == size ) { 58 | onProgressUpdate( add + calculationRatio ); 59 | return true; 60 | } 61 | return false; 62 | } 63 | 64 | @Override 65 | final public void init( int size, double calculationRatio ) { 66 | add += this.calculationRatio; 67 | this.calculationRatio = calculationRatio; 68 | this.size = size; 69 | step = 1 / ( numOfUpdates * calculationRatio ); 70 | counter = 0; 71 | last = 0; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/PathDisplayer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation; 7 | 8 | import cz.certicon.routing.model.entity.Path; 9 | 10 | /** 11 | * Interface defining path displaying functionality. Displays given path on the 12 | * map. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public interface PathDisplayer { 17 | 18 | /** 19 | * Displays given path on the map 20 | * 21 | * @param path given path 22 | */ 23 | public void displayPath( Path path ); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/jxmapviewer/JxMapViewerFrame.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation.jxmapviewer; 7 | 8 | import cz.certicon.routing.model.entity.Path; 9 | import cz.certicon.routing.presentation.PathDisplayer; 10 | import cz.certicon.routing.model.entity.Coordinate; 11 | import java.util.ArrayList; 12 | import java.util.HashSet; 13 | import java.util.List; 14 | import java.util.Set; 15 | import javax.swing.JFrame; 16 | import static javax.swing.JFrame.EXIT_ON_CLOSE; 17 | import org.jdesktop.swingx.JXMapKit; 18 | import org.jdesktop.swingx.JXMapViewer; 19 | import org.jdesktop.swingx.OSMTileFactoryInfo; 20 | import org.jdesktop.swingx.mapviewer.DefaultTileFactory; 21 | import org.jdesktop.swingx.mapviewer.GeoPosition; 22 | import org.jdesktop.swingx.mapviewer.TileFactoryInfo; 23 | import org.jdesktop.swingx.painter.CompoundPainter; 24 | import org.jdesktop.swingx.painter.Painter; 25 | 26 | /** 27 | * An implementation of {@link PathDisplayer} using a JXMapViewer library. 28 | * 29 | * @author Michael Blaha {@literal } 30 | */ 31 | public class JxMapViewerFrame implements PathDisplayer { 32 | 33 | private final JXMapViewer mapViewer; 34 | private final JXMapKit mapKit; 35 | private JFrame frame; 36 | private DefaultTileFactory tileFactory; 37 | private final Set fitGeoPosition = new HashSet<>(); 38 | private final List> painters = new ArrayList<>(); 39 | private final Set waypoints = new HashSet<>(); 40 | 41 | public JxMapViewerFrame() { 42 | this.mapKit = new JXMapKit(); 43 | this.mapViewer = mapKit.getMainMap(); 44 | } 45 | 46 | @Override 47 | public void displayPath( Path path ) { 48 | frame = new JFrame( "map" ); 49 | frame.setContentPane( mapViewer ); 50 | frame.setSize( 800, 600 ); 51 | frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); 52 | frame.setVisible( true ); 53 | TileFactoryInfo info = new OSMTileFactoryInfo(); 54 | tileFactory = new DefaultTileFactory( info ); 55 | tileFactory.setThreadPoolSize( 8 ); 56 | mapKit.setTileFactory( tileFactory ); 57 | 58 | fitGeoPosition.clear(); 59 | if ( path.getCoordinates().size() > 0 ) { 60 | Coordinate source = path.getCoordinates().get( 0 ); 61 | Coordinate target = path.getCoordinates().get( path.getCoordinates().size() - 1 ); 62 | fitGeoPosition.add( new GeoPosition( source.getLatitude(), source.getLongitude() ) ); 63 | fitGeoPosition.add( new GeoPosition( target.getLatitude(), target.getLongitude() ) ); 64 | mapViewer.zoomToBestFit( fitGeoPosition, 0.7 ); 65 | 66 | List track = new ArrayList<>(); 67 | for ( Coordinate coordinate : path.getCoordinates() ) { 68 | track.add( new GeoPosition( coordinate.getLatitude(), coordinate.getLongitude() ) ); 69 | } 70 | RoutePainter routePainter = new RoutePainter( track ); 71 | for ( LabelWaypoint waypoint : waypoints ) { 72 | mapViewer.add( waypoint.getComponent() ); 73 | } 74 | painters.add( routePainter ); 75 | LabelWaypointOverlayPainter p = new LabelWaypointOverlayPainter(); 76 | p.setWaypoints( waypoints ); 77 | painters.add( p ); 78 | CompoundPainter painter = new CompoundPainter<>( painters ); 79 | mapViewer.setOverlayPainter( painter ); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/jxmapviewer/JxNodeViewer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation.jxmapviewer; 7 | 8 | import cz.certicon.routing.model.entity.Path; 9 | import cz.certicon.routing.presentation.PathDisplayer; 10 | import cz.certicon.routing.model.entity.Coordinate; 11 | import java.util.ArrayList; 12 | import java.util.HashSet; 13 | import java.util.List; 14 | import java.util.Set; 15 | import javax.swing.JFrame; 16 | import static javax.swing.JFrame.EXIT_ON_CLOSE; 17 | import org.jdesktop.swingx.JXMapKit; 18 | import org.jdesktop.swingx.JXMapViewer; 19 | import org.jdesktop.swingx.OSMTileFactoryInfo; 20 | import org.jdesktop.swingx.mapviewer.DefaultTileFactory; 21 | import org.jdesktop.swingx.mapviewer.GeoPosition; 22 | import org.jdesktop.swingx.mapviewer.TileFactoryInfo; 23 | import org.jdesktop.swingx.painter.CompoundPainter; 24 | import org.jdesktop.swingx.painter.Painter; 25 | 26 | /** 27 | * Implementation of {@link PathDisplayer} using JXMapViewer library. 28 | * 29 | * @author Michael Blaha {@literal } 30 | */ 31 | public class JxNodeViewer implements PathDisplayer { 32 | 33 | private final JXMapViewer mapViewer; 34 | private final JXMapKit mapKit; 35 | private JFrame frame; 36 | private DefaultTileFactory tileFactory; 37 | private final Set fitGeoPosition = new HashSet<>(); 38 | private final List> painters = new ArrayList<>(); 39 | private final Set waypoints = new HashSet<>(); 40 | 41 | public JxNodeViewer() { 42 | this.mapKit = new JXMapKit(); 43 | this.mapViewer = mapKit.getMainMap(); 44 | } 45 | 46 | @Override 47 | public void displayPath( Path path ) { 48 | frame = new JFrame( "map" ); 49 | frame.setContentPane( mapViewer ); 50 | frame.setSize( 800, 600 ); 51 | frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); 52 | frame.setVisible( true ); 53 | TileFactoryInfo info = new OSMTileFactoryInfo(); 54 | tileFactory = new DefaultTileFactory( info ); 55 | tileFactory.setThreadPoolSize( 8 ); 56 | mapKit.setTileFactory( tileFactory ); 57 | 58 | fitGeoPosition.clear(); 59 | if ( path.getCoordinates().size() > 0 ) { 60 | Coordinate source = path.getCoordinates().get( 0 ); 61 | Coordinate target = path.getCoordinates().get( path.getCoordinates().size() - 1 ); 62 | fitGeoPosition.add( new GeoPosition( source.getLatitude(), source.getLongitude() ) ); 63 | fitGeoPosition.add( new GeoPosition( target.getLatitude(), target.getLongitude() ) ); 64 | mapViewer.zoomToBestFit( fitGeoPosition, 0.7 ); 65 | 66 | List track = new ArrayList<>(); 67 | for ( Coordinate coordinate : path.getCoordinates() ) { 68 | track.add( new GeoPosition( coordinate.getLatitude(), coordinate.getLongitude() ) ); 69 | } 70 | NodePainter routePainter = new NodePainter(track ); 71 | for ( LabelWaypoint waypoint : waypoints ) { 72 | mapViewer.add( waypoint.getComponent() ); 73 | } 74 | painters.add( routePainter ); 75 | LabelWaypointOverlayPainter p = new LabelWaypointOverlayPainter(); 76 | p.setWaypoints( waypoints ); 77 | painters.add( p ); 78 | CompoundPainter painter = new CompoundPainter<>( painters ); 79 | mapViewer.setOverlayPainter( painter ); 80 | } 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/jxmapviewer/LabelWaypoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation.jxmapviewer; 7 | 8 | import java.awt.event.MouseEvent; 9 | import java.awt.event.MouseListener; 10 | import java.util.Objects; 11 | import javax.swing.JComponent; 12 | import javax.swing.JLabel; 13 | import javax.swing.JOptionPane; 14 | import org.jdesktop.swingx.mapviewer.DefaultWaypoint; 15 | import org.jdesktop.swingx.mapviewer.GeoPosition; 16 | 17 | /** 18 | * A waypoint class representing a waypoint with id as a label 19 | * 20 | * @author Michael Blaha {@literal } 21 | */ 22 | public class LabelWaypoint extends DefaultWaypoint { 23 | 24 | private final JLabel button; 25 | private final String text; 26 | 27 | private static final int MAX_LENGTH = 5; 28 | 29 | public LabelWaypoint( String text, GeoPosition coord ) { 30 | super( coord ); 31 | this.text = text; 32 | button = new JLabel( ( text.length() < MAX_LENGTH ) ? ( ( text.isEmpty() ) ? "empty" : text ) : text.substring( 0, MAX_LENGTH ) ); 33 | // button.setSize( 24, 24 ); 34 | // button.setPreferredSize( new Dimension( 24, 24 ) ); 35 | button.addMouseListener( new SwingWaypointMouseListener() ); 36 | button.setVisible( true ); 37 | } 38 | 39 | public JComponent getComponent() { 40 | return button; 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | int hash = 3; 46 | hash = 13 * hash + Objects.hashCode( this.getPosition() ); 47 | return hash; 48 | } 49 | 50 | @Override 51 | public boolean equals( Object obj ) { 52 | if ( this == obj ) { 53 | return true; 54 | } 55 | if ( obj == null ) { 56 | return false; 57 | } 58 | if ( getClass() != obj.getClass() ) { 59 | return false; 60 | } 61 | final LabelWaypoint other = (LabelWaypoint) obj; 62 | if ( !Objects.equals( this.getPosition(), other.getPosition() ) ) { 63 | return false; 64 | } 65 | return true; 66 | } 67 | 68 | 69 | 70 | private class SwingWaypointMouseListener implements MouseListener { 71 | 72 | @Override 73 | public void mouseClicked( MouseEvent e ) { 74 | JOptionPane.showMessageDialog( button, text ); 75 | } 76 | 77 | @Override 78 | public void mousePressed( MouseEvent e ) { 79 | } 80 | 81 | @Override 82 | public void mouseReleased( MouseEvent e ) { 83 | } 84 | 85 | @Override 86 | public void mouseEntered( MouseEvent e ) { 87 | } 88 | 89 | @Override 90 | public void mouseExited( MouseEvent e ) { 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/jxmapviewer/LabelWaypointOverlayPainter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation.jxmapviewer; 7 | 8 | import java.awt.Graphics2D; 9 | import java.awt.Rectangle; 10 | import java.awt.geom.Point2D; 11 | import javax.swing.JComponent; 12 | import org.jdesktop.swingx.JXMapViewer; 13 | import org.jdesktop.swingx.mapviewer.WaypointPainter; 14 | 15 | /** 16 | * An implementation of {@link WaypointPainter} supporting {@link LabeLWaypoint} 17 | * 18 | * @author Michael Blaha {@literal } 19 | */ 20 | public class LabelWaypointOverlayPainter extends WaypointPainter { 21 | 22 | @Override 23 | protected void doPaint( Graphics2D g, JXMapViewer jxMapViewer, int width, int height ) { 24 | for ( LabelWaypoint waypoint : getWaypoints() ) { 25 | Point2D point = jxMapViewer.getTileFactory().geoToPixel( 26 | waypoint.getPosition(), jxMapViewer.getZoom() ); 27 | Rectangle rectangle = jxMapViewer.getViewportBounds(); 28 | int buttonX = (int) ( point.getX() - rectangle.getX() ); 29 | int buttonY = (int) ( point.getY() - rectangle.getY() ); 30 | JComponent button = waypoint.getComponent(); 31 | button.setLocation( buttonX - button.getWidth() / 2, buttonY - button.getHeight() / 2 ); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/jxmapviewer/NodePainter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation.jxmapviewer; 7 | 8 | import java.awt.BasicStroke; 9 | import java.awt.Color; 10 | import java.awt.Graphics2D; 11 | import java.awt.Rectangle; 12 | import java.awt.RenderingHints; 13 | import java.awt.geom.Point2D; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | import org.jdesktop.swingx.JXMapViewer; 17 | import org.jdesktop.swingx.mapviewer.GeoPosition; 18 | import org.jdesktop.swingx.painter.Painter; 19 | 20 | /** 21 | * Painter for the node 22 | * 23 | * @author Michael Blaha {@literal } 24 | */ 25 | public class NodePainter implements Painter { 26 | 27 | private Color color = Color.RED; 28 | private final boolean antiAlias = true; 29 | 30 | private final List track; 31 | 32 | /** 33 | * @param track the track 34 | */ 35 | public NodePainter( List track ) { 36 | // copy the list so that changes in the 37 | // original list do not have an effect here 38 | this.track = new ArrayList<>( track ); 39 | } 40 | 41 | @Override 42 | public void paint( Graphics2D g, JXMapViewer map, int w, int h ) { 43 | g = (Graphics2D) g.create(); 44 | 45 | // convert from viewport to world bitmap 46 | Rectangle rect = map.getViewportBounds(); 47 | g.translate( -rect.x, -rect.y ); 48 | 49 | if ( antiAlias ) { 50 | g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); 51 | } 52 | 53 | // do the drawing 54 | g.setColor( Color.BLACK ); 55 | g.setStroke( new BasicStroke( 4 ) ); 56 | 57 | drawRoute( g, map ); 58 | 59 | // do the drawing again 60 | g.setColor( color ); 61 | g.setStroke( new BasicStroke( 2 ) ); 62 | 63 | drawRoute( g, map ); 64 | 65 | g.dispose(); 66 | } 67 | 68 | public void setColor( Color color ) { 69 | this.color = color; 70 | } 71 | 72 | /** 73 | * @param g the graphics object 74 | * @param map the map 75 | */ 76 | private void drawRoute( Graphics2D g, JXMapViewer map ) { 77 | int lastX = 0; 78 | int lastY = 0; 79 | 80 | boolean first = true; 81 | 82 | int counter = 0; 83 | for ( GeoPosition gp : track ) { 84 | // convert geo-coordinate to world bitmap pixel 85 | Point2D pt = map.getTileFactory().geoToPixel( gp, map.getZoom() ); 86 | 87 | g.drawString( Integer.toString( counter++ ), (int) pt.getX(), (int) pt.getY() ); 88 | // if ( first ) { 89 | // first = false; 90 | // } else { 91 | // g.drawLine( lastX, lastY, (int) pt.getX(), (int) pt.getY() ); 92 | // } 93 | 94 | lastX = (int) pt.getX(); 95 | lastY = (int) pt.getY(); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/presentation/jxmapviewer/RoutePainter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.presentation.jxmapviewer; 7 | 8 | import java.awt.BasicStroke; 9 | import java.awt.Color; 10 | import java.awt.Graphics2D; 11 | import java.awt.Rectangle; 12 | import java.awt.RenderingHints; 13 | import java.awt.geom.Point2D; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | import org.jdesktop.swingx.JXMapViewer; 17 | import org.jdesktop.swingx.mapviewer.GeoPosition; 18 | import org.jdesktop.swingx.painter.Painter; 19 | 20 | /** 21 | * 22 | * Paints a route 23 | * 24 | * @author Martin Steiger 25 | * @author Michael Blaha {@literal } 26 | */ 27 | public class RoutePainter implements Painter { 28 | 29 | private Color color = Color.RED; 30 | private final boolean antiAlias = true; 31 | private final List track; 32 | 33 | /** 34 | * @param track the track 35 | */ 36 | public RoutePainter( List track ) { 37 | // copy the list so that changes in the 38 | // original list do not have an effect here 39 | this.track = new ArrayList<>( track ); 40 | } 41 | 42 | @Override 43 | public void paint( Graphics2D g, JXMapViewer map, int w, int h ) { 44 | g = (Graphics2D) g.create(); 45 | 46 | // convert from viewport to world bitmap 47 | Rectangle rect = map.getViewportBounds(); 48 | g.translate( -rect.x, -rect.y ); 49 | 50 | if ( antiAlias ) { 51 | g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); 52 | } 53 | 54 | // do the drawing 55 | g.setColor( Color.BLACK ); 56 | g.setStroke( new BasicStroke( 4 ) ); 57 | 58 | drawRoute( g, map ); 59 | 60 | // do the drawing again 61 | g.setColor( color ); 62 | g.setStroke( new BasicStroke( 2 ) ); 63 | 64 | drawRoute( g, map ); 65 | 66 | g.dispose(); 67 | } 68 | 69 | public void setColor( Color color ) { 70 | this.color = color; 71 | } 72 | 73 | /** 74 | * @param g the graphics object 75 | * @param map the map 76 | */ 77 | private void drawRoute( Graphics2D g, JXMapViewer map ) { 78 | int lastX = 0; 79 | int lastY = 0; 80 | 81 | boolean first = true; 82 | 83 | for ( GeoPosition gp : track ) { 84 | // convert geo-coordinate to world bitmap pixel 85 | Point2D pt = map.getTileFactory().geoToPixel( gp, map.getZoom() ); 86 | 87 | if ( first ) { 88 | first = false; 89 | } else { 90 | g.drawLine( lastX, lastY, (int) pt.getX(), (int) pt.getY() ); 91 | } 92 | 93 | lastX = (int) pt.getX(); 94 | lastY = (int) pt.getY(); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/CollectionUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | /** 13 | * Utility class for frequent operations with collections. 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public class CollectionUtils { 18 | 19 | /** 20 | * Returns list from a map referenced by the given key. If the list is not 21 | * present under the given key, a new list is created, inserted into the map 22 | * and returned. In other words, it ensures retrieval of a list for the 23 | * given key. 24 | * 25 | * @param key type of the map 26 | * @param value type of the list (which acts as a value in the map) 27 | * @param map key-value map, where value is of type {@link List} 28 | * @param node key 29 | * @return non-null {@link List} for the given key 30 | */ 31 | public static List getList( Map> map, Key node ) { 32 | List list = map.get( node ); 33 | if ( list == null ) { 34 | list = new ArrayList<>(); 35 | map.put( node, list ); 36 | } 37 | return list; 38 | } 39 | 40 | /** 41 | * Converts {@link List} of Integers into an int array 42 | * 43 | * @param list list to be converted 44 | * @return int[] representation 45 | */ 46 | public static int[] toIntArray( List list ) { 47 | int[] array = new int[list.size()]; 48 | for ( int i = 0; i < list.size(); i++ ) { 49 | array[i] = list.get( i ); 50 | } 51 | return array; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/CommunicationUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils; 7 | 8 | import cz.certicon.routing.model.entity.Coordinate; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Utilities for communication 14 | * 15 | * @author Michael Blaha {@literal } 16 | */ 17 | public class CommunicationUtils { 18 | 19 | /** 20 | * Serves for decoding polyline string into the list of coordinates. 21 | * 22 | * @param encoded polyline coordinate string 23 | * @return list of decoded coordinates 24 | */ 25 | private List decodePolyline( String encoded ) { 26 | List poly = new ArrayList(); 27 | int index = 0, len = encoded.length(); 28 | int lat = 0, lng = 0; 29 | while ( index < len ) { 30 | int b, shift = 0, result = 0; 31 | do { 32 | b = encoded.charAt( index++ ) - 63; 33 | result |= ( b & 0x1f ) << shift; 34 | shift += 5; 35 | } while ( b >= 0x20 ); 36 | int dlat = ( ( result & 1 ) != 0 ? ~( result >> 1 ) : ( result >> 1 ) ); 37 | lat += dlat; 38 | shift = 0; 39 | result = 0; 40 | do { 41 | b = encoded.charAt( index++ ) - 63; 42 | result |= ( b & 0x1f ) << shift; 43 | shift += 5; 44 | } while ( b >= 0x20 ); 45 | int dlng = ( ( result & 1 ) != 0 ? ~( result >> 1 ) : ( result >> 1 ) ); 46 | lng += dlng; 47 | Coordinate p = new Coordinate( ( ( (double) lat / 1E5 ) ), 48 | ( ( (double) lng / 1E5 ) ) ); 49 | poly.add( p ); 50 | } 51 | return poly; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/SpeedUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils; 7 | 8 | /** 9 | * Speed utility class. 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public class SpeedUtils { 14 | 15 | private static final double MPH_TO_KPH_RATIO = 1.609; 16 | private static final double KNOTS_TO_KPH_RATIO = 1.852; 17 | 18 | /** 19 | * Converts miles per hour to kilometers per hour 20 | * 21 | * @param mph speed in Miles/Hour 22 | * @return speed in km/h 23 | */ 24 | public static double mphToKmph( double mph ) { 25 | return mph * MPH_TO_KPH_RATIO; 26 | } 27 | 28 | /** 29 | * Converts knots to kilometers per hour 30 | * 31 | * @param knots speed in Knots 32 | * @return speed in km/h 33 | */ 34 | public static double knotToKmph( double knots ) { 35 | return knots * KNOTS_TO_KPH_RATIO; 36 | } 37 | 38 | /** 39 | * Converts kilometers per hour to meters per second 40 | * 41 | * @param kmph speed in km/h 42 | * @return speed in m/s 43 | */ 44 | public static double kmphToMps( double kmph ) { 45 | return kmph / 3.6; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/AbstractChainGroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | import java.util.Iterator; 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | 12 | /** 13 | * Abstract implementation of {@link ChainGroup} interface. Adds implementation 14 | * of the execute operation and next operation. 15 | * 16 | * @author Michael Blaha {@literal } 17 | * @param traveling instance 18 | */ 19 | public abstract class AbstractChainGroup implements ChainGroup { 20 | 21 | private final List> list = new LinkedList<>(); 22 | private Iterator> iterator = null; 23 | 24 | @Override 25 | public void addChainLink( ChainLink cl ) { 26 | list.add( cl ); 27 | } 28 | 29 | @Override 30 | public boolean execute( Traveler t ) { 31 | iterator = list.iterator(); 32 | return next( t ); 33 | } 34 | 35 | @Override 36 | public boolean next( Traveler t ) { 37 | if ( !getIterator().hasNext() ) { 38 | return false; 39 | } 40 | ChainLink next = getIterator().next(); 41 | return executeNext( next, t ); 42 | } 43 | 44 | /** 45 | * Let the extending class choose, whether to call next or not. 46 | * 47 | * @param next the next chain-link in line 48 | * @param traveler traveling object 49 | * @return result of the execution 50 | */ 51 | abstract protected boolean executeNext( ChainLink next, Traveler traveler ); 52 | 53 | protected Iterator> getIterator() { 54 | return iterator; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/AbstractHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * @since 1.X, X > 2 10 | * @author Michael Blaha {@literal } 11 | * @param in 12 | * @param out 13 | */ 14 | public abstract class AbstractHandler implements Handler { 15 | 16 | private Handler next; 17 | 18 | @Override 19 | public Handler getNext() { 20 | return next; 21 | } 22 | 23 | @Override 24 | public void setNext( Handler next ) { 25 | this.next = next; 26 | } 27 | 28 | @Override 29 | public Out process( In input, Out output ) { 30 | output = handle( input, output ); 31 | if ( next != null ) { 32 | return next.process( input, output ); 33 | } 34 | return output; 35 | } 36 | 37 | protected Out returnOutput( Out output ) { 38 | return output; 39 | } 40 | 41 | protected Out continueProcessing( In input, Out output ) { 42 | output = handle( input, output ); 43 | if ( next != null ) { 44 | return next.process( input, output ); 45 | } 46 | return output; 47 | } 48 | 49 | protected abstract Out handle( In input, Out output ); 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/ChainGroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * Group of chain-links, which acts as a single chain-link on the outside 10 | * 11 | * @author Michael Blaha {@literal } 12 | * @param traveling instance 13 | */ 14 | public interface ChainGroup extends ChainLink { 15 | 16 | /** 17 | * Adds chain-link into this group 18 | * 19 | * @param chainlink chain-link to be added 20 | */ 21 | public void addChainLink( ChainLink chainlink ); 22 | 23 | /** 24 | * Calls next chain-link in this group, returns result of the sub-link's 25 | * execute operation or false if no more chain-links are present. The 26 | * concrete behavior is based on the implementation. 27 | * 28 | * @param traveler traveling object 29 | * @return result of execute operation or false if no more chain-links are 30 | * present 31 | */ 32 | public boolean next( Traveller traveler ); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/ChainLink.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * Link of the chain, which is able to execute a single operation on the 10 | * traveler. Links can be grouped into {@link ChainGroup}. Implementations offer 11 | * OR {@link OrChainGroup} or XOR {@link XorChainGroup} functionality. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param traveling instance 15 | */ 16 | public interface ChainLink { 17 | 18 | /** 19 | * Execute the chain-link operation 20 | * 21 | * @param t traveler object 22 | * @return true if the operation was executed, false otherwise 23 | */ 24 | public boolean execute( Traveler t ); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/ChainOfResponsibility.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * Need to think this through first. TODO 10 | * 11 | * @since 1.X, X > 2 12 | * @author Michael Blaha {@literal } 13 | * @param in 14 | * @param out 15 | */ 16 | public interface ChainOfResponsibility { 17 | 18 | public Out process( In input, Out output ); 19 | 20 | public ChainOfResponsibility add( Handler handler ); 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/Handler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * 10 | * @param 11 | * @param 12 | * @since 1.X, X > 2 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public interface Handler { 16 | public Out process(In input, Out output); 17 | public Handler getNext(); 18 | public void setNext(Handler handler); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/LinkedChainOfResponsibility.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * 10 | * @since 1.X, X > 2 11 | * @author Michael Blaha {@literal } 12 | * @param in 13 | * @param out 14 | */ 15 | public class LinkedChainOfResponsibility implements ChainOfResponsibility { 16 | 17 | private Handler first; 18 | 19 | @Override 20 | public Out process( In input, Out output ) { 21 | return first.process( input, output ); 22 | } 23 | 24 | @Override 25 | public ChainOfResponsibility add( Handler handler ) { 26 | if ( first == null ) { 27 | first = handler; 28 | } else { 29 | Handler prev = first; 30 | Handler current = first; 31 | while ( current != null ) { 32 | prev = current; 33 | current = current.getNext(); 34 | } 35 | prev.setNext( handler ); 36 | } 37 | return this; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/OrChainGroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * OR implementation of the {@link ChainGroup} interface. Executes all the 10 | * sublinks. Returns true if ANY of the sublinks' executions is true. 11 | * 12 | * @author Michael Blaha {@literal } 13 | * @param traveling instance 14 | */ 15 | public class OrChainGroup extends AbstractChainGroup { 16 | 17 | @Override 18 | protected boolean executeNext( ChainLink next, Traveller t ) { 19 | return next.execute( t ); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/cor/XorChainGroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.cor; 7 | 8 | /** 9 | * XOR implementation of the {@link ChainGroup} interface. Executes only until 10 | * the first true execution is met. Returns true, if such execution was found, 11 | * false otherwise. 12 | * 13 | * @author Michael Blaha {@literal } 14 | * @param traveling instance 15 | */ 16 | public class XorChainGroup extends AbstractChainGroup { 17 | 18 | @Override 19 | protected boolean executeNext( ChainLink next, Traveller t ) { 20 | if ( !next.execute( t ) ) { 21 | return next( t ); 22 | } else { 23 | return true; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/debug/Log.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.debug; 7 | 8 | import java.io.IOException; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | import java.util.logging.FileHandler; 12 | import java.util.logging.Level; 13 | import java.util.logging.Logger; 14 | 15 | /** 16 | * Logging class offering somewhat Android-like printing tools. Logs into .log 17 | * files. 18 | * 19 | * @author Michael Blaha {@literal } 20 | */ 21 | public class Log { 22 | 23 | private static final Map LOGGERS_MAP = new HashMap<>(); 24 | 25 | /** 26 | * Log debug message with the given tag (logs into a file [tag].log). Does 27 | * not add end of line. 28 | * 29 | * @param tag name of the target file 30 | * @param message message to be logged 31 | */ 32 | public static void d( String tag, String message ) { 33 | getLogger( tag ).info( message ); 34 | } 35 | 36 | /** 37 | * Log debug message with the given tag (logs into a file [tag].log). Adds 38 | * end of line. 39 | * 40 | * @param tag name of the target file 41 | * @param message message to be logged 42 | */ 43 | public static void dln( String tag, String message ) { 44 | String msg = message + "\n"; 45 | getLogger( tag ).info( msg ); 46 | } 47 | 48 | private static Logger getLogger( String tag ) { 49 | Logger logger = LOGGERS_MAP.get( tag ); 50 | if ( logger == null ) { 51 | try { 52 | FileHandler fileHandler = new FileHandler( tag + ".log" ); 53 | fileHandler.setFormatter( new PlainTextFormatter() ); 54 | logger = Logger.getLogger( tag ); 55 | logger.addHandler( fileHandler ); 56 | LOGGERS_MAP.put( tag, logger ); 57 | } catch ( IOException | SecurityException ex ) { 58 | Logger.getLogger( Log.class.getName() ).log( Level.SEVERE, null, ex ); 59 | } 60 | } 61 | return logger; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/debug/PlainTextFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.debug; 7 | 8 | import java.util.logging.Formatter; 9 | import java.util.logging.LogRecord; 10 | 11 | /** 12 | * Extension to {@link Formatter}. Formats records into plain text. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public class PlainTextFormatter extends Formatter { 17 | 18 | @Override 19 | public String format( LogRecord record ) { 20 | return record.getMessage(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/efficient/BitArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.efficient; 7 | 8 | /** 9 | * Efficient array of bits. 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public interface BitArray { 14 | 15 | /** 16 | * Initializes the array with the given size 17 | * 18 | * @param size given size 19 | */ 20 | public void init( int size ); 21 | 22 | /** 23 | * Sets the value at the given index to the given value 24 | * 25 | * @param index target index 26 | * @param value given value 27 | */ 28 | public void set( int index, boolean value ); 29 | 30 | /** 31 | * Returns value at the given index 32 | * 33 | * @param index target index 34 | * @return value at the index 35 | */ 36 | public boolean get( int index ); 37 | 38 | /** 39 | * Returns size of this array 40 | * 41 | * @return 42 | */ 43 | public int size(); 44 | 45 | /** 46 | * Clears this array (sets all to false) 47 | */ 48 | public void clear(); 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/efficient/IntLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.efficient; 7 | 8 | import gnu.trove.iterator.TIntIterator; 9 | 10 | /** 11 | * Efficient integer linked list. From the outside it can be only added to. It 12 | * supports reading and removal via iterator. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public class IntLinkedList { 17 | 18 | private Entry first = null; 19 | private Entry last = null; 20 | private int size = 0; 21 | 22 | /** 23 | * Add number to the end of list 24 | * 25 | * @param n number to be added 26 | */ 27 | public void add( int n ) { 28 | if ( last == null ) { 29 | first = last = new Entry( n ); 30 | } else { 31 | last.next = new Entry( n ); 32 | last = last.next; 33 | } 34 | size++; 35 | } 36 | 37 | /** 38 | * Returns iterator 39 | * 40 | * @return iterator 41 | */ 42 | public TIntIterator iterator() { 43 | return new IntLinkedListIterator(); 44 | } 45 | 46 | private static class Entry { 47 | 48 | public final int value; 49 | public Entry next; 50 | 51 | public Entry( int value ) { 52 | this.value = value; 53 | this.next = null; 54 | } 55 | } 56 | 57 | private class IntLinkedListIterator implements TIntIterator { 58 | 59 | private Entry current = null; 60 | private Entry previous = null; 61 | 62 | public IntLinkedListIterator() { 63 | } 64 | 65 | @Override 66 | public int next() { 67 | previous = current; 68 | current = ( current == null ) ? first : current.next; 69 | return current.value; 70 | } 71 | 72 | @Override 73 | public boolean hasNext() { 74 | return ( current != null ) ? current.next != null : first != null; 75 | } 76 | 77 | @Override 78 | public void remove() { 79 | if ( previous == null ) { 80 | first = first.next; 81 | } else { 82 | previous.next = current.next; 83 | } 84 | } 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/efficient/LongBitArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.efficient; 7 | 8 | import cz.certicon.routing.utils.EffectiveUtils; 9 | 10 | /** 11 | * Implementation of {@link BitArray} using long as bottom layer data type. 12 | * 13 | * @author Michael Blaha {@literal } 14 | */ 15 | public class LongBitArray implements BitArray { 16 | 17 | private final static int ADDRESS_BITS_PER_WORD = 6; 18 | private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD; 19 | private final static int BIT_INDEX_MASK = BITS_PER_WORD - 1; 20 | 21 | private static final long WORD_MASK = 0xffffffffffffffffL; 22 | 23 | private long[] array; 24 | private long[] resetArray; 25 | private int size; 26 | 27 | public LongBitArray() { 28 | } 29 | 30 | public LongBitArray( int size ) { 31 | init( size ); 32 | } 33 | 34 | @Override 35 | public final void init( int size ) { 36 | this.size = size; 37 | int arraySize = wordIndex( size - 1 ) + 1; 38 | array = new long[arraySize]; 39 | resetArray = new long[arraySize]; 40 | } 41 | 42 | @Override 43 | public void set( int index, boolean value ) { 44 | if ( value ) { 45 | array[wordIndex( index )] |= ( 1L << index ); 46 | } else { 47 | array[wordIndex( index )] &= ~( 1L << index ); 48 | } 49 | } 50 | 51 | @Override 52 | public boolean get( int index ) { 53 | return ( ( array[wordIndex( index )] & ( 1L << index ) ) != 0 ); 54 | } 55 | 56 | private static int wordIndex( int bitIndex ) { 57 | return bitIndex >> ADDRESS_BITS_PER_WORD; 58 | } 59 | 60 | @Override 61 | public void clear() { 62 | EffectiveUtils.copyArray( resetArray, array ); 63 | } 64 | 65 | @Override 66 | public int size() { 67 | return size; 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | StringBuilder sb = new StringBuilder(); 73 | sb.append( "[" ); 74 | for ( int i = 0; i < size; i++ ) { 75 | sb.append( get( i ) ? "1" : "0" ).append( ", " ); 76 | } 77 | if ( sb.length() > 3 ) { 78 | sb.replace( sb.length() - 2, sb.length(), "" ); 79 | } 80 | sb.append( "]" ); 81 | return sb.toString(); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/measuring/MemoryUnits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.measuring; 7 | 8 | /** 9 | * Enumeration for memory units. Supports conversion and string representation. 10 | * 11 | * @author Michael Blaha {@literal } 12 | */ 13 | public enum MemoryUnits { 14 | BYTES( 1, "B" ), KILOBYTES( BYTES.getDivisor() * 1000, "KB" ), MEGABYTES( KILOBYTES.getDivisor() * 1000, "MB" ), GIGABYTES( MEGABYTES.getDivisor() * 1000, "GB" ); 15 | 16 | private final long byteDivisor; 17 | private final String unit; 18 | 19 | private MemoryUnits( long byteDivisor, String unit ) { 20 | this.byteDivisor = byteDivisor; 21 | this.unit = unit; 22 | } 23 | 24 | private long getDivisor() { 25 | return byteDivisor; 26 | } 27 | 28 | /** 29 | * Converts bytes to current units 30 | * 31 | * @param bytes value in bytes 32 | * @return value in current units 33 | */ 34 | public long fromBytes( long bytes ) { 35 | return bytes / byteDivisor; 36 | } 37 | 38 | /** 39 | * Converts current units to bytes 40 | * 41 | * @param value value in current units 42 | * @return value in bytes 43 | */ 44 | public long toBytes( long value ) { 45 | return value * byteDivisor; 46 | } 47 | 48 | /** 49 | * Returns string representation of current units 50 | * 51 | * @return string representation of current units 52 | */ 53 | public String getUnit() { 54 | return unit; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/measuring/StatsLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.measuring; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * Logging class for statistic counters. 13 | * 14 | * @author Michael Blaha {@literal } 15 | */ 16 | public class StatsLogger { 17 | 18 | private static final Map STATS_MAP = new HashMap<>(); 19 | 20 | /** 21 | * Log given {@link Command} for given {@link Statistic} data type 22 | * 23 | * @param statistic given statistic data type 24 | * @param command given command 25 | */ 26 | public static void log( Statistic statistic, Command command ) { 27 | STATS_MAP.put( statistic, command.execute( getValue( statistic ) ) ); 28 | } 29 | 30 | /** 31 | * Return value of the given {@link Statistic} counter 32 | * 33 | * @param statistic given statistic data type 34 | * @return counter 35 | */ 36 | public static int getValue( Statistic statistic ) { 37 | Integer val = STATS_MAP.get( statistic ); 38 | if ( val == null ) { 39 | val = 0; 40 | STATS_MAP.put( statistic, val ); 41 | } 42 | return val; 43 | } 44 | 45 | /** 46 | * Interface for commands as well as wrapping class for predefined commands. 47 | */ 48 | public interface Command { 49 | 50 | int execute( int input ); 51 | 52 | /** 53 | * Increment given counter 54 | */ 55 | public static final Command INCREMENT = new Command() { 56 | @Override 57 | public int execute( int input ) { 58 | return input + 1; 59 | } 60 | }; 61 | 62 | /** 63 | * Reset given counter 64 | */ 65 | public static final Command RESET = new Command() { 66 | @Override 67 | public int execute( int input ) { 68 | return 0; 69 | } 70 | }; 71 | 72 | /** 73 | * Decrement given counter 74 | */ 75 | public static final Command DECREMENT = new Command() { 76 | @Override 77 | public int execute( int input ) { 78 | return input - 1; 79 | } 80 | }; 81 | } 82 | 83 | /** 84 | * Available statistic data types 85 | */ 86 | public static enum Statistic { 87 | /** 88 | * Amount of examined (visited) nodes during algorithm execution 89 | */ 90 | NODES_EXAMINED, 91 | /** 92 | * Amount of examined (visited) edges during algorithm execution 93 | */ 94 | EDGES_EXAMINED; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/cz/certicon/routing/utils/measuring/TimeLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.utils.measuring; 7 | 8 | import cz.certicon.routing.model.basic.TimeUnits; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * Logging class for execution times. See 14 | * {@link #getTimeMeasurement(cz.certicon.routing.utils.measuring.TimeLogger.Event) getTimeMeasurement(Event)} 15 | * method for elapsed time retrieval. 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class TimeLogger { 20 | 21 | private static final Map TIME_MAP = new HashMap<>(); 22 | private static TimeUnits timeUnits = TimeUnits.MILLISECONDS; 23 | 24 | /** 25 | * Set time units globally => all the timers will return values in these 26 | * units 27 | * 28 | * @param timeUnits given time units 29 | */ 30 | public static void setTimeUnits( TimeUnits timeUnits ) { 31 | TimeLogger.timeUnits = timeUnits; 32 | for ( TimeMeasurement value : TIME_MAP.values() ) { 33 | value.setTimeUnits( timeUnits ); 34 | } 35 | } 36 | 37 | /** 38 | * Log given {@link Command} for given {@link Event} type 39 | * 40 | * @param event given event type 41 | * @param command given command 42 | */ 43 | public static void log( Event event, Command command ) { 44 | command.execute( getTimeMeasurement( event ) ); 45 | } 46 | 47 | /** 48 | * Returns {@link TimeMeasurement} object for the given event. Extract 49 | * elapsed {@link Time} via 50 | * {@link TimeMeasurement#getTime() timeMeasurement.getTime()} 51 | * 52 | * @param event given event 53 | * @return time measurement object 54 | */ 55 | public static TimeMeasurement getTimeMeasurement( Event event ) { 56 | TimeMeasurement time = TIME_MAP.get( event ); 57 | if ( time == null ) { 58 | time = new TimeMeasurement(); 59 | time.setTimeUnits( timeUnits ); 60 | TIME_MAP.put( event, time ); 61 | } 62 | return time; 63 | } 64 | 65 | /** 66 | * Enumeration for event types 67 | */ 68 | public static enum Event { 69 | PREPROCESSING, GRAPH_LOADING, PREPROCESSED_LOADING, NODE_SEARCHING, ROUTING, ROUTE_BUILDING, PATH_LOADING; 70 | } 71 | 72 | /** 73 | * Interface for commands as well as wrapping class for predefined commands. 74 | */ 75 | public static enum Command { 76 | /** 77 | * Start given time measurement 78 | */ 79 | START { 80 | @Override 81 | void execute( TimeMeasurement timeMeasurement ) { 82 | timeMeasurement.start(); 83 | } 84 | }, 85 | /** 86 | * Stop given time measurement 87 | */ 88 | STOP { 89 | @Override 90 | void execute( TimeMeasurement timeMeasurement ) { 91 | timeMeasurement.stop(); 92 | } 93 | }, 94 | /** 95 | * Pause given time measurement 96 | */ 97 | PAUSE { 98 | @Override 99 | void execute( TimeMeasurement timeMeasurement ) { 100 | timeMeasurement.pause(); 101 | } 102 | }, 103 | /** 104 | * Continue given time measurement 105 | */ 106 | CONTINUE { 107 | @Override 108 | void execute( TimeMeasurement timeMeasurement ) { 109 | timeMeasurement.continue_(); 110 | } 111 | }; 112 | 113 | abstract void execute( TimeMeasurement timeMeasurement ); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/resources/cz/certicon/routing/data/basic/database/database_connection.properties: -------------------------------------------------------------------------------- 1 | driver=org.postgresql.Driver 2 | url=jdbc:postgresql://localhost:5432/postgis_prague 3 | user=postgres 4 | password=password 5 | -------------------------------------------------------------------------------- /src/main/resources/cz/certicon/routing/data/osm/osm_defaultspeed_zone_type.properties: -------------------------------------------------------------------------------- 1 | # To change this license header, choose License Headers in Project Properties. 2 | # To change this template file, choose Tools | Templates 3 | # and open the template in the editor. 4 | cz_motorway=130 5 | cz_motorway-link=130 6 | cz_motorway-inside=80 7 | cz_motorway-link-inside=80 8 | cz_trunk=90 9 | cz_trunk-inside=50 10 | cz_trunk-link=90 11 | cz_primary=90 12 | cz_primary-inside=50 13 | cz_primary-link=90 14 | cz_secondary=90 15 | cz_secondary-inside=50 16 | cz_secondary-link=90 17 | cz_tertiary=90 18 | cz_tertiary-inside=50 19 | cz_tertiary-link=90 20 | cz_unclassified=90 21 | cz_unclassified-inside=50 22 | cz_residential=90 23 | cz_residential-inside=50 24 | cz_living_street=20 25 | cz_living_street-inside=20 26 | cz_service=20 27 | cz_service-inside=20 28 | -------------------------------------------------------------------------------- /src/main/resources/cz/certicon/routing/data/osm/osm_maxspeed_source_zones.properties: -------------------------------------------------------------------------------- 1 | # To change this license header, choose License Headers in Project Properties. 2 | # To change this template file, choose Tools | Templates 3 | # and open the template in the editor. 4 | at_urban= 5 | cz_motorway=130 6 | cz_motorroad=110 7 | cz_rural=90 8 | cz_urban=50 9 | de_motorway= 10 | de_rural=100 11 | de_urban=50 12 | fr_rural=90 13 | fr_urban=50 14 | it_rural=90 15 | it_motorway=130 16 | it_urban=50 17 | jp_nsl=60 18 | jp_express=100 19 | no_rural=80 20 | no_urban=50 21 | on_urban=50 22 | on_rural=80 23 | ro_motorway=130 24 | ro_rural=90 25 | ro_trunk=100 26 | ro_urban=50 27 | ru_rural=90 28 | ru_urban=60 29 | gb_motorway=70 mph 30 | gb_nsl_dual=70 mph 31 | gb_nsl_single=60 mph 32 | uk_motorway=70 mph 33 | uk_nsl_dual=70 mph 34 | uk_nsl_single=60 mph 35 | -------------------------------------------------------------------------------- /src/test/java/cz/certicon/routing/model/basic/LengthTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | import org.junit.After; 9 | import org.junit.AfterClass; 10 | import org.junit.Before; 11 | import org.junit.BeforeClass; 12 | import org.junit.Test; 13 | import static org.junit.Assert.*; 14 | 15 | /** 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class LengthTest { 20 | 21 | public LengthTest() { 22 | } 23 | 24 | @BeforeClass 25 | public static void setUpClass() { 26 | } 27 | 28 | @AfterClass 29 | public static void tearDownClass() { 30 | } 31 | 32 | @Before 33 | public void setUp() { 34 | } 35 | 36 | @After 37 | public void tearDown() { 38 | } 39 | 40 | /** 41 | * Test of getLengthUnits method, of class Length. 42 | */ 43 | @Test 44 | public void testGetLengthUnits() { 45 | System.out.println( "getLengthUnits" ); 46 | Length instance = new Length(LengthUnits.METERS, 5); 47 | LengthUnits expResult = LengthUnits.METERS; 48 | LengthUnits result = instance.getLengthUnits(); 49 | assertEquals( expResult, result ); 50 | } 51 | 52 | /** 53 | * Test of getNanoseconds method, of class Length. 54 | */ 55 | @Test 56 | public void testGetNanoseconds() { 57 | System.out.println( "getNanometers" ); 58 | Length instance = new Length(LengthUnits.METERS, 5); 59 | long expResult = 5000000000L; 60 | long result = instance.getNanometers(); 61 | assertEquals( expResult, result ); 62 | } 63 | 64 | /** 65 | * Test of getLength method, of class Length. 66 | */ 67 | @Test 68 | public void testGetLength() { 69 | System.out.println( "getLength" ); 70 | Length instance = new Length(LengthUnits.METERS, 5); 71 | long expResult = 5L; 72 | long result = instance.getLength(); 73 | assertEquals( expResult, result ); 74 | } 75 | 76 | /** 77 | * Test of getUnit method, of class Length. 78 | */ 79 | @Test 80 | public void testGetUnit() { 81 | System.out.println( "getUnit" ); 82 | Length instance = new Length(LengthUnits.METERS, 5); 83 | String expResult = "m"; 84 | String result = instance.getUnit(); 85 | assertEquals( expResult, result ); 86 | } 87 | 88 | /** 89 | * Test of toString method, of class Length. 90 | */ 91 | @Test 92 | public void testToString() { 93 | System.out.println( "toString" ); 94 | Length instance = new Length(LengthUnits.METERS, 50); 95 | String expResult = "50"; 96 | String result = instance.toString(); 97 | assertEquals( expResult, result ); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/cz/certicon/routing/model/basic/TimeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package cz.certicon.routing.model.basic; 7 | 8 | import org.junit.After; 9 | import org.junit.AfterClass; 10 | import org.junit.Before; 11 | import org.junit.BeforeClass; 12 | import org.junit.Test; 13 | import static org.junit.Assert.*; 14 | 15 | /** 16 | * 17 | * @author Michael Blaha {@literal } 18 | */ 19 | public class TimeTest { 20 | 21 | public TimeTest() { 22 | } 23 | 24 | @BeforeClass 25 | public static void setUpClass() { 26 | } 27 | 28 | @AfterClass 29 | public static void tearDownClass() { 30 | } 31 | 32 | @Before 33 | public void setUp() { 34 | } 35 | 36 | @After 37 | public void tearDown() { 38 | } 39 | 40 | /** 41 | * Test of getTimeUnits method, of class Time. 42 | */ 43 | @Test 44 | public void testGetTimeUnits() { 45 | System.out.println( "getTimeUnits" ); 46 | Time instance = new Time( TimeUnits.SECONDS, 5 ); 47 | TimeUnits expResult = TimeUnits.SECONDS; 48 | TimeUnits result = instance.getTimeUnits(); 49 | assertEquals( expResult, result ); 50 | } 51 | 52 | /** 53 | * Test of getNanoseconds method, of class Time. 54 | */ 55 | @Test 56 | public void testGetNanoseconds() { 57 | System.out.println( "getNanoseconds" ); 58 | Time instance = new Time( TimeUnits.SECONDS, 5 ); 59 | long expResult = 5000000000L; 60 | long result = instance.getNanoseconds(); 61 | assertEquals( expResult, result ); 62 | } 63 | 64 | /** 65 | * Test of getTime method, of class Time. 66 | */ 67 | @Test 68 | public void testGetTime() { 69 | System.out.println( "getTime" ); 70 | Time instance = new Time( TimeUnits.SECONDS, 5 ); 71 | long expResult = 5L; 72 | long result = instance.getTime(); 73 | assertEquals( expResult, result ); 74 | } 75 | 76 | /** 77 | * Test of getUnit method, of class Time. 78 | */ 79 | @Test 80 | public void testGetUnit() { 81 | System.out.println( "getUnit" ); 82 | Time instance = new Time( TimeUnits.SECONDS, 5 ); 83 | String expResult = "s"; 84 | String result = instance.getUnit(); 85 | assertEquals( expResult, result ); 86 | } 87 | 88 | /** 89 | * Test of add method, of class Time. 90 | */ 91 | @Test 92 | public void testAdd() { 93 | System.out.println( "add" ); 94 | Time time = new Time( TimeUnits.MINUTES, 3 ); 95 | Time instance = new Time( TimeUnits.SECONDS, 5 ); 96 | Time expResult = new Time( TimeUnits.SECONDS, 3 * 60 + 5 ); 97 | Time result = instance.add( time ); 98 | assertEquals( expResult, result ); 99 | } 100 | 101 | /** 102 | * Test of divide method, of class Time. 103 | */ 104 | @Test 105 | public void testDivide() { 106 | System.out.println( "divide" ); 107 | long divisor = 4L; 108 | Time instance = new Time( TimeUnits.SECONDS, 50 ); 109 | Time expResult = new Time( TimeUnits.SECONDS, 50 / 4 ); 110 | Time result = instance.divide( divisor ); 111 | assertEquals( expResult, result ); 112 | } 113 | 114 | /** 115 | * Test of toString method, of class Time. 116 | */ 117 | @Test 118 | public void testToString() { 119 | System.out.println( "toString" ); 120 | Time instance = new Time( TimeUnits.SECONDS, 50 ); 121 | String expResult = "50"; 122 | String result = instance.toString(); 123 | assertEquals( expResult, result ); 124 | } 125 | 126 | } 127 | --------------------------------------------------------------------------------