forked from graphhopper/graphhopper
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGraphHopper.java
More file actions
1519 lines (1331 loc) · 75 KB
/
GraphHopper.java
File metadata and controls
1519 lines (1331 loc) · 75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper;
import com.bedatadriven.jackson.datatype.jts.JtsModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.graphhopper.config.CHProfile;
import com.graphhopper.config.LMProfile;
import com.graphhopper.config.Profile;
import com.graphhopper.reader.dem.*;
import com.graphhopper.reader.osm.OSMReader;
import com.graphhopper.reader.osm.RestrictionTagParser;
import com.graphhopper.reader.osm.conditional.DateRangeParser;
import com.graphhopper.routing.*;
import com.graphhopper.routing.ch.CHPreparationHandler;
import com.graphhopper.routing.ch.PrepareContractionHierarchies;
import com.graphhopper.routing.ev.*;
import com.graphhopper.routing.lm.LMConfig;
import com.graphhopper.routing.lm.LMPreparationHandler;
import com.graphhopper.routing.lm.LandmarkStorage;
import com.graphhopper.routing.lm.PrepareLandmarks;
import com.graphhopper.routing.matrix.GHMatrixRequest;
import com.graphhopper.routing.matrix.GHMatrixResponse;
import com.graphhopper.routing.matrix.RouterMatrix;
import com.graphhopper.routing.subnetwork.PrepareRoutingSubnetworks;
import com.graphhopper.routing.subnetwork.PrepareRoutingSubnetworks.PrepareJob;
import com.graphhopper.routing.util.*;
import com.graphhopper.routing.util.countryrules.CountryRuleFactory;
import com.graphhopper.routing.util.parsers.*;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.routing.weighting.custom.CustomProfile;
import com.graphhopper.routing.weighting.custom.CustomWeighting;
import com.graphhopper.storage.*;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.storage.index.LocationIndexTree;
import com.graphhopper.util.*;
import com.graphhopper.util.Parameters.Landmark;
import com.graphhopper.util.Parameters.Routing;
import com.graphhopper.util.details.PathDetailsBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.graphhopper.util.GHUtility.readCountries;
import static com.graphhopper.util.Helper.*;
import static com.graphhopper.util.Parameters.Algorithms.RoundTrip;
/**
* Easy to use access point to configure import and (offline) routing.
*
* @author Peter Karich
*/
public class GraphHopper {
private static final Logger logger = LoggerFactory.getLogger(GraphHopper.class);
private MaxSpeedCalculator maxSpeedCalculator;
private final Map<String, Profile> profilesByName = new LinkedHashMap<>();
private final String fileLockName = "gh.lock";
// utils
protected final TranslationMap trMap = new TranslationMap().doImport();
boolean removeZipped = true;
// for country rules:
private CountryRuleFactory countryRuleFactory = null;
// for custom areas:
private String customAreasDirectory = "";
// for graph:
private BaseGraph baseGraph;
private StorableProperties properties;
private EncodingManager encodingManager;
private OSMParsers osmParsers;
private int defaultSegmentSize = -1;
private String ghLocation = "";
private DAType dataAccessDefaultType = DAType.RAM_STORE;
private final LinkedHashMap<String, String> dataAccessConfig = new LinkedHashMap<>();
private boolean sortGraph = false;
private boolean elevation = false;
private LockFactory lockFactory = new NativeFSLockFactory();
private boolean allowWrites = true;
protected boolean fullyLoaded = false;
private final OSMReaderConfig osmReaderConfig = new OSMReaderConfig();
// for routing
protected final RouterConfig routerConfig = new RouterConfig();
// for index
protected LocationIndex locationIndex;
private int preciseIndexResolution = 300;
private int maxRegionSearch = 4;
// subnetworks
private int minNetworkSize = 200;
private int subnetworksThreads = 1;
// residential areas
private double residentialAreaRadius = 400;
private double residentialAreaSensitivity = 6000;
private double cityAreaRadius = 1500;
private double cityAreaSensitivity = 1000;
private int urbanDensityCalculationThreads = 0;
// preparation handlers
private final LMPreparationHandler lmPreparationHandler = new LMPreparationHandler();
private final CHPreparationHandler chPreparationHandler = new CHPreparationHandler();
protected Map<String, RoutingCHGraph> chGraphs = Collections.emptyMap();
protected Map<String, LandmarkStorage> landmarks = Collections.emptyMap();
// for data reader
private String osmFile;
private ElevationProvider eleProvider = ElevationProvider.NOOP;
private VehicleEncodedValuesFactory vehicleEncodedValuesFactory = new DefaultVehicleEncodedValuesFactory();
private VehicleTagParserFactory vehicleTagParserFactory = new DefaultVehicleTagParserFactory();
private EncodedValueFactory encodedValueFactory = new DefaultEncodedValueFactory();
private TagParserFactory tagParserFactory = new DefaultTagParserFactory();
protected PathDetailsBuilderFactory pathBuilderFactory = new PathDetailsBuilderFactory();
private String dateRangeParserString = "";
private String encodedValuesString = "";
private String vehiclesString = "";
public GraphHopper setEncodedValuesString(String encodedValuesString) {
this.encodedValuesString = encodedValuesString;
return this;
}
public GraphHopper setVehiclesString(String vehiclesString) {
this.vehiclesString = vehiclesString;
return this;
}
public EncodingManager getEncodingManager() {
if (encodingManager == null)
throw new IllegalStateException("EncodingManager not yet built");
return encodingManager;
}
public OSMParsers getOSMParsers() {
if (osmParsers == null)
throw new IllegalStateException("OSMParsers not yet built");
return osmParsers;
}
public ElevationProvider getElevationProvider() {
return eleProvider;
}
public GraphHopper setElevationProvider(ElevationProvider eleProvider) {
if (eleProvider == null || eleProvider == ElevationProvider.NOOP)
setElevation(false);
else
setElevation(true);
this.eleProvider = eleProvider;
return this;
}
public GraphHopper setPathDetailsBuilderFactory(PathDetailsBuilderFactory pathBuilderFactory) {
this.pathBuilderFactory = pathBuilderFactory;
return this;
}
public PathDetailsBuilderFactory getPathDetailsBuilderFactory() {
return pathBuilderFactory;
}
/**
* Precise location resolution index means also more space (disc/RAM) could be consumed and
* probably slower query times, which would be e.g. not suitable for Android. The resolution
* specifies the tile width (in meter).
*/
public GraphHopper setPreciseIndexResolution(int precision) {
ensureNotLoaded();
preciseIndexResolution = precision;
return this;
}
public GraphHopper setMinNetworkSize(int minNetworkSize) {
ensureNotLoaded();
this.minNetworkSize = minNetworkSize;
return this;
}
/**
* Configures the urban density classification. Each edge will be classified as 'rural','residential' or 'city', {@link UrbanDensity}
*
* @param residentialAreaRadius in meters. The higher this value the longer the calculation will take and the bigger the area for
* which the road density used to identify residential areas is calculated.
* @param residentialAreaSensitivity Use this to find a trade-off between too many roads being classified as residential (too high
* values) and not enough roads being classified as residential (too small values)
* @param cityAreaRadius in meters. The higher this value the longer the calculation will take and the bigger the area for
* which the road density used to identify city areas is calculated. Set this to zero
* to skip the city classification.
* @param cityAreaSensitivity Use this to find a trade-off between too many roads being classified as city (too high values)
* and not enough roads being classified as city (too small values)
* @param threads the number of threads used for the calculation. If this is zero the urban density
* calculation is skipped entirely
*/
public GraphHopper setUrbanDensityCalculation(double residentialAreaRadius, double residentialAreaSensitivity,
double cityAreaRadius, double cityAreaSensitivity, int threads) {
ensureNotLoaded();
this.residentialAreaRadius = residentialAreaRadius;
this.residentialAreaSensitivity = residentialAreaSensitivity;
this.cityAreaRadius = cityAreaRadius;
this.cityAreaSensitivity = cityAreaSensitivity;
this.urbanDensityCalculationThreads = threads;
return this;
}
/**
* Only valid option for in-memory graph and if you e.g. want to disable store on flush for unit
* tests. Specify storeOnFlush to true if you want that existing data will be loaded FROM disc
* and all in-memory data will be flushed TO disc after flush is called e.g. while OSM import.
*
* @param storeOnFlush true by default
*/
public GraphHopper setStoreOnFlush(boolean storeOnFlush) {
ensureNotLoaded();
if (storeOnFlush)
dataAccessDefaultType = DAType.RAM_STORE;
else
dataAccessDefaultType = DAType.RAM;
return this;
}
/**
* Sets the routing profiles that shall be supported by this GraphHopper instance. The (and only the) given profiles
* can be used for routing without preparation and for CH/LM preparation.
* <p>
* Here is an example how to setup two CH profiles and one LM profile (via the Java API)
*
* <pre>
* {@code
* hopper.setProfiles(
* new Profile("my_car").setVehicle("car").setWeighting("shortest"),
* new Profile("your_bike").setVehicle("bike").setWeighting("fastest")
* );
* hopper.getCHPreparationHandler().setCHProfiles(
* new CHProfile("my_car"),
* new CHProfile("your_bike")
* );
* hopper.getLMPreparationHandler().setLMProfiles(
* new LMProfile("your_bike")
* );
* }
* </pre>
* <p>
* See also https://github.com/graphhopper/graphhopper/pull/1922.
*
* @see CHPreparationHandler#setCHProfiles
* @see LMPreparationHandler#setLMProfiles
*/
public GraphHopper setProfiles(Profile... profiles) {
return setProfiles(Arrays.asList(profiles));
}
public GraphHopper setProfiles(List<Profile> profiles) {
if (!profilesByName.isEmpty())
throw new IllegalArgumentException("Cannot initialize profiles multiple times");
if (encodingManager != null)
throw new IllegalArgumentException("Cannot set profiles after EncodingManager was built");
for (Profile profile : profiles) {
Profile previous = this.profilesByName.put(profile.getName(), profile);
if (previous != null)
throw new IllegalArgumentException("Profile names must be unique. Duplicate name: '" + profile.getName() + "'");
}
return this;
}
public List<Profile> getProfiles() {
return new ArrayList<>(profilesByName.values());
}
/**
* Returns the profile for the given profile name, or null if it does not exist
*/
public Profile getProfile(String profileName) {
return profilesByName.get(profileName);
}
/**
* @return true if storing and fetching elevation data is enabled. Default is false
*/
public boolean hasElevation() {
return elevation;
}
/**
* Enable storing and fetching elevation data. Default is false
*/
public GraphHopper setElevation(boolean includeElevation) {
this.elevation = includeElevation;
return this;
}
public String getGraphHopperLocation() {
return ghLocation;
}
/**
* Sets the graphhopper folder.
*/
public GraphHopper setGraphHopperLocation(String ghLocation) {
ensureNotLoaded();
if (ghLocation == null)
throw new IllegalArgumentException("graphhopper location cannot be null");
this.ghLocation = ghLocation;
return this;
}
public String getOSMFile() {
return osmFile;
}
/**
* This file can be an osm xml (.osm), a compressed xml (.osm.zip or .osm.gz) or a protobuf file
* (.pbf).
*/
public GraphHopper setOSMFile(String osmFile) {
ensureNotLoaded();
if (isEmpty(osmFile))
throw new IllegalArgumentException("OSM file cannot be empty.");
this.osmFile = osmFile;
return this;
}
/**
* The underlying graph used in algorithms.
*
* @throws IllegalStateException if graph is not instantiated.
*/
public BaseGraph getBaseGraph() {
if (baseGraph == null)
throw new IllegalStateException("GraphHopper storage not initialized");
return baseGraph;
}
public void setBaseGraph(BaseGraph baseGraph) {
this.baseGraph = baseGraph;
setFullyLoaded();
}
public StorableProperties getProperties() {
return properties;
}
/**
* @return a mapping between profile names and according CH preparations. The map will be empty before loading
* or import.
*/
public Map<String, RoutingCHGraph> getCHGraphs() {
return chGraphs;
}
/**
* @return a mapping between profile names and according landmark preparations. The map will be empty before loading
* or import.
*/
public Map<String, LandmarkStorage> getLandmarks() {
return landmarks;
}
/**
* The location index created from the graph.
*
* @throws IllegalStateException if index is not initialized
*/
public LocationIndex getLocationIndex() {
if (locationIndex == null)
throw new IllegalStateException("LocationIndex not initialized");
return locationIndex;
}
protected void setLocationIndex(LocationIndex locationIndex) {
this.locationIndex = locationIndex;
}
/**
* Sorts the graph which requires more RAM while import. See #12
*/
public GraphHopper setSortGraph(boolean sortGraph) {
ensureNotLoaded();
this.sortGraph = sortGraph;
return this;
}
public boolean isAllowWrites() {
return allowWrites;
}
/**
* Specifies if it is allowed for GraphHopper to write. E.g. for read only filesystems it is not
* possible to create a lock file and so we can avoid write locks.
*/
public GraphHopper setAllowWrites(boolean allowWrites) {
this.allowWrites = allowWrites;
return this;
}
public TranslationMap getTranslationMap() {
return trMap;
}
public GraphHopper setVehicleEncodedValuesFactory(VehicleEncodedValuesFactory factory) {
this.vehicleEncodedValuesFactory = factory;
return this;
}
public EncodedValueFactory getEncodedValueFactory() {
return this.encodedValueFactory;
}
public GraphHopper setEncodedValueFactory(EncodedValueFactory factory) {
this.encodedValueFactory = factory;
return this;
}
public VehicleTagParserFactory getVehicleTagParserFactory() {
return this.vehicleTagParserFactory;
}
public GraphHopper setVehicleTagParserFactory(VehicleTagParserFactory factory) {
this.vehicleTagParserFactory = factory;
return this;
}
public TagParserFactory getTagParserFactory() {
return this.tagParserFactory;
}
public GraphHopper setTagParserFactory(TagParserFactory factory) {
this.tagParserFactory = factory;
return this;
}
public GraphHopper setCustomAreasDirectory(String customAreasDirectory) {
this.customAreasDirectory = customAreasDirectory;
return this;
}
public String getCustomAreasDirectory() {
return this.customAreasDirectory;
}
/**
* Sets the factory used to create country rules. Use `null` to disable country rules
*/
public GraphHopper setCountryRuleFactory(CountryRuleFactory countryRuleFactory) {
this.countryRuleFactory = countryRuleFactory;
return this;
}
public CountryRuleFactory getCountryRuleFactory() {
return this.countryRuleFactory;
}
/**
* Reads the configuration from a {@link GraphHopperConfig} object which can be manually filled, or more typically
* is read from `config.yml`.
* <p>
* Important note: Calling this method overwrites the configuration done in some of the setter methods of this class,
* so generally it is advised to either use this method to configure GraphHopper or the different setter methods,
* but not both. Unfortunately, this still does not cover all cases and sometimes you have to use both, but then you
* should make sure there are no conflicts. If you need both it might also help to call the init before calling the
* setters, because this way the init method won't apply defaults to configuration options you already chose using
* the setters.
*/
public GraphHopper init(GraphHopperConfig ghConfig) {
ensureNotLoaded();
// disabling_allowed config options were removed for GH 3.0
if (ghConfig.has("routing.ch.disabling_allowed"))
throw new IllegalArgumentException("The 'routing.ch.disabling_allowed' configuration option is no longer supported");
if (ghConfig.has("routing.lm.disabling_allowed"))
throw new IllegalArgumentException("The 'routing.lm.disabling_allowed' configuration option is no longer supported");
if (ghConfig.has("osmreader.osm"))
throw new IllegalArgumentException("Instead of osmreader.osm use datareader.file, for other changes see CHANGELOG.md");
String tmpOsmFile = ghConfig.getString("datareader.file", "");
if (!isEmpty(tmpOsmFile))
osmFile = tmpOsmFile;
String graphHopperFolder = ghConfig.getString("graph.location", "");
if (isEmpty(graphHopperFolder) && isEmpty(ghLocation)) {
if (isEmpty(osmFile))
throw new IllegalArgumentException("If no graph.location is provided you need to specify an OSM file.");
graphHopperFolder = pruneFileEnd(osmFile) + "-gh";
}
ghLocation = graphHopperFolder;
countryRuleFactory = ghConfig.getBool("country_rules.enabled", false) ? new CountryRuleFactory() : null;
customAreasDirectory = ghConfig.getString("custom_areas.directory", customAreasDirectory);
defaultSegmentSize = ghConfig.getInt("graph.dataaccess.segment_size", defaultSegmentSize);
String daTypeString = ghConfig.getString("graph.dataaccess.default_type", ghConfig.getString("graph.dataaccess", "RAM_STORE"));
dataAccessDefaultType = DAType.fromString(daTypeString);
for (Map.Entry<String, Object> entry : ghConfig.asPMap().toMap().entrySet()) {
if (entry.getKey().startsWith("graph.dataaccess.type."))
dataAccessConfig.put(entry.getKey().substring("graph.dataaccess.type.".length()), entry.getValue().toString());
if (entry.getKey().startsWith("graph.dataaccess.mmap.preload."))
dataAccessConfig.put(entry.getKey().substring("graph.dataaccess.mmap.".length()), entry.getValue().toString());
}
if (ghConfig.getBool("max_speed_calculator.enabled", false))
maxSpeedCalculator = new MaxSpeedCalculator(MaxSpeedCalculator.createLegalDefaultSpeeds());
sortGraph = ghConfig.getBool("graph.do_sort", sortGraph);
removeZipped = ghConfig.getBool("graph.remove_zipped", removeZipped);
if (!ghConfig.getString("spatial_rules.location", "").isEmpty())
throw new IllegalArgumentException("spatial_rules.location has been deprecated. Please use custom_areas.directory instead and read the documentation for custom areas.");
if (!ghConfig.getString("spatial_rules.borders_directory", "").isEmpty())
throw new IllegalArgumentException("spatial_rules.borders_directory has been deprecated. Please use custom_areas.directory instead and read the documentation for custom areas.");
// todo: maybe introduce custom_areas.max_bbox if this is needed later
if (!ghConfig.getString("spatial_rules.max_bbox", "").isEmpty())
throw new IllegalArgumentException("spatial_rules.max_bbox has been deprecated. There is no replacement, all custom areas will be considered.");
setProfiles(ghConfig.getProfiles());
if (ghConfig.has("graph.vehicles") && ghConfig.has("graph.flag_encoders"))
throw new IllegalArgumentException("Remove graph.flag_encoders as it cannot be used in parallel with graph.vehicles");
if (ghConfig.has("graph.flag_encoders"))
logger.warn("The option graph.flag_encoders is deprecated and will be removed. Replace with graph.vehicles");
vehiclesString = ghConfig.getString("graph.vehicles", ghConfig.getString("graph.flag_encoders", vehiclesString));
encodedValuesString = ghConfig.getString("graph.encoded_values", encodedValuesString);
dateRangeParserString = ghConfig.getString("datareader.date_range_parser_day", dateRangeParserString);
if (ghConfig.getString("graph.locktype", "native").equals("simple"))
lockFactory = new SimpleFSLockFactory();
else
lockFactory = new NativeFSLockFactory();
// elevation
if (ghConfig.has("graph.elevation.smoothing"))
throw new IllegalArgumentException("Use 'graph.elevation.edge_smoothing: moving_average' or the new 'graph.elevation.edge_smoothing: ramer'. See #2634.");
osmReaderConfig.setElevationSmoothing(ghConfig.getString("graph.elevation.edge_smoothing", osmReaderConfig.getElevationSmoothing()));
osmReaderConfig.setSmoothElevationAverageWindowSize(ghConfig.getDouble("graph.elevation.edge_smoothing.moving_average.window_size", osmReaderConfig.getSmoothElevationAverageWindowSize()));
osmReaderConfig.setElevationSmoothingRamerMax(ghConfig.getInt("graph.elevation.edge_smoothing.ramer.max_elevation", osmReaderConfig.getElevationSmoothingRamerMax()));
osmReaderConfig.setLongEdgeSamplingDistance(ghConfig.getDouble("graph.elevation.long_edge_sampling_distance", osmReaderConfig.getLongEdgeSamplingDistance()));
osmReaderConfig.setElevationMaxWayPointDistance(ghConfig.getDouble("graph.elevation.way_point_max_distance", osmReaderConfig.getElevationMaxWayPointDistance()));
routerConfig.setElevationWayPointMaxDistance(ghConfig.getDouble("graph.elevation.way_point_max_distance", routerConfig.getElevationWayPointMaxDistance()));
ElevationProvider elevationProvider = createElevationProvider(ghConfig);
setElevationProvider(elevationProvider);
if (osmReaderConfig.getLongEdgeSamplingDistance() < Double.MAX_VALUE && !elevationProvider.canInterpolate())
logger.warn("Long edge sampling enabled, but bilinear interpolation disabled. See #1953");
// optimizable prepare
minNetworkSize = ghConfig.getInt("prepare.min_network_size", minNetworkSize);
subnetworksThreads = ghConfig.getInt("prepare.subnetworks.threads", subnetworksThreads);
// prepare CH&LM
chPreparationHandler.init(ghConfig);
lmPreparationHandler.init(ghConfig);
// osm import
// We do a few checks for import.osm.ignored_highways to prevent configuration errors when migrating from an older
// GH version.
if (!ghConfig.has("import.osm.ignored_highways"))
throw new IllegalArgumentException("Missing 'import.osm.ignored_highways'. Not using this parameter can decrease performance, see config-example.yml for more details");
String ignoredHighwaysString = ghConfig.getString("import.osm.ignored_highways", "");
if ((ignoredHighwaysString.contains("footway") || ignoredHighwaysString.contains("path")) && ghConfig.getProfiles().stream().map(Profile::getName).anyMatch(p -> p.contains("foot") || p.contains("hike") || p.contains("wheelchair")))
throw new IllegalArgumentException("You should not use import.osm.ignored_highways=footway or =path in conjunction with pedestrian profiles. This is probably an error in your configuration.");
if ((ignoredHighwaysString.contains("cycleway") || ignoredHighwaysString.contains("path")) && ghConfig.getProfiles().stream().map(Profile::getName).anyMatch(p -> p.contains("mtb") || p.contains("bike")))
throw new IllegalArgumentException("You should not use import.osm.ignored_highways=cycleway or =path in conjunction with bicycle profiles. This is probably an error in your configuration");
osmReaderConfig.setIgnoredHighways(Arrays.stream(ghConfig.getString("import.osm.ignored_highways", String.join(",", osmReaderConfig.getIgnoredHighways()))
.split(",")).map(String::trim).collect(Collectors.toList()));
osmReaderConfig.setParseWayNames(ghConfig.getBool("datareader.instructions", osmReaderConfig.isParseWayNames()));
osmReaderConfig.setPreferredLanguage(ghConfig.getString("datareader.preferred_language", osmReaderConfig.getPreferredLanguage()));
osmReaderConfig.setMaxWayPointDistance(ghConfig.getDouble(Routing.INIT_WAY_POINT_MAX_DISTANCE, osmReaderConfig.getMaxWayPointDistance()));
osmReaderConfig.setWorkerThreads(ghConfig.getInt("datareader.worker_threads", osmReaderConfig.getWorkerThreads()));
// index
preciseIndexResolution = ghConfig.getInt("index.high_resolution", preciseIndexResolution);
maxRegionSearch = ghConfig.getInt("index.max_region_search", maxRegionSearch);
// urban density calculation
residentialAreaRadius = ghConfig.getDouble("graph.urban_density.residential_radius", residentialAreaRadius);
residentialAreaSensitivity = ghConfig.getDouble("graph.urban_density.residential_sensitivity", residentialAreaSensitivity);
cityAreaRadius = ghConfig.getDouble("graph.urban_density.city_radius", cityAreaRadius);
cityAreaSensitivity = ghConfig.getDouble("graph.urban_density.city_sensitivity", cityAreaSensitivity);
urbanDensityCalculationThreads = ghConfig.getInt("graph.urban_density.threads", urbanDensityCalculationThreads);
// routing
routerConfig.setMaxVisitedNodes(ghConfig.getInt(Routing.INIT_MAX_VISITED_NODES, routerConfig.getMaxVisitedNodes()));
routerConfig.setTimeoutMillis(ghConfig.getLong(Routing.INIT_TIMEOUT_MS, routerConfig.getTimeoutMillis()));
routerConfig.setMaxRoundTripRetries(ghConfig.getInt(RoundTrip.INIT_MAX_RETRIES, routerConfig.getMaxRoundTripRetries()));
routerConfig.setNonChMaxWaypointDistance(ghConfig.getInt(Parameters.NON_CH.MAX_NON_CH_POINT_DISTANCE, routerConfig.getNonChMaxWaypointDistance()));
routerConfig.setInstructionsEnabled(ghConfig.getBool(Routing.INIT_INSTRUCTIONS, routerConfig.isInstructionsEnabled()));
int activeLandmarkCount = ghConfig.getInt(Landmark.ACTIVE_COUNT_DEFAULT, Math.min(8, lmPreparationHandler.getLandmarks()));
if (activeLandmarkCount > lmPreparationHandler.getLandmarks())
throw new IllegalArgumentException("Default value for active landmarks " + activeLandmarkCount
+ " should be less or equal to landmark count of " + lmPreparationHandler.getLandmarks());
routerConfig.setActiveLandmarkCount(activeLandmarkCount);
return this;
}
protected EncodingManager buildEncodingManager(Map<String, String> vehiclesByName, List<String> encodedValueStrings,
boolean withUrbanDensity, boolean withMaxSpeedEst, Collection<Profile> profiles) {
EncodingManager.Builder emBuilder = new EncodingManager.Builder();
vehiclesByName.forEach((name, vehicleStr) -> emBuilder.add(vehicleEncodedValuesFactory.createVehicleEncodedValues(name, new PMap(vehicleStr))));
profiles.forEach(profile -> emBuilder.add(Subnetwork.create(profile.getName())));
if (withMaxSpeedEst)
emBuilder.add(MaxSpeedEstimated.create());
if (withUrbanDensity)
emBuilder.add(UrbanDensity.create());
encodedValueStrings.forEach(s -> emBuilder.add(encodedValueFactory.create(s, new PMap())));
return emBuilder.build();
}
protected OSMParsers buildOSMParsers(Map<String, String> vehiclesByName, List<String> encodedValueStrings,
List<String> ignoredHighways, String dateRangeParserString) {
OSMParsers osmParsers = new OSMParsers();
ignoredHighways.forEach(osmParsers::addIgnoredHighway);
for (String s : encodedValueStrings) {
TagParser tagParser = tagParserFactory.create(encodingManager, s, new PMap());
if (tagParser != null)
osmParsers.addWayTagParser(tagParser);
}
// this needs to be in sync with the default EVs added in EncodingManager.Builder#build. ideally I would like to remove
// all these defaults and just use the config as the single source of truth
if (!encodedValueStrings.contains(Roundabout.KEY))
osmParsers.addWayTagParser(new OSMRoundaboutParser(encodingManager.getBooleanEncodedValue(Roundabout.KEY)));
if (!encodedValueStrings.contains(RoadClass.KEY))
osmParsers.addWayTagParser(new OSMRoadClassParser(encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class)));
if (!encodedValueStrings.contains(RoadClassLink.KEY))
osmParsers.addWayTagParser(new OSMRoadClassLinkParser(encodingManager.getBooleanEncodedValue(RoadClassLink.KEY)));
if (!encodedValueStrings.contains(RoadEnvironment.KEY))
osmParsers.addWayTagParser(new OSMRoadEnvironmentParser(encodingManager.getEnumEncodedValue(RoadEnvironment.KEY, RoadEnvironment.class)));
if (!encodedValueStrings.contains(MaxSpeed.KEY))
osmParsers.addWayTagParser(new OSMMaxSpeedParser(encodingManager.getDecimalEncodedValue(MaxSpeed.KEY)));
if (!encodedValueStrings.contains(RoadAccess.KEY))
osmParsers.addWayTagParser(new OSMRoadAccessParser(encodingManager.getEnumEncodedValue(RoadAccess.KEY, RoadAccess.class), OSMRoadAccessParser.toOSMRestrictions(TransportationMode.CAR)));
if (encodingManager.hasEncodedValue(AverageSlope.KEY) || encodingManager.hasEncodedValue(MaxSlope.KEY)) {
if (!encodingManager.hasEncodedValue(AverageSlope.KEY) || !encodingManager.hasEncodedValue(MaxSlope.KEY))
throw new IllegalArgumentException("Enable both, average_slope and max_slope");
osmParsers.addWayTagParser(new SlopeCalculator(encodingManager.getDecimalEncodedValue(MaxSlope.KEY),
encodingManager.getDecimalEncodedValue(AverageSlope.KEY)));
}
if (maxSpeedCalculator != null) {
if (!encodingManager.hasEncodedValue(Country.KEY))
throw new IllegalArgumentException("max_speed_calculator needs country");
if (!encodingManager.hasEncodedValue(UrbanDensity.KEY))
throw new IllegalArgumentException("max_speed_calculator needs urban_density");
osmParsers.addWayTagParser(maxSpeedCalculator.getParser());
}
if (encodingManager.hasEncodedValue(Curvature.KEY))
osmParsers.addWayTagParser(new CurvatureCalculator(encodingManager.getDecimalEncodedValue(Curvature.KEY)));
DateRangeParser dateRangeParser = DateRangeParser.createInstance(dateRangeParserString);
Set<String> added = new HashSet<>();
vehiclesByName.forEach((name, vehicleStr) -> {
VehicleTagParsers vehicleTagParsers = vehicleTagParserFactory.createParsers(encodingManager, name,
new PMap(vehicleStr).putObject("date_range_parser", dateRangeParser));
if (vehicleTagParsers == null)
return;
vehicleTagParsers.getTagParsers().forEach(tagParser -> {
if (tagParser == null) return;
if (tagParser instanceof BikeCommonAccessParser) {
if (encodingManager.hasEncodedValue(BikeNetwork.KEY) && added.add(BikeNetwork.KEY))
osmParsers.addRelationTagParser(relConfig -> new OSMBikeNetworkTagParser(encodingManager.getEnumEncodedValue(BikeNetwork.KEY, RouteNetwork.class), relConfig));
if (encodingManager.hasEncodedValue(Smoothness.KEY) && added.add(Smoothness.KEY))
osmParsers.addWayTagParser(new OSMSmoothnessParser(encodingManager.getEnumEncodedValue(Smoothness.KEY, Smoothness.class)));
} else if (tagParser instanceof FootAccessParser) {
if (encodingManager.hasEncodedValue(FootNetwork.KEY) && added.add(FootNetwork.KEY))
osmParsers.addRelationTagParser(relConfig -> new OSMFootNetworkTagParser(encodingManager.getEnumEncodedValue(FootNetwork.KEY, RouteNetwork.class), relConfig));
}
String turnCostKey = TurnCost.key(new PMap(vehicleStr).getString("name", name));
if (encodingManager.hasEncodedValue(turnCostKey)
// need to make sure we do not add the same restriction parsers multiple times
&& osmParsers.getRestrictionTagParsers().stream().noneMatch(r -> r.getTurnCostEnc().getName().equals(turnCostKey))) {
List<String> restrictions = tagParser instanceof AbstractAccessParser
? ((AbstractAccessParser) tagParser).getRestrictions()
: OSMRoadAccessParser.toOSMRestrictions(TransportationMode.valueOf(new PMap(vehicleStr).getString("transportation_mode", "VEHICLE")));
osmParsers.addRestrictionTagParser(new RestrictionTagParser(restrictions, encodingManager.getDecimalEncodedValue(turnCostKey)));
}
});
vehicleTagParsers.getTagParsers().forEach(tagParser -> {
if (tagParser == null) return;
osmParsers.addWayTagParser(tagParser);
if (tagParser instanceof BikeCommonAccessParser && encodingManager.hasEncodedValue(GetOffBike.KEY) && added.add(GetOffBike.KEY))
osmParsers.addWayTagParser(new OSMGetOffBikeParser(encodingManager.getBooleanEncodedValue(GetOffBike.KEY), ((BikeCommonAccessParser) tagParser).getAccessEnc()));
});
});
return osmParsers;
}
public static List<String> getEncodedValueStrings(String encodedValuesStr) {
return Arrays.stream(encodedValuesStr.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
}
public static Map<String, String> getVehiclesByName(String vehiclesStr, Collection<Profile> profiles) {
Map<String, String> vehiclesMap = new LinkedHashMap<>();
for (String encoderStr : vehiclesStr.split(",")) {
String name = encoderStr.split("\\|")[0].trim();
if (name.isEmpty())
continue;
if (vehiclesMap.containsKey(name))
throw new IllegalArgumentException("Duplicate vehicle: " + name + " in: " + encoderStr);
vehiclesMap.put(name, encoderStr);
}
Map<String, String> vehiclesFromProfiles = new LinkedHashMap<>();
for (Profile profile : profiles) {
// if a profile uses a vehicle with turn costs make sure we add that vehicle with turn costs
String vehicle = profile.getVehicle().trim();
if (!vehiclesFromProfiles.containsKey(vehicle) || profile.isTurnCosts())
vehiclesFromProfiles.put(vehicle, vehicle + (profile.isTurnCosts() ? "|turn_costs=true" : ""));
}
// vehicles from profiles are only taken into account when they were not given explicitly
vehiclesFromProfiles.forEach(vehiclesMap::putIfAbsent);
return vehiclesMap;
}
private static ElevationProvider createElevationProvider(GraphHopperConfig ghConfig) {
String eleProviderStr = toLowerCase(ghConfig.getString("graph.elevation.provider", "noop"));
if (ghConfig.has("graph.elevation.calcmean"))
throw new IllegalArgumentException("graph.elevation.calcmean is deprecated, use graph.elevation.interpolate");
String cacheDirStr = ghConfig.getString("graph.elevation.cache_dir", "");
if (cacheDirStr.isEmpty() && ghConfig.has("graph.elevation.cachedir"))
throw new IllegalArgumentException("use graph.elevation.cache_dir not cachedir in configuration");
ElevationProvider elevationProvider = ElevationProvider.NOOP;
if (eleProviderStr.equalsIgnoreCase("hgt")) {
elevationProvider = new HGTProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("srtm")) {
elevationProvider = new SRTMProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("cgiar")) {
elevationProvider = new CGIARProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("gmted")) {
elevationProvider = new GMTEDProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("srtmgl1")) {
elevationProvider = new SRTMGL1Provider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("multi")) {
elevationProvider = new MultiSourceElevationProvider(cacheDirStr);
} else if (eleProviderStr.equalsIgnoreCase("skadi")) {
elevationProvider = new SkadiProvider(cacheDirStr);
}
if (elevationProvider instanceof TileBasedElevationProvider) {
TileBasedElevationProvider provider = (TileBasedElevationProvider) elevationProvider;
String baseURL = ghConfig.getString("graph.elevation.base_url", "");
if (baseURL.isEmpty() && ghConfig.has("graph.elevation.baseurl"))
throw new IllegalArgumentException("use graph.elevation.base_url not baseurl in configuration");
DAType elevationDAType = DAType.fromString(ghConfig.getString("graph.elevation.dataaccess", "MMAP"));
boolean interpolate = ghConfig.has("graph.elevation.interpolate")
? "bilinear".equals(ghConfig.getString("graph.elevation.interpolate", "none"))
: ghConfig.getBool("graph.elevation.calc_mean", false);
boolean removeTempElevationFiles = ghConfig.getBool("graph.elevation.cgiar.clear", true);
removeTempElevationFiles = ghConfig.getBool("graph.elevation.clear", removeTempElevationFiles);
provider
.setAutoRemoveTemporaryFiles(removeTempElevationFiles)
.setInterpolate(interpolate)
.setDAType(elevationDAType);
if (!baseURL.isEmpty())
provider.setBaseURL(baseURL);
}
return elevationProvider;
}
private void printInfo() {
logger.info("version " + Constants.VERSION + "|" + Constants.BUILD_DATE + " (" + Constants.getVersions() + ")");
if (baseGraph != null)
logger.info("graph " + getBaseGraphString() + ", details:" + baseGraph.toDetailsString());
}
private String getBaseGraphString() {
return encodingManager
+ "|" + baseGraph.getDirectory().getDefaultType()
+ "|" + baseGraph.getNodeAccess().getDimension() + "D"
+ "|" + (baseGraph.getTurnCostStorage() != null ? baseGraph.getTurnCostStorage() : "no_turn_cost")
+ "|" + getVersionsString();
}
private String getVersionsString() {
return "nodes:" + Constants.VERSION_NODE +
",edges:" + Constants.VERSION_EDGE +
",geometry:" + Constants.VERSION_GEOMETRY +
",location_index:" + Constants.VERSION_LOCATION_IDX +
",string_index:" + Constants.VERSION_KV_STORAGE +
",nodesCH:" + Constants.VERSION_NODE_CH +
",shortcuts:" + Constants.VERSION_SHORTCUT;
}
/**
* Imports provided data from disc and creates graph. Depending on the settings the resulting
* graph will be stored to disc so on a second call this method will only load the graph from
* disc which is usually a lot faster.
*/
public GraphHopper importOrLoad() {
if (!load()) {
printInfo();
process(false);
} else {
printInfo();
}
return this;
}
/**
* Imports and processes data, storing it to disk when complete.
*/
public void importAndClose() {
if (!load()) {
printInfo();
process(true);
} else {
printInfo();
logger.info("Graph already imported into " + ghLocation);
}
close();
}
/**
* Creates the graph from OSM data.
*/
protected void process(boolean closeEarly) {
GHDirectory directory = new GHDirectory(ghLocation, dataAccessDefaultType);
directory.configure(dataAccessConfig);
boolean withUrbanDensity = urbanDensityCalculationThreads > 0;
boolean withMaxSpeedEstimation = maxSpeedCalculator != null;
Map<String, String> vehiclesByName = getVehiclesByName(vehiclesString, profilesByName.values());
List<String> encodedValueStrings = getEncodedValueStrings(encodedValuesString);
encodingManager = buildEncodingManager(vehiclesByName, encodedValueStrings, withUrbanDensity,
withMaxSpeedEstimation, profilesByName.values());
osmParsers = buildOSMParsers(vehiclesByName, encodedValueStrings, osmReaderConfig.getIgnoredHighways(), dateRangeParserString);
baseGraph = new BaseGraph.Builder(getEncodingManager())
.setDir(directory)
.set3D(hasElevation())
.withTurnCosts(encodingManager.needsTurnCostsSupport())
.setSegmentSize(defaultSegmentSize)
.build();
properties = new StorableProperties(directory);
checkProfilesConsistency();
GHLock lock = null;
try {
if (directory.getDefaultType().isStoring()) {
lockFactory.setLockDir(new File(ghLocation));
lock = lockFactory.create(fileLockName, true);
if (!lock.tryLock())
throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
}
ensureWriteAccess();
importOSM();
cleanUp();
postImport();
postProcessing(closeEarly);
flush();
} finally {
if (lock != null)
lock.release();
}
}
protected void postImport() {
// Important note: To deal with via-way turn restrictions we introduce artificial edges in OSMReader (#2689).
// These are simply copies of real edges. Any further modifications of the graph edges must take care of keeping
// the artificial edges in sync with their real counterparts. So if an edge attribute shall be changed this change
// must also be applied to the corresponding artificial edge.
if (sortGraph) {
BaseGraph newGraph = GHUtility.newGraph(baseGraph);
GHUtility.sortDFS(baseGraph, newGraph);
logger.info("graph sorted (" + getMemInfo() + ")");
baseGraph = newGraph;
}
if (hasElevation())
interpolateBridgesTunnelsAndFerries();
if (encodingManager.hasEncodedValue(UrbanDensity.KEY)) {
EnumEncodedValue<UrbanDensity> urbanDensityEnc = encodingManager.getEnumEncodedValue(UrbanDensity.KEY, UrbanDensity.class);
if (!encodingManager.hasEncodedValue(RoadClass.KEY))
throw new IllegalArgumentException("Urban density calculation requires " + RoadClass.KEY);
if (!encodingManager.hasEncodedValue(RoadClassLink.KEY))
throw new IllegalArgumentException("Urban density calculation requires " + RoadClassLink.KEY);
EnumEncodedValue<RoadClass> roadClassEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class);
BooleanEncodedValue roadClassLinkEnc = encodingManager.getBooleanEncodedValue(RoadClassLink.KEY);
UrbanDensityCalculator.calcUrbanDensity(baseGraph, urbanDensityEnc, roadClassEnc,
roadClassLinkEnc, residentialAreaRadius, residentialAreaSensitivity, cityAreaRadius, cityAreaSensitivity, urbanDensityCalculationThreads);
}
if (maxSpeedCalculator != null) {
maxSpeedCalculator.fillMaxSpeed(getBaseGraph(), encodingManager);
maxSpeedCalculator.close();
}
}
protected void importOSM() {
if (osmFile == null)
throw new IllegalStateException("Couldn't load from existing folder: " + ghLocation
+ " but also cannot use file for DataReader as it wasn't specified!");
List<CustomArea> customAreas = readCountries();
if (isEmpty(customAreasDirectory)) {
logger.info("No custom areas are used, custom_areas.directory not given");
} else {
logger.info("Creating custom area index, reading custom areas from: '" + customAreasDirectory + "'");
customAreas.addAll(readCustomAreas());
}
AreaIndex<CustomArea> areaIndex = new AreaIndex<>(customAreas);
if (countryRuleFactory == null || countryRuleFactory.getCountryToRuleMap().isEmpty()) {
logger.info("No country rules available");
} else {
logger.info("Applying rules for the following countries: {}", countryRuleFactory.getCountryToRuleMap().keySet());
}
if (countryRuleFactory == null || countryRuleFactory.getCountryToRuleMap().isEmpty()) {
logger.info("No country rules available");
} else {
logger.info("Applying rules for the following countries: {}", countryRuleFactory.getCountryToRuleMap().keySet());
}
logger.info("start creating graph from " + osmFile);
OSMReader reader = new OSMReader(baseGraph.getBaseGraph(), osmParsers, osmReaderConfig).setFile(_getOSMFile()).
setAreaIndex(areaIndex).
setElevationProvider(eleProvider).
setCountryRuleFactory(countryRuleFactory);
logger.info("using " + getBaseGraphString() + ", memory:" + getMemInfo());
createBaseGraphAndProperties();
try {
reader.readGraph();
} catch (IOException ex) {
throw new RuntimeException("Cannot read file " + getOSMFile(), ex);
}
DateFormat f = createFormatter();
properties.put("datareader.import.date", f.format(new Date()));
if (reader.getDataDate() != null)
properties.put("datareader.data.date", f.format(reader.getDataDate()));
writeEncodingManagerToProperties();
}
protected void createBaseGraphAndProperties() {
baseGraph.getDirectory().create();
baseGraph.create(100);
properties.create(100);
if (maxSpeedCalculator != null)
maxSpeedCalculator.createDataAccessForParser(baseGraph.getDirectory());
}
protected void writeEncodingManagerToProperties() {
EncodingManager.putEncodingManagerIntoProperties(encodingManager, properties);
}
private List<CustomArea> readCustomAreas() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JtsModule());
final Path bordersDirectory = Paths.get(customAreasDirectory);
List<JsonFeatureCollection> jsonFeatureCollections = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(bordersDirectory, "*.{geojson,json}")) {
for (Path borderFile : stream) {
try (BufferedReader reader = Files.newBufferedReader(borderFile, StandardCharsets.UTF_8)) {
JsonFeatureCollection jsonFeatureCollection = objectMapper.readValue(reader, JsonFeatureCollection.class);
jsonFeatureCollections.add(jsonFeatureCollection);
}