diff --git a/OsmAnd-java/src/net/osmand/binary/BinaryInspector.java b/OsmAnd-java/src/net/osmand/binary/BinaryInspector.java index f1fe075cb1..962495a425 100644 --- a/OsmAnd-java/src/net/osmand/binary/BinaryInspector.java +++ b/OsmAnd-java/src/net/osmand/binary/BinaryInspector.java @@ -56,7 +56,7 @@ import com.google.protobuf.CodedOutputStream; import com.google.protobuf.WireFormat; public class BinaryInspector { - + public static final int BUFFER_SIZE = 1 << 20; public static final int SHIFT_ID = 6; @@ -71,11 +71,6 @@ public class BinaryInspector { // "-vrouting", "-vaddress", "-vcities","-vstreetgroups", "-vstreets", "-vbuildings", "-vintersections", -// "-zoom=15", -// "-bbox=1.74,51.17,1.75,51.16", -// "-vstats", -// "/Users/victorshcherb/osmand/maps/Synthetic_test_rendering.obf" -// "/Users/victorshcherb/osmand/maps/Netherlands_europe_2.road.obf" "/Users/victorshcherb/osmand/maps/Argentina_southamerica_2.obf" }); } else { @@ -84,15 +79,15 @@ public class BinaryInspector { } private void printToFile(String s) throws IOException { - if(vInfo.osmOut != null) { + if (vInfo.osmOut != null) { vInfo.osmOut.write(s.getBytes()); } else { System.out.println(s); } } - + private void println(String s) { - if(vInfo != null && vInfo.osm && vInfo.osmOut == null) { + if (vInfo != null && vInfo.osm && vInfo.osmOut == null) { // ignore } else { System.out.println(s); @@ -101,13 +96,13 @@ public class BinaryInspector { } private void print(String s) { - if(vInfo != null && vInfo.osm && vInfo.osmOut == null) { + if (vInfo != null && vInfo.osm && vInfo.osmOut == null) { // ignore } else { System.out.print(s); } } - + protected static class VerboseInfo { boolean vaddress; boolean vcities; @@ -129,71 +124,71 @@ public class BinaryInspector { double lonleft = -180; double lonright = 180; int zoom = -1; - + public boolean isVaddress() { return vaddress; } - + public int getZoom() { return zoom; } - + public boolean isVmap() { return vmap; } - + public boolean isVrouting() { return vrouting; } - + public boolean isVpoi() { return vpoi; } - + public boolean isVtransport() { return vtransport; } - + public boolean isVStats() { return vstats; } - + public VerboseInfo(String[] params) throws FileNotFoundException { - for(int i=0;i= o.getLocation().getLatitude() && latbottom <= o.getLocation().getLatitude() && lonleft <= o.getLocation().getLongitude() && lonright >= o.getLocation().getLongitude(); - + } public void close() throws IOException { - if(osmOut != null) { - osmOut.close();; + if (osmOut != null) { + osmOut.close(); osmOut = null; } } } - public void inspector(String[] args) throws IOException { - if(args == null || args.length == 0){ + public void inspector(String[] args) throws IOException { + if (args == null || args.length == 0) { printUsage(null); return; } @@ -266,6 +261,7 @@ public class BinaryInspector { printFileInformation(f); } } + public static final void writeInt(CodedOutputStream ous, int v) throws IOException { ous.writeRawByte((v >>> 24) & 0xFF); ous.writeRawByte((v >>> 16) & 0xFF); @@ -423,82 +419,81 @@ public class BinaryInspector { } - protected String formatBounds(int left, int right, int top, int bottom){ + protected String formatBounds(int left, int right, int top, int bottom) { double l = MapUtils.get31LongitudeX(left); double r = MapUtils.get31LongitudeX(right); double t = MapUtils.get31LatitudeY(top); double b = MapUtils.get31LatitudeY(bottom); - return formatLatBounds(l, r, t, b); + return formatLatBounds(l, r, t, b); } - - protected String formatLatBounds(double l, double r, double t, double b){ + + protected String formatLatBounds(double l, double r, double t, double b) { MessageFormat format = new MessageFormat("(left top - right bottom) : {0,number,#.####}, {1,number,#.####} NE - {2,number,#.####}, {3,number,#.####} NE", new Locale("EN", "US")); - return format.format(new Object[]{l, t, r, b}); + return format.format(new Object[]{l, t, r, b}); } - - public void printFileInformation(String fileName) throws IOException { + + public void printFileInformation(String fileName) throws IOException { File file = new File(fileName); - if(!file.exists()){ + if (!file.exists()) { println("Binary OsmAnd index " + fileName + " was not found."); return; } printFileInformation(file); } - - + public void printFileInformation(File file) throws IOException { RandomAccessFile r = new RandomAccessFile(file.getAbsolutePath(), "r"); printFileInformation(r, file); } - public void printFileInformation(RandomAccessFile r, File file ) throws IOException { + public void printFileInformation(RandomAccessFile r, File file) throws IOException { String filename = file.getName(); try { BinaryMapIndexReader index = new BinaryMapIndexReader(r, file); int i = 1; - println("Binary index " + filename + " version = " + index.getVersion() +" edition = " + new Date(index.getDateCreated())); - for(BinaryIndexPart p : index.getIndexes()){ + println("Binary index " + filename + " version = " + index.getVersion() + " edition = " + new Date(index.getDateCreated())); + for (BinaryIndexPart p : index.getIndexes()) { String partname = ""; - if(p instanceof MapIndex ){ + if (p instanceof MapIndex) { partname = "Map"; - } else if(p instanceof TransportIndex){ - partname = "Transport"; - } else if(p instanceof RouteRegion){ + } else if (p instanceof TransportIndex) { + + } else if (p instanceof RouteRegion) { partname = "Routing"; - } else if(p instanceof PoiRegion){ + } else if (p instanceof PoiRegion) { partname = "Poi"; - } else if(p instanceof AddressRegion){ + } else if (p instanceof AddressRegion) { partname = "Address"; } - String name = p.getName() == null ? "" : p.getName(); + String name = p.getName() == null ? "" : p.getName(); println(MessageFormat.format("{0} {1} data {3} - {2,number,#} bytes", new Object[]{i, partname, p.getLength(), name})); if(p instanceof TransportIndex){ TransportIndex ti = ((TransportIndex) p); int sh = (31 - BinaryMapIndexReader.TRANSPORT_STOP_ZOOM); - println("\tBounds " + formatBounds(ti.getLeft() << sh, ti.getRight() << sh, + println("\tBounds " + formatBounds(ti.getLeft() << sh, ti.getRight() << sh, ti.getTop() << sh, ti.getBottom() << sh)); - } else if(p instanceof RouteRegion){ + } else if (p instanceof RouteRegion) { RouteRegion ri = ((RouteRegion) p); - println("\tBounds " + formatLatBounds(ri.getLeftLongitude(), ri.getRightLongitude(), + println("\tBounds " + formatLatBounds(ri.getLeftLongitude(), ri.getRightLongitude(), ri.getTopLatitude(), ri.getBottomLatitude())); - if((vInfo != null && vInfo.isVrouting())){ + if ((vInfo != null && vInfo.isVrouting())) { printRouteDetailInfo(index, (RouteRegion) p); } - } else if(p instanceof MapIndex){ + } else if (p instanceof MapIndex) { MapIndex m = ((MapIndex) p); int j = 1; - for(MapRoot mi : m.getRoots()){ + for (MapRoot mi : m.getRoots()) { println(MessageFormat.format("\t{4}.{5} Map level minZoom = {0}, maxZoom = {1}, size = {2,number,#} bytes \n\t\tBounds {3}", new Object[] { mi.getMinZoom(), mi.getMaxZoom(), mi.getLength(), formatBounds(mi.getLeft(), mi.getRight(), mi.getTop(), mi.getBottom()), i, j++})); } - if((vInfo != null && vInfo.isVmap())){ + if ((vInfo != null && vInfo.isVmap())) { printMapDetailInfo(index, m); } - } else if(p instanceof PoiRegion && (vInfo != null && vInfo.isVpoi())){ + } else if (p instanceof PoiRegion && (vInfo != null && vInfo.isVpoi())) { printPOIDetailInfo(vInfo, index, (PoiRegion) p); } else if (p instanceof AddressRegion) { List cities = ((AddressRegion) p).cities; @@ -511,13 +506,13 @@ public class BinaryInspector { } i++; } - - + + } catch (IOException e) { - System.err.println("File doesn't have valid structure : " + filename + " " + e.getMessage() ); + System.err.println("File doesn't have valid structure : " + filename + " " + e.getMessage()); throw e; } - + } private void printRouteDetailInfo(BinaryMapIndexReader index, RouteRegion p) throws IOException { @@ -636,8 +631,8 @@ public class BinaryInspector { continue; } println(":"); - - for (City c : cities) { + + for (City c : cities) { int size = index.preloadStreets(c, null); List streets = new ArrayList(c.getStreets()); print(MessageFormat.format("\t\t''{0}'' [{1,number,#}], {2,number,#} street(s) size {3,number,#} bytes", @@ -650,14 +645,14 @@ public class BinaryInspector { println(":"); if (!verbose.contains(c)) continue; - + for (Street t : streets) { if (!verbose.contains(t)) continue; index.preloadBuildings(t, null); final List buildings = t.getBuildings(); final List intersections = t.getIntersectedStreets(); - + println(MessageFormat.format("\t\t\t''{0}'' [{1,number,#}], {2,number,#} building(s), {3,number,#} intersections(s)", new Object[]{t.getName(lang), t.getId(), buildings.size(), intersections.size()})); @@ -668,7 +663,7 @@ public class BinaryInspector { new Object[]{b.getName(lang), b.getId()})); } } - + if (intersections != null && !intersections.isEmpty() && verbose.vintersections) { print("\t\t\t\tIntersects with:"); for (Street s : intersections) { @@ -683,7 +678,7 @@ public class BinaryInspector { private static class DamnCounter { int value; } - + private static class MapStatKey { String key = ""; long statCoordinates; @@ -692,7 +687,7 @@ public class BinaryInspector { int count; int namesLength; } - + private class MapStats { public int lastStringNamesSize; public int lastObjectIdSize; @@ -701,22 +696,22 @@ public class BinaryInspector { public int lastObjectTypes; public int lastObjectCoordinates; public int lastObjectCoordinatesCount; - + public int lastObjectSize; - + private Map types = new LinkedHashMap(); private SearchRequest req; - + public void processKey(String simpleString, MapObjectStat st, TIntObjectHashMap objectNames, - int coordinates, boolean names ) { + int coordinates, boolean names) { TIntObjectIterator it = objectNames.iterator(); int nameLen = 0; - while(it.hasNext()) { + while (it.hasNext()) { it.advance(); - nameLen ++; + nameLen++; nameLen += it.value().length(); } - if(!types.containsKey(simpleString)) { + if (!types.containsKey(simpleString)) { MapStatKey stt = new MapStatKey(); stt.key = simpleString; types.put(simpleString, stt); @@ -756,7 +751,7 @@ public class BinaryInspector { for (int i = 0; i < obj.getTypes().length; i++) { int tp = obj.getTypes()[i]; TagValuePair pair = obj.mapIndex.decodeType(tp); - if(pair == null) { + if (pair == null) { continue; } processKey(pair.toSimpleString(), st, obj.getObjectNames(), cnt, names); @@ -784,7 +779,7 @@ public class BinaryInspector { b += out("Ids", lastObjectIdSize); b += out("String names", lastStringNamesSize); out("TOTAL", b); - + println("\n\nOBJECT BY TYPE STATS: "); ArrayList stats = new ArrayList(types.values()); Collections.sort(stats, new Comparator() { @@ -793,19 +788,19 @@ public class BinaryInspector { public int compare(MapStatKey o1, MapStatKey o2) { return compare(o1.statObjectSize, o2.statObjectSize); } - + public int compare(long x, long y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } }); - - for(MapStatKey s : stats) { - println(s.key + " (" + s.count + ") \t " + s.statObjectSize + " bytes \t coord="+ - s.statCoordinatesCount+ - " (" +s.statCoordinates +" bytes) " + - " names "+s.namesLength + " bytes"); + + for (MapStatKey s : stats) { + println(s.key + " (" + s.count + ") \t " + s.statObjectSize + " bytes \t coord=" + + s.statCoordinatesCount + + " (" + s.statCoordinates + " bytes) " + + " names " + s.namesLength + " bytes"); } - + } private long out(String s, long i) { @@ -813,7 +808,7 @@ public class BinaryInspector { s += " "; } DecimalFormat df = new DecimalFormat("0,000,000,000"); - println(s+": " + df.format(i)); + println(s + ": " + df.format(i)); return i; } @@ -821,18 +816,18 @@ public class BinaryInspector { public void setReq(SearchRequest req) { this.req = req; } - + } - - private void printMapDetailInfo(BinaryMapIndexReader index, MapIndex mapIndex) throws IOException { + + private void printMapDetailInfo(BinaryMapIndexReader index, MapIndex mapIndex) throws IOException { final StringBuilder b = new StringBuilder(); final DamnCounter mapObjectsCounter = new DamnCounter(); final MapStats mapObjectStats = new MapStats(); - if(vInfo.osm){ + if (vInfo.osm) { printToFile("\n" + "\n"); } - if(vInfo.isVStats()) { + if (vInfo.isVStats()) { BinaryMapIndexReader.READ_STATS = true; } final SearchRequest req = BinaryMapIndexReader.buildSearchRequest( @@ -851,7 +846,7 @@ public class BinaryInspector { @Override public boolean publish(BinaryMapDataObject obj) { mapObjectsCounter.value++; - if(vInfo.isVStats()) { + if (vInfo.isVStats()) { mapObjectStats.process(obj); } else if (vInfo.vmapObjects) { b.setLength(0); @@ -870,61 +865,61 @@ public class BinaryInspector { } return false; } + @Override public boolean isCancelled() { return false; } }); - if(vInfo.vstats) { + if (vInfo.vstats) { mapObjectStats.setReq(req); } index.searchMapIndex(req, mapIndex); - if(vInfo.osm){ + if (vInfo.osm) { printToFile("\n"); - } - if(vInfo.vstats) { + } + if (vInfo.vstats) { mapObjectStats.print(); } println("\tTotal map objects: " + mapObjectsCounter.value); } - private static void printMapDetails(BinaryMapDataObject obj, StringBuilder b, boolean vmapCoordinates) { boolean multipolygon = obj.getPolygonInnerCoordinates() != null && obj.getPolygonInnerCoordinates().length > 0; - if(multipolygon ) { + if (multipolygon) { b.append("Multipolygon"); } else { - b.append(obj.area? "Area" : (obj.getPointsLength() > 1? "Way" : "Point")); + b.append(obj.area ? "Area" : (obj.getPointsLength() > 1 ? "Way" : "Point")); } int[] types = obj.getTypes(); b.append(" types ["); - for(int j = 0; j 0) { + for (int j = 0; j < types.length; j++) { + if (j > 0) { b.append(", "); } TagValuePair pair = obj.getMapIndex().decodeType(types[j]); - if(pair == null) { + if (pair == null) { System.err.println("Type " + types[j] + "was not found"); continue; // throw new NullPointerException("Type " + obj.getAdditionalTypes()[j] + "was not found"); } - b.append(pair.toSimpleString()+" ("+types[j]+")"); + b.append(pair.toSimpleString() + " (" + types[j] + ")"); } b.append("]"); - if(obj.getAdditionalTypes() != null && obj.getAdditionalTypes().length > 0){ + if (obj.getAdditionalTypes() != null && obj.getAdditionalTypes().length > 0) { b.append(" add_types ["); - for(int j = 0; j 0) { + for (int j = 0; j < obj.getAdditionalTypes().length; j++) { + if (j > 0) { b.append(", "); } TagValuePair pair = obj.getMapIndex().decodeType(obj.getAdditionalTypes()[j]); - if(pair == null) { + if (pair == null) { System.err.println("Type " + obj.getAdditionalTypes()[j] + "was not found"); continue; // throw new NullPointerException("Type " + obj.getAdditionalTypes()[j] + "was not found"); } - b.append(pair.toSimpleString()+"("+obj.getAdditionalTypes()[j]+")"); + b.append(pair.toSimpleString() + "(" + obj.getAdditionalTypes()[j] + ")"); } b.append("]"); @@ -963,33 +958,33 @@ public class BinaryInspector { private static int OSM_ID = 1; - private void printOsmMapDetails(BinaryMapDataObject obj, StringBuilder b) { + private void printOsmMapDetails(BinaryMapDataObject obj, StringBuilder b) { boolean multipolygon = obj.getPolygonInnerCoordinates() != null && obj.getPolygonInnerCoordinates().length > 0; boolean point = obj.getPointsLength() == 1; StringBuilder tags = new StringBuilder(); int[] types = obj.getTypes(); - for(int j = 0; j\n"); } - if(obj.getAdditionalTypes() != null && obj.getAdditionalTypes().length > 0){ - for(int j = 0; j 0) { + for (int j = 0; j < obj.getAdditionalTypes().length; j++) { TagValuePair pair = obj.getMapIndex().decodeType(obj.getAdditionalTypes()[j]); - if(pair == null) { + if (pair == null) { throw new NullPointerException("Type " + obj.getAdditionalTypes()[j] + "was not found"); } tags.append("\t\n"); } } TIntObjectHashMap names = obj.getObjectNames(); - if(names != null && !names.isEmpty()) { + if (names != null && !names.isEmpty()) { int[] keys = names.keys(); - for(int j = 0; j\n" ); + b.append("\n"); b.append(tags); b.append("\n"); } else { TLongArrayList innerIds = new TLongArrayList(); TLongArrayList ids = new TLongArrayList(); - for(int i=0; i\n" ); + b.append("\t\n"); ids.add(id); } long outerId = printWay(ids, b, multipolygon ? null : tags); if (multipolygon) { int[][] polygonInnerCoordinates = obj.getPolygonInnerCoordinates(); for (int j = 0; j < polygonInnerCoordinates.length; j++) { - ids.clear();; + ids.clear(); for (int i = 0; i < polygonInnerCoordinates[j].length; i += 2) { float lon = (float) MapUtils.get31LongitudeX(polygonInnerCoordinates[j][i]); float lat = (float) MapUtils.get31LatitudeY(polygonInnerCoordinates[j][i + 1]); @@ -1033,36 +1028,36 @@ public class BinaryInspector { innerIds.add(printWay(ids, b, null)); } int id = OSM_ID++; - b.append("\n" ); + b.append("\n"); b.append(tags); - b.append("\t\n" ); + b.append("\t\n"); TLongIterator it = innerIds.iterator(); - while(it.hasNext()) { + while (it.hasNext()) { long ref = it.next(); - b.append("\n" ); + b.append("\n"); } - b.append("\n" ); + b.append("\n"); } } } - private long printWay(TLongArrayList ids, StringBuilder b , StringBuilder tags){ + private long printWay(TLongArrayList ids, StringBuilder b, StringBuilder tags) { int id = OSM_ID++; - b.append("\n" ); - if(tags != null) { + b.append("\n"); + if (tags != null) { b.append(tags); } TLongIterator it = ids.iterator(); - while(it.hasNext()) { + while (it.hasNext()) { long ref = it.next(); - b.append("\t\n" ); + b.append("\t\n"); } - b.append("\n" ); + b.append("\n"); return id; } - private void printPOIDetailInfo(VerboseInfo verbose, BinaryMapIndexReader index, PoiRegion p) throws IOException { + private void printPOIDetailInfo(VerboseInfo verbose, BinaryMapIndexReader index, PoiRegion p) throws IOException { SearchRequest req = BinaryMapIndexReader.buildSearchPoiRequest( MapUtils.get31TileNumberX(verbose.lonleft), MapUtils.get31TileNumberX(verbose.lonright), @@ -1079,53 +1074,54 @@ public class BinaryInspector { public boolean isEmpty() { return false; } - + }, new ResultMatcher() { @Override public boolean publish(Amenity object) { Iterator> it = object.getAdditionalInfo().entrySet().iterator(); String s = ""; - while(it.hasNext()) { + while (it.hasNext()) { Entry e = it.next(); - if(e.getValue().startsWith(" gz ")) { - s += " " + e.getKey() +"=..."; + if (e.getValue().startsWith(" gz ")) { + s += " " + e.getKey() + "=..."; } else { - s += " " + e.getKey() +"=" +e.getValue(); + s += " " + e.getKey() + "=" + e.getValue(); } } - + println(object.getType().getKeyName() + " : " + object.getSubType() + " " + object.getName() + " " + object.getLocation() + " id=" + (object.getId() >> 1) + " " + s); return false; } + @Override public boolean isCancelled() { return false; } }); - + index.initCategories(p); println("\tRegion: " + p.name); - println("\t\tBounds " + formatLatBounds(p.getLeftLongitude(), p.getRightLongitude(), + println("\t\tBounds " + formatLatBounds(p.getLeftLongitude(), p.getRightLongitude(), p.getTopLatitude(), p.getBottomLatitude())); println("\t\tCategories:"); - for(int i =0; i< p.categories.size(); i++) { + for (int i = 0; i < p.categories.size(); i++) { println("\t\t\t" + p.categories.get(i)); - for(int j = 0; j < p.subcategories.get(i).size(); j++) + for (int j = 0; j < p.subcategories.get(i).size(); j++) println("\t\t\t\t" + p.subcategories.get(i).get(j)); } println("\t\tSubtypes:"); - for(int i =0; i< p.subTypes.size(); i++) { + for (int i = 0; i < p.subTypes.size(); i++) { PoiSubType st = p.subTypes.get(i); - println("\t\t\t" + st.name + " " + (st.text ? "text":(" encoded " + st.possibleValues.size()))); + println("\t\t\t" + st.name + " " + (st.text ? "text" : (" encoded " + st.possibleValues.size()))); } // req.poiTypeFilter = null;//for test only index.searchPoi(p, req); - + } - public void printUsage(String warning) { - if(warning != null){ + public void printUsage(String warning) { + if (warning != null) { println(warning); } println("Inspector is console utility for working with binary indexes of OsmAnd."); diff --git a/OsmAnd-java/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java b/OsmAnd-java/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java index 231b2d50fc..4f10ebb8df 100644 --- a/OsmAnd-java/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java +++ b/OsmAnd-java/src/net/osmand/binary/BinaryMapAddressReaderAdapter.java @@ -53,19 +53,18 @@ public class BinaryMapAddressReaderAdapter { public String getEnName() { return enName; } - + public List getCities() { return cities; } - + public List getAttributeTagsTable() { return attributeTagsTable; } - + public int getIndexNameOffset() { return indexNameOffset; } - public String getPartName() { return "Address"; diff --git a/OsmAnd-java/src/net/osmand/binary/BinaryMapIndexReader.java b/OsmAnd-java/src/net/osmand/binary/BinaryMapIndexReader.java index a228411f4c..ea09cfd535 100644 --- a/OsmAnd-java/src/net/osmand/binary/BinaryMapIndexReader.java +++ b/OsmAnd-java/src/net/osmand/binary/BinaryMapIndexReader.java @@ -76,7 +76,7 @@ import com.google.protobuf.CodedOutputStream; import com.google.protobuf.WireFormat; public class BinaryMapIndexReader { - + public final static int TRANSPORT_STOP_ZOOM = 24; public static final int SHIFT_COORDINATES = 5; private final static Log log = PlatformUtil.getLog(BinaryMapIndexReader.class); @@ -86,26 +86,26 @@ public class BinaryMapIndexReader { private final RandomAccessFile raf; protected final File file; /*private*/ int version; - /*private */long dateCreated; + /*private*/ long dateCreated; // keep them immutable inside - /*private */ boolean basemap = false; - /*private */List mapIndexes = new ArrayList(); - /*private */List poiIndexes = new ArrayList(); - /*private */List addressIndexes = new ArrayList(); - /*private */List transportIndexes = new ArrayList(); - /*private */List routingIndexes = new ArrayList(); - /*private */List indexes = new ArrayList(); - + /*private*/ boolean basemap = false; + /*private*/ List mapIndexes = new ArrayList(); + /*private*/ List poiIndexes = new ArrayList(); + /*private*/ List addressIndexes = new ArrayList(); + /*private*/ List transportIndexes = new ArrayList(); + /*private*/ List routingIndexes = new ArrayList(); + /*private*/ List indexes = new ArrayList(); + protected CodedInputStream codedIS; - + private final BinaryMapTransportReaderAdapter transportAdapter; private final BinaryMapPoiReaderAdapter poiAdapter; private final BinaryMapAddressReaderAdapter addressAdapter; private final BinaryMapRouteReaderAdapter routeAdapter; - + private static String BASEMAP_NAME = "basemap"; - + public BinaryMapIndexReader(final RandomAccessFile raf, File file) throws IOException { this.raf = raf; this.file = file; @@ -117,7 +117,7 @@ public class BinaryMapIndexReader { routeAdapter = new BinaryMapRouteReaderAdapter(this); init(); } - + /*private */BinaryMapIndexReader(final RandomAccessFile raf, File file, boolean init) throws IOException { this.raf = raf; this.file = file; @@ -127,11 +127,11 @@ public class BinaryMapIndexReader { addressAdapter = new BinaryMapAddressReaderAdapter(this); poiAdapter = new BinaryMapPoiReaderAdapter(this); routeAdapter = new BinaryMapRouteReaderAdapter(this); - if(init) { + if (init) { init(); } } - + public BinaryMapIndexReader(final RandomAccessFile raf, BinaryMapIndexReader referenceToSameFile) throws IOException { this.raf = raf; this.file = referenceToSameFile.file; @@ -151,15 +151,15 @@ public class BinaryMapIndexReader { indexes = new ArrayList(referenceToSameFile.indexes); basemap = referenceToSameFile.basemap; } - - + + public long getDateCreated() { return dateCreated; } - + private void init() throws IOException { boolean initCorrectly = false; - while(true){ + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); switch (tag) { @@ -173,7 +173,7 @@ public class BinaryMapIndexReader { version = codedIS.readUInt32(); break; case OsmandOdb.OsmAndStructure.DATECREATED_FIELD_NUMBER : - dateCreated = codedIS.readInt64(); + dateCreated = codedIS.readInt64(); break; case OsmandOdb.OsmAndStructure.MAPINDEX_FIELD_NUMBER: MapIndex mapIndex = new MapIndex(); @@ -252,12 +252,12 @@ public class BinaryMapIndexReader { } } } - - private void calculateCenterPointForRegions(){ - for(AddressRegion reg : addressIndexes){ - for(MapIndex map : mapIndexes){ - if(Algorithms.objectEquals(reg.name, map.name)){ - if(map.getRoots().size() > 0){ + + private void calculateCenterPointForRegions() { + for (AddressRegion reg : addressIndexes) { + for (MapIndex map : mapIndexes) { + if (Algorithms.objectEquals(reg.name, map.name)) { + if (map.getRoots().size() > 0) { MapRoot mapRoot = map.getRoots().get(map.getRoots().size() - 1); double cy = (MapUtils.get31LatitudeY(mapRoot.getBottom()) + MapUtils.get31LatitudeY(mapRoot.getTop())) / 2; double cx = (MapUtils.get31LongitudeX(mapRoot.getLeft()) + MapUtils.get31LongitudeX(mapRoot.getRight())) / 2; @@ -268,35 +268,35 @@ public class BinaryMapIndexReader { } } } - + public List getIndexes() { return indexes; } - + public List getMapIndexes() { return mapIndexes; } - + public List getRoutingIndexes() { return routingIndexes; } - + public boolean isBasemap() { return basemap; } - - public boolean containsMapData(){ + + public boolean containsMapData() { return mapIndexes.size() > 0; } - - public boolean containsPoiData(){ + + public boolean containsPoiData() { return poiIndexes.size() > 0; } - - public boolean containsRouteData(){ + + public boolean containsRouteData() { return routingIndexes.size() > 0; } - + public boolean containsRouteData(int left31x, int top31y, int right31x, int bottom31y, int zoom) { for (RouteRegion ri : routingIndexes) { List sr = ri.getSubregions(); @@ -308,7 +308,7 @@ public class BinaryMapIndexReader { } return false; } - + public boolean containsPoiData(double latitude, double longitude) { for (PoiRegion index : poiIndexes) { if (index.rightLongitude >= longitude && index.leftLongitude <= longitude && @@ -318,23 +318,22 @@ public class BinaryMapIndexReader { } return false; } - - + public boolean containsPoiData(double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude) { for (PoiRegion index : poiIndexes) { - if (index.rightLongitude >= leftLongitude && index.leftLongitude <= rightLongitude && + if (index.rightLongitude >= leftLongitude && index.leftLongitude <= rightLongitude && index.topLatitude >= bottomLatitude && index.bottomLatitude <= topLatitude) { return true; } } return false; } - - public boolean containsMapData(int tile31x, int tile31y, int zoom){ - for(MapIndex mapIndex : mapIndexes){ - for(MapRoot root : mapIndex.getRoots()){ + + public boolean containsMapData(int tile31x, int tile31y, int zoom) { + for (MapIndex mapIndex : mapIndexes) { + for (MapRoot root : mapIndex.getRoots()) { if (root.minZoom <= zoom && root.maxZoom >= zoom) { - if (tile31x >= root.left && tile31x <= root.right && root.top <= tile31y && root.bottom >= tile31y) { + if (tile31x >= root.left && tile31x <= root.right && root.top <= tile31y && root.bottom >= tile31y) { return true; } } @@ -342,12 +341,12 @@ public class BinaryMapIndexReader { } return false; } - - public boolean containsMapData(int left31x, int top31y, int right31x, int bottom31y, int zoom){ - for(MapIndex mapIndex : mapIndexes){ - for(MapRoot root : mapIndex.getRoots()){ + + public boolean containsMapData(int left31x, int top31y, int right31x, int bottom31y, int zoom) { + for (MapIndex mapIndex : mapIndexes) { + for (MapRoot root : mapIndex.getRoots()) { if (root.minZoom <= zoom && root.maxZoom >= zoom) { - if (right31x >= root.left && left31x <= root.right && root.top <= bottom31y && root.bottom >= top31y) { + if (right31x >= root.left && left31x <= root.right && root.top <= bottom31y && root.bottom >= top31y) { return true; } } @@ -355,34 +354,33 @@ public class BinaryMapIndexReader { } return false; } - - public boolean containsAddressData(){ + + public boolean containsAddressData() { return addressIndexes.size() > 0; } - - public boolean hasTransportData(){ + + public boolean hasTransportData() { return transportIndexes.size() > 0; } - - + public RandomAccessFile getRaf() { return raf; } - + public File getFile() { return file; } - - public int readByte() throws IOException{ + + public int readByte() throws IOException { byte b = codedIS.readRawByte(); - if(b < 0){ + if (b < 0) { return b + 256; } else { return b; } } - + public final int readInt() throws IOException { int ch1 = readByte(); int ch2 = readByte(); @@ -390,32 +388,31 @@ public class BinaryMapIndexReader { int ch4 = readByte(); return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4); } - - + + public int getVersion() { return version; } - - + protected void skipUnknownField(int tag) throws IOException { int wireType = WireFormat.getTagWireType(tag); - if(wireType == WireFormat.WIRETYPE_FIXED32_LENGTH_DELIMITED){ + if (wireType == WireFormat.WIRETYPE_FIXED32_LENGTH_DELIMITED) { int length = readInt(); codedIS.skipRawBytes(length); } else { codedIS.skipField(tag); } } - - + + /** * Transport public methods */ public TIntObjectHashMap getTransportRoutes(int[] filePointers) throws IOException { TIntObjectHashMap result = new TIntObjectHashMap(); Map groupPoints = new HashMap(); - for(int filePointer : filePointers){ + for (int filePointer : filePointers) { TransportIndex ind = getTransportIndex(filePointer); if (ind != null) { if (!groupPoints.containsKey(ind)) { @@ -424,8 +421,8 @@ public class BinaryMapIndexReader { groupPoints.get(ind).add(filePointer); } } - Iterator > it = groupPoints.entrySet().iterator(); - if(it.hasNext()){ + Iterator> it = groupPoints.entrySet().iterator(); + if (it.hasNext()) { Entry e = it.next(); TransportIndex ind = e.getKey(); TIntArrayList pointers = e.getValue(); @@ -437,79 +434,79 @@ public class BinaryMapIndexReader { result.put(filePointer, transportRoute); } transportAdapter.initializeStringTable(ind, stringTable); - for(TransportRoute r : result.values(new TransportRoute[result.size()])){ + for (TransportRoute r : result.values(new TransportRoute[result.size()])) { transportAdapter.initializeNames(false, r, stringTable); } } return result; } - + /** * Transport public methods */ public List getTransportRouteDescriptions(TransportStop stop) throws IOException { TransportIndex ind = getTransportIndex(stop.getFileOffset()); - if(ind == null){ + if (ind == null) { return null; } List list = new ArrayList(); TIntObjectHashMap stringTable = new TIntObjectHashMap(); - for(int filePointer : stop.getReferencesToRoutes()){ + for (int filePointer : stop.getReferencesToRoutes()) { TransportRoute tr = transportAdapter.getTransportRoute(filePointer, stringTable, true); - if(tr != null){ - list.add(tr); + if (tr != null) { + list.add(tr); } } transportAdapter.initializeStringTable(ind, stringTable); - for(TransportRoute route : list){ + for (TransportRoute route : list) { transportAdapter.initializeNames(true, route, stringTable); } return list; } - - public boolean transportStopBelongsTo(TransportStop s){ + + public boolean transportStopBelongsTo(TransportStop s) { return getTransportIndex(s.getFileOffset()) != null; } - + public List getTransportIndexes() { return transportIndexes; } - + private TransportIndex getTransportIndex(int filePointer) { TransportIndex ind = null; - for(TransportIndex i : transportIndexes){ - if(i.filePointer <= filePointer && (filePointer - i.filePointer) < i.length){ + for (TransportIndex i : transportIndexes) { + if (i.filePointer <= filePointer && (filePointer - i.filePointer) < i.length) { ind = i; break; } } return ind; } - + public boolean containTransportData(double latitude, double longitude) { double x = MapUtils.getTileNumberX(TRANSPORT_STOP_ZOOM, longitude); double y = MapUtils.getTileNumberY(TRANSPORT_STOP_ZOOM, latitude); for (TransportIndex index : transportIndexes) { - if (index.right >= x && index.left <= x && index.top <= y && index.bottom >= y) { + if (index.right >= x && index.left <= x && index.top <= y && index.bottom >= y) { return true; } } return false; } - - public boolean containTransportData(double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude){ + + public boolean containTransportData(double topLatitude, double leftLongitude, double bottomLatitude, double rightLongitude) { double leftX = MapUtils.getTileNumberX(TRANSPORT_STOP_ZOOM, leftLongitude); double topY = MapUtils.getTileNumberY(TRANSPORT_STOP_ZOOM, topLatitude); double rightX = MapUtils.getTileNumberX(TRANSPORT_STOP_ZOOM, rightLongitude); double bottomY = MapUtils.getTileNumberY(TRANSPORT_STOP_ZOOM, bottomLatitude); for (TransportIndex index : transportIndexes) { - if (index.right >= leftX && index.left <= rightX && index.top <= bottomY && index.bottom >= topY) { + if (index.right >= leftX && index.left <= rightX && index.top <= bottomY && index.bottom >= topY) { return true; } } return false; } - + public List searchTransportIndex(SearchRequest req) throws IOException { for (TransportIndex index : transportIndexes) { if (index.stopsFileLength == 0 || index.right < req.left || index.left > req.right || index.top > req.bottom @@ -529,38 +526,38 @@ public class BinaryMapIndexReader { } } } - if(req.numberOfVisitedObjects > 0) { + if (req.numberOfVisitedObjects > 0) { log.debug("Search is done. Visit " + req.numberOfVisitedObjects + " objects. Read " + req.numberOfAcceptedObjects + " objects."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.debug("Read " + req.numberOfReadSubtrees + " subtrees. Go through " + req.numberOfAcceptedSubtrees + " subtrees."); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } return req.getSearchResults(); } - + /** * Address public methods */ - public List getRegionNames(){ + public List getRegionNames() { List names = new ArrayList(); - for(AddressRegion r : addressIndexes){ + for (AddressRegion r : addressIndexes) { names.add(r.name); } return names; } - + public LatLon getRegionCenter() { - for(AddressRegion r : addressIndexes) { - if(r.calculatedCenter != null) + for (AddressRegion r : addressIndexes) { + if (r.calculatedCenter != null) return r.calculatedCenter; } return null; } - - public List getCities(SearchRequest resultMatcher, - int cityType) throws IOException { + + public List getCities(SearchRequest resultMatcher, + int cityType) throws IOException { return getCities(resultMatcher, null, null, cityType); } - + public List getCities(SearchRequest resultMatcher, StringMatcher matcher, String lang, int cityType) throws IOException { List cities = new ArrayList(); @@ -584,8 +581,8 @@ public class BinaryMapIndexReader { public List getCities(AddressRegion region, SearchRequest resultMatcher, StringMatcher matcher, int cityType) throws IOException { List cities = new ArrayList(); - for(CitiesBlock block : region.cities) { - if(block.type == cityType) { + for (CitiesBlock block : region.cities) { + if (block.type == cityType) { codedIS.seek(block.filePointer); int old = codedIS.pushLimit(block.length); addressAdapter.readCities(cities, resultMatcher, matcher, region.attributeTagsTable); @@ -594,7 +591,7 @@ public class BinaryMapIndexReader { } return cities; } - + public int preloadStreets(City c, SearchRequest resultMatcher) throws IOException { AddressRegion reg = checkAddressIndex(c.getFileOffset()); codedIS.seek(c.getFileOffset()); @@ -604,7 +601,7 @@ public class BinaryMapIndexReader { codedIS.popLimit(old); return size; } - + private AddressRegion checkAddressIndex(int offset) { for (AddressRegion r : addressIndexes) { if (offset >= r.filePointer && offset <= (r.length + r.filePointer)) { @@ -614,30 +611,30 @@ public class BinaryMapIndexReader { throw new IllegalArgumentException("Illegal offset " + offset); //$NON-NLS-1$ } - + public void preloadBuildings(Street s, SearchRequest resultMatcher) throws IOException { AddressRegion reg = checkAddressIndex(s.getFileOffset()); codedIS.seek(s.getFileOffset()); int size = codedIS.readRawVarint32(); int old = codedIS.pushLimit(size); City city = s.getCity(); - addressAdapter.readStreet(s, resultMatcher, true, 0, 0, city != null && city.isPostcode() ? city.getName() : null, + addressAdapter.readStreet(s, resultMatcher, true, 0, 0, city != null && city.isPostcode() ? city.getName() : null, reg.attributeTagsTable); codedIS.popLimit(old); } - - + + /** - * Map public methods + * Map public methods */ private void readMapIndex(MapIndex index, boolean onlyInitEncodingRules) throws IOException { int defaultId = 1; - int oldLimit ; - while(true){ + int oldLimit; + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); - + switch (tag) { case 0: // encoding rules are required! @@ -677,13 +674,13 @@ public class BinaryMapIndexReader { } } } - - + + private void readMapEncodingRule(MapIndex index, int id) throws IOException { int type = 0; String tags = null; String val = null; - while(true){ + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); switch (tag) { @@ -711,7 +708,7 @@ public class BinaryMapIndexReader { private MapRoot readMapLevel(MapRoot root) throws IOException { - while(true){ + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); switch (tag) { @@ -758,11 +755,11 @@ public class BinaryMapIndexReader { break; } } - + } - + private void readMapTreeBounds(MapTree tree, int aleft, int aright, int atop, int abottom) throws IOException { - while(true){ + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); switch (tag) { @@ -790,16 +787,15 @@ public class BinaryMapIndexReader { case MapDataBox.SHIFTTOMAPDATA_FIELD_NUMBER : tree.mapDataBlock = readInt() + tree.filePointer; break; - + default: skipUnknownField(t); break; } } } - - - + + public List searchMapIndex(SearchRequest req) throws IOException { req.numberOfVisitedObjects = 0; req.numberOfAcceptedObjects = 0; @@ -808,7 +804,7 @@ public class BinaryMapIndexReader { List foundSubtrees = new ArrayList(); for (MapIndex mapIndex : mapIndexes) { // lazy initializing rules - if(mapIndex.encodingRules.isEmpty()) { + if (mapIndex.encodingRules.isEmpty()) { codedIS.seek(mapIndex.filePointer); int oldLimit = codedIS.pushLimit(mapIndex.length); readMapIndex(mapIndex, true); @@ -819,16 +815,16 @@ public class BinaryMapIndexReader { if (index.right < req.left || index.left > req.right || index.top > req.bottom || index.bottom < req.top) { continue; } - + // lazy initializing trees - if(index.trees == null){ + if (index.trees == null) { index.trees = new ArrayList(); codedIS.seek(index.filePointer); int oldLimit = codedIS.pushLimit(index.length); readMapLevel(index); codedIS.popLimit(oldLimit); } - + for (MapTree tree : index.trees) { if (tree.right < req.left || tree.left > req.right || tree.top > req.bottom || tree.bottom < req.top) { continue; @@ -838,15 +834,15 @@ public class BinaryMapIndexReader { searchMapTreeBounds(tree, index, req, foundSubtrees); codedIS.popLimit(oldLimit); } - + Collections.sort(foundSubtrees, new Comparator() { @Override public int compare(MapTree o1, MapTree o2) { return o1.mapDataBlock < o2.mapDataBlock ? -1 : (o1.mapDataBlock == o2.mapDataBlock ? 0 : 1); } }); - for(MapTree tree : foundSubtrees) { - if(!req.isCancelled()){ + for (MapTree tree : foundSubtrees) { + if (!req.isCancelled()) { codedIS.seek(tree.mapDataBlock); int length = codedIS.readRawVarint32(); int oldLimit = codedIS.pushLimit(length); @@ -856,46 +852,46 @@ public class BinaryMapIndexReader { } foundSubtrees.clear(); } - + } } - if(req.numberOfVisitedObjects > 0 && req.log) { + if (req.numberOfVisitedObjects > 0 && req.log) { log.info("Search is done. Visit " + req.numberOfVisitedObjects + " objects. Read " + req.numberOfAcceptedObjects + " objects."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info("Read " + req.numberOfReadSubtrees + " subtrees. Go through " + req.numberOfAcceptedSubtrees + " subtrees."); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } return req.getSearchResults(); } - + public List searchMapIndex(SearchRequest req, MapIndex mapIndex) throws IOException { req.numberOfVisitedObjects = 0; req.numberOfAcceptedObjects = 0; req.numberOfAcceptedSubtrees = 0; req.numberOfReadSubtrees = 0; List foundSubtrees = new ArrayList(); - + // lazy initializing rules - if(mapIndex.encodingRules.isEmpty()) { + if (mapIndex.encodingRules.isEmpty()) { codedIS.seek(mapIndex.filePointer); int oldLimit = codedIS.pushLimit(mapIndex.length); readMapIndex(mapIndex, true); codedIS.popLimit(oldLimit); } - + for (MapRoot level : mapIndex.getRoots()) { if ((level.minZoom <= req.zoom && level.maxZoom >= req.zoom) || req.zoom == -1) { if (level.right < req.left || level.left > req.right || level.top > req.bottom || level.bottom < req.top) { continue; } - + // lazy initializing trees - if(level.trees == null){ + if (level.trees == null) { level.trees = new ArrayList(); codedIS.seek(level.filePointer); int oldLimit = codedIS.pushLimit(level.length); readMapLevel(level); codedIS.popLimit(oldLimit); } - + for (MapTree tree : level.trees) { if (tree.right < req.left || tree.left > req.right || tree.top > req.bottom || tree.bottom < req.top) { continue; @@ -905,15 +901,15 @@ public class BinaryMapIndexReader { searchMapTreeBounds(tree, level, req, foundSubtrees); codedIS.popLimit(oldLimit); } - + Collections.sort(foundSubtrees, new Comparator() { @Override public int compare(MapTree o1, MapTree o2) { return o1.mapDataBlock < o2.mapDataBlock ? -1 : (o1.mapDataBlock == o2.mapDataBlock ? 0 : 1); } }); - for(MapTree tree : foundSubtrees) { - if(!req.isCancelled()){ + for (MapTree tree : foundSubtrees) { + if (!req.isCancelled()) { codedIS.seek(tree.mapDataBlock); int length = codedIS.readRawVarint32(); int oldLimit = codedIS.pushLimit(length); @@ -923,20 +919,20 @@ public class BinaryMapIndexReader { } foundSubtrees.clear(); } - + } - - - if(req.numberOfVisitedObjects > 0) { + + + if (req.numberOfVisitedObjects > 0) { log.info("Search is done. Visit " + req.numberOfVisitedObjects + " objects. Read " + req.numberOfAcceptedObjects + " objects."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info("Read " + req.numberOfReadSubtrees + " subtrees. Go through " + req.numberOfAcceptedSubtrees + " subtrees."); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } return req.getSearchResults(); } - + protected void readMapDataBlocks(SearchRequest req, MapTree tree, MapIndex root) throws IOException { List tempResults = null; - long baseId = 0; + long baseId = 0; while (true) { if (req.isCancelled()) { return; @@ -969,7 +965,7 @@ public class BinaryMapIndexReader { mapObject.setId(mapObject.getId() + baseId); if (READ_STATS) { req.publish(mapObject); - } + } if (tempResults == null) { tempResults = new ArrayList(); } @@ -1007,21 +1003,21 @@ public class BinaryMapIndexReader { } } - + protected void searchMapTreeBounds(MapTree current, MapTree parent, SearchRequest req, List foundSubtrees) throws IOException { int init = 0; req.numberOfReadSubtrees++; - while(true){ - if(req.isCancelled()){ + while (true) { + if (req.isCancelled()) { return; } int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); - if(init == 0xf){ + if (init == 0xf) { init = 0; // coordinates are init - if(current.right < req.left || current.left > req.right || current.top > req.bottom || current.bottom < req.top){ + if (current.right < req.left || current.left > req.right || current.top > req.bottom || current.bottom < req.top) { return; } else { req.numberOfAcceptedSubtrees++; @@ -1078,18 +1074,18 @@ public class BinaryMapIndexReader { } } } - + private int MASK_TO_READ = ~((1 << SHIFT_COORDINATES) - 1); private BinaryMapDataObject readMapDataObject(MapTree tree , SearchRequest req, MapIndex root) throws IOException { int tag = WireFormat.getTagFieldNumber(codedIS.readTag()); boolean area = OsmandOdb.MapData.AREACOORDINATES_FIELD_NUMBER == tag; - if(!area && OsmandOdb.MapData.COORDINATES_FIELD_NUMBER != tag) { + if (!area && OsmandOdb.MapData.COORDINATES_FIELD_NUMBER != tag) { throw new IllegalArgumentException(); } req.cacheCoordinates.clear(); int size = codedIS.readRawVarint32(); - if(READ_STATS) { + if (READ_STATS) { req.stat.lastObjectCoordinates += size; req.stat.addTagHeader(OsmandOdb.MapData.COORDINATES_FIELD_NUMBER, size); @@ -1103,44 +1099,44 @@ public class BinaryMapIndexReader { int minY = Integer.MAX_VALUE; int maxY = 0; req.numberOfVisitedObjects++; - while(codedIS.getBytesUntilLimit() > 0){ + while (codedIS.getBytesUntilLimit() > 0) { int x = (codedIS.readSInt32() << SHIFT_COORDINATES) + px; int y = (codedIS.readSInt32() << SHIFT_COORDINATES) + py; req.cacheCoordinates.add(x); req.cacheCoordinates.add(y); px = x; py = y; - if(!contains && req.left <= x && req.right >= x && req.top <= y && req.bottom >= y){ + if (!contains && req.left <= x && req.right >= x && req.top <= y && req.bottom >= y) { contains = true; } - if(!contains){ + if (!contains) { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); } } - if(!contains){ - if(maxX >= req.left && minX <= req.right && minY <= req.bottom && maxY >= req.top){ + if (!contains) { + if (maxX >= req.left && minX <= req.right && minY <= req.bottom && maxY >= req.top) { contains = true; } - + } codedIS.popLimit(old); - if(!contains){ + if (!contains) { codedIS.skipRawBytes(codedIS.getBytesUntilLimit()); return null; } - + // read - + List innercoordinates = null; TIntArrayList additionalTypes = null; TIntObjectHashMap stringNames = null; TIntArrayList stringOrder = null; long id = 0; - - boolean loop = true; + + boolean loop = true; while (loop) { int t = codedIS.readTag(); tag = WireFormat.getTagFieldNumber(t); @@ -1186,7 +1182,7 @@ public class BinaryMapIndexReader { additionalTypes.add(codedIS.readRawVarint32()); } codedIS.popLimit(old); - + break; case OsmandOdb.MapData.TYPES_FIELD_NUMBER: req.cacheTypes.clear(); @@ -1264,13 +1260,13 @@ public class BinaryMapIndexReader { dataObject.mapIndex = root; return dataObject; } - + public List searchAddressDataByName(SearchRequest req) throws IOException { if (req.nameQuery == null || req.nameQuery.length() == 0) { throw new IllegalArgumentException(); } for (AddressRegion reg : addressIndexes) { - if(reg.indexNameOffset != -1) { + if (reg.indexNameOffset != -1) { codedIS.seek(reg.indexNameOffset); int len = readInt(); int old = codedIS.pushLimit(len); @@ -1280,11 +1276,11 @@ public class BinaryMapIndexReader { } return req.getSearchResults(); } - + public void initCategories(PoiRegion poiIndex) throws IOException { poiAdapter.initCategories(poiIndex); } - + public List searchPoiByName(SearchRequest req) throws IOException { if (req.nameQuery == null || req.nameQuery.length() == 0) { throw new IllegalArgumentException(); @@ -1298,8 +1294,8 @@ public class BinaryMapIndexReader { } return req.getSearchResults(); } - - public Map > searchPoiCategoriesByName(String query, Map > map) throws IOException { + + public Map> searchPoiCategoriesByName(String query, Map> map) throws IOException { if (query == null || query.length() == 0) { throw new IllegalArgumentException(); } @@ -1330,7 +1326,7 @@ public class BinaryMapIndexReader { } return map; } - + public List searchPoi(SearchRequest req) throws IOException { req.numberOfVisitedObjects = 0; req.numberOfAcceptedObjects = 0; @@ -1345,31 +1341,31 @@ public class BinaryMapIndexReader { } log.info("Read " + req.numberOfReadSubtrees + " subtrees. Go through " + req.numberOfAcceptedSubtrees + " subtrees."); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ log.info("Search poi is done. Visit " + req.numberOfVisitedObjects + " objects. Read " + req.numberOfAcceptedObjects + " objects."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - + return req.getSearchResults(); } - + public List searchPoi(PoiRegion poiIndex, SearchRequest req) throws IOException { req.numberOfVisitedObjects = 0; req.numberOfAcceptedObjects = 0; req.numberOfAcceptedSubtrees = 0; req.numberOfReadSubtrees = 0; - + poiAdapter.initCategories(poiIndex); codedIS.seek(poiIndex.filePointer); int old = codedIS.pushLimit(poiIndex.length); poiAdapter.searchPoiIndex(req.left, req.right, req.top, req.bottom, req, poiIndex); codedIS.popLimit(old); - + log.info("Search poi is done. Visit " + req.numberOfVisitedObjects + " objects. Read " + req.numberOfAcceptedObjects + " objects."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ log.info("Read " + req.numberOfReadSubtrees + " subtrees. Go through " + req.numberOfAcceptedSubtrees + " subtrees."); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - + return req.getSearchResults(); } - - protected List readStringTable() throws IOException{ + + protected List readStringTable() throws IOException { List list = new ArrayList(); - while(true){ + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); switch (tag) { @@ -1384,18 +1380,18 @@ public class BinaryMapIndexReader { } } } - + protected List getAddressIndexes() { return addressIndexes; } - + protected List getPoiIndexes() { return poiIndexes; } - - public static SearchRequest buildSearchRequest(int sleft, int sright, int stop, int sbottom, int zoom, SearchFilter searchFilter){ + + public static SearchRequest buildSearchRequest(int sleft, int sright, int stop, int sbottom, int zoom, SearchFilter searchFilter) { return buildSearchRequest(sleft, sright, stop, sbottom, zoom, searchFilter, null); } @@ -1410,31 +1406,30 @@ public class BinaryMapIndexReader { request.bottom = sbottom; request.zoom = zoom; request.searchFilter = searchFilter; - request.resultMatcher = resultMatcher; + request.resultMatcher = resultMatcher; return request; } - - public static SearchRequest buildAddressRequest(ResultMatcher resultMatcher){ + + public static SearchRequest buildAddressRequest(ResultMatcher resultMatcher) { SearchRequest request = new SearchRequest(); request.resultMatcher = resultMatcher; return request; } - - - - public static SearchRequest buildAddressByNameRequest(ResultMatcher resultMatcher, String nameRequest){ + + + public static SearchRequest buildAddressByNameRequest(ResultMatcher resultMatcher, String nameRequest) { SearchRequest request = new SearchRequest(); request.resultMatcher = resultMatcher; request.nameQuery = nameRequest; return request; } - + public static SearchRequest buildSearchPoiRequest(List route, double radius, SearchPoiTypeFilter poiTypeFilter, ResultMatcher resultMatcher) { SearchRequest request = new SearchRequest(); - float coeff = (float) (radius / MapUtils.getTileDistanceWidth(SearchRequest.ZOOM_TO_SEARCH_POI)); + float coeff = (float) (radius / MapUtils.getTileDistanceWidth(SearchRequest.ZOOM_TO_SEARCH_POI)); TLongObjectHashMap> zooms = new TLongObjectHashMap>(); - for(int i = 1; i < route.size(); i++) { + for (int i = 1; i < route.size(); i++) { Location cr = route.get(i); Location pr = route.get(i - 1); double tx = MapUtils.getTileNumberX(SearchRequest.ZOOM_TO_SEARCH_POI, cr.getLongitude()); @@ -1445,10 +1440,10 @@ public class BinaryMapIndexReader { double topLeftY = Math.min(ty, py) - coeff; double bottomRightX = Math.max(tx, px) + coeff; double bottomRightY = Math.max(ty, py) + coeff; - for(int x = (int) topLeftX; x <= bottomRightX; x++) { - for(int y = (int) topLeftY; y <= bottomRightY; y++) { - long hash = (((long)x) << SearchRequest.ZOOM_TO_SEARCH_POI) + y; - if(!zooms.containsKey(hash)) { + for (int x = (int) topLeftX; x <= bottomRightX; x++) { + for (int y = (int) topLeftY; y <= bottomRightY; y++) { + long hash = (((long) x) << SearchRequest.ZOOM_TO_SEARCH_POI) + y; + if (!zooms.containsKey(hash)) { zooms.put(hash, new LinkedList()); } List ll = zooms.get(hash); @@ -1456,12 +1451,12 @@ public class BinaryMapIndexReader { ll.add(cr); } } - + } - int sleft = Integer.MAX_VALUE , sright = 0, stop = Integer.MAX_VALUE, sbottom = 0; - for(long vl : zooms.keys()) { + int sleft = Integer.MAX_VALUE, sright = 0, stop = Integer.MAX_VALUE, sbottom = 0; + for (long vl : zooms.keys()) { long x = (vl >> SearchRequest.ZOOM_TO_SEARCH_POI) << (31 - SearchRequest.ZOOM_TO_SEARCH_POI); - long y = (vl & ((1 << SearchRequest.ZOOM_TO_SEARCH_POI) -1)) << (31 - SearchRequest.ZOOM_TO_SEARCH_POI); + long y = (vl & ((1 << SearchRequest.ZOOM_TO_SEARCH_POI) - 1)) << (31 - SearchRequest.ZOOM_TO_SEARCH_POI); sleft = (int) Math.min(x, sleft); stop = (int) Math.min(y, stop); sbottom = (int) Math.max(y, sbottom); @@ -1489,7 +1484,7 @@ public class BinaryMapIndexReader { request.zoom = zoom; request.poiTypeFilter = poiTypeFilter; request.resultMatcher = matcher; - + return request; } @@ -1501,14 +1496,12 @@ public class BinaryMapIndexReader { request.top = stop; request.bottom = sbottom; request.resultMatcher = matcher; - + return request; } - - - - - public static SearchRequest buildSearchPoiRequest(int x, int y, String nameFilter, int sleft, int sright, int stop, int sbottom, ResultMatcher resultMatcher){ + + + public static SearchRequest buildSearchPoiRequest(int x, int y, String nameFilter, int sleft, int sright, int stop, int sbottom, ResultMatcher resultMatcher) { SearchRequest request = new SearchRequest(); request.x = x; request.y = y; @@ -1520,9 +1513,9 @@ public class BinaryMapIndexReader { request.nameQuery = nameFilter; return request; } - - - public static SearchRequest buildSearchTransportRequest(int sleft, int sright, int stop, int sbottom, int limit, List stops){ + + + public static SearchRequest buildSearchTransportRequest(int sleft, int sright, int stop, int sbottom, int limit, List stops) { SearchRequest request = new SearchRequest(); if (stops != null) { request.searchResults = stops; @@ -1535,9 +1528,9 @@ public class BinaryMapIndexReader { request.limit = limit; return request; } - - public void close() throws IOException{ - if(codedIS != null){ + + public void close() throws IOException { + if (codedIS != null) { raf.close(); codedIS = null; mapIndexes.clear(); @@ -1545,20 +1538,20 @@ public class BinaryMapIndexReader { transportIndexes.clear(); } } - + public static interface SearchFilter { - + public boolean accept(TIntArrayList types, MapIndex index); - + } - + public static interface SearchPoiTypeFilter { - + public boolean accept(PoiCategory type, String subcategory); - + public boolean isEmpty(); } - + public static class MapObjectStat { public int lastStringNamesSize; public int lastObjectIdSize; @@ -1567,20 +1560,20 @@ public class BinaryMapIndexReader { public int lastObjectTypes; public int lastObjectCoordinates; - public int lastObjectSize ; + public int lastObjectSize; public int lastBlockStringTableSize; public int lastBlockHeaderInfo; - + public void addBlockHeader(int typesFieldNumber, int sizeL) { lastBlockHeaderInfo += CodedOutputStream.computeTagSize(typesFieldNumber) + - CodedOutputStream.computeRawVarint32Size(sizeL); + CodedOutputStream.computeRawVarint32Size(sizeL); } - + public void addTagHeader(int typesFieldNumber, int sizeL) { lastObjectHeaderInfo += CodedOutputStream.computeTagSize(typesFieldNumber) + - CodedOutputStream.computeRawVarint32Size(sizeL); + CodedOutputStream.computeRawVarint32Size(sizeL); } public void clearObjectStats() { @@ -1592,15 +1585,15 @@ public class BinaryMapIndexReader { lastObjectCoordinates = 0; } } - + public static class SearchRequest { - public final static int ZOOM_TO_SEARCH_POI = 16; + public final static int ZOOM_TO_SEARCH_POI = 16; private List searchResults = new ArrayList(); private boolean land = false; private boolean ocean = false; - + private ResultMatcher resultMatcher; - + // 31 zoom tiles // common variables int x = 0; @@ -1609,7 +1602,7 @@ public class BinaryMapIndexReader { int right = 0; int top = 0; int bottom = 0; - + int zoom = 15; int limit = -1; @@ -1617,24 +1610,24 @@ public class BinaryMapIndexReader { // stores tile of 16 index and pairs (even length always) of points intersecting tile TLongObjectHashMap> tiles = null; double radius = -1; - - + + String nameQuery = null; SearchFilter searchFilter = null; - + SearchPoiTypeFilter poiTypeFilter = null; - + // internal read information TIntObjectHashMap stringTable = null; - + // cache information TIntArrayList cacheCoordinates = new TIntArrayList(); TIntArrayList cacheTypes = new TIntArrayList(); - + MapObjectStat stat = new MapObjectStat(); - - + + // TRACE INFO public boolean log = true; int numberOfVisitedObjects = 0; @@ -1642,92 +1635,93 @@ public class BinaryMapIndexReader { int numberOfReadSubtrees = 0; int numberOfAcceptedSubtrees = 0; boolean interrupted = false; - - - protected SearchRequest(){ + + + protected SearchRequest() { } - + public long getTileHashOnPath(double lat, double lon) { long x = (int) MapUtils.getTileNumberX(SearchRequest.ZOOM_TO_SEARCH_POI, lon); long y = (int) MapUtils.getTileNumberY(SearchRequest.ZOOM_TO_SEARCH_POI, lat); return (x << SearchRequest.ZOOM_TO_SEARCH_POI) | y; } - - - public boolean publish(T obj){ - if(resultMatcher == null || resultMatcher.publish(obj)){ + + + public boolean publish(T obj) { + if (resultMatcher == null || resultMatcher.publish(obj)) { searchResults.add(obj); return true; } return false; } - - protected void publishOceanTile(boolean ocean){ - if(ocean) { + + protected void publishOceanTile(boolean ocean) { + if (ocean) { this.ocean = true; } else { this.land = true; } } - + public List getSearchResults() { return searchResults; } - + public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; } - + public boolean limitExceeded() { return limit != -1 && searchResults.size() > limit; } + public boolean isCancelled() { - if(this.interrupted){ + if (this.interrupted) { return interrupted; } - if(resultMatcher != null){ + if (resultMatcher != null) { return resultMatcher.isCancelled(); } return false; } - + public boolean isOcean() { return ocean; } - + public boolean isLand() { return land; } - - public boolean intersects(int l, int t, int r, int b){ + + public boolean intersects(int l, int t, int r, int b) { return r >= left && l <= right && t <= bottom && b >= top; } - - public boolean contains(int l, int t, int r, int b){ + + public boolean contains(int l, int t, int r, int b) { return r <= right && l >= left && b <= bottom && t >= top; } - + public int getLeft() { return left; } - + public int getRight() { return right; } - + public int getBottom() { return bottom; } - + public int getTop() { return top; } - + public int getZoom() { return zoom; } - - public void clearSearchResults(){ + + public void clearSearchResults() { // recreate whole list to allow GC collect old data searchResults = new ArrayList(); cacheCoordinates.clear(); @@ -1740,12 +1734,15 @@ public class BinaryMapIndexReader { numberOfAcceptedSubtrees = 0; } } - - + + public static class MapIndex extends BinaryIndexPart { + public String getPartName() { return "Map"; } + public int getFieldNumber() { return OsmandOdb.OsmAndStructure.MAPINDEX_FIELD_NUMBER; } + List roots = new ArrayList(); - - Map > encodingRules = new HashMap >(); + + Map> encodingRules = new HashMap>(); public TIntObjectMap decodingRules = new TIntObjectHashMap(); public int nameEncodingType = 0; public int nameEnEncodingType = -1; @@ -1757,20 +1754,20 @@ public class BinaryMapIndexReader { public int onewayReverseAttribute = -1; public TIntHashSet positiveLayers = new TIntHashSet(2); public TIntHashSet negativeLayers = new TIntHashSet(2); - - public Integer getRule(String t, String v){ + + public Integer getRule(String t, String v) { Map m = encodingRules.get(t); - if(m != null){ + if (m != null) { return m.get(v); } return null; } - + public List getRoots() { return roots; } - - public TagValuePair decodeType(int type){ + + public TagValuePair decodeType(int type) { return decodingRules.get(type); } @@ -1778,46 +1775,46 @@ public class BinaryMapIndexReader { int free = decodingRules.size() * 2 + 1; coastlineBrokenEncodingType = free++; initMapEncodingRule(0, coastlineBrokenEncodingType, "natural", "coastline_broken"); - if(landEncodingType == -1){ + if (landEncodingType == -1) { landEncodingType = free++; initMapEncodingRule(0, landEncodingType, "natural", "land"); } } - + public boolean isRegisteredRule(int id) { return decodingRules.containsKey(id); } - + public void initMapEncodingRule(int type, int id, String tag, String val) { - if(!encodingRules.containsKey(tag)){ + if (!encodingRules.containsKey(tag)) { encodingRules.put(tag, new HashMap()); } encodingRules.get(tag).put(val, id); - if(!decodingRules.containsKey(id)){ + if (!decodingRules.containsKey(id)) { decodingRules.put(id, new TagValuePair(tag, val, type)); } - - if("name".equals(tag)){ + + if ("name".equals(tag)) { nameEncodingType = id; - } else if("natural".equals(tag) && "coastline".equals(val)){ + } else if ("natural".equals(tag) && "coastline".equals(val)) { coastlineEncodingType = id; - } else if("natural".equals(tag) && "land".equals(val)){ + } else if ("natural".equals(tag) && "land".equals(val)) { landEncodingType = id; - } else if("oneway".equals(tag) && "yes".equals(val)){ + } else if ("oneway".equals(tag) && "yes".equals(val)) { onewayAttribute = id; - } else if("oneway".equals(tag) && "-1".equals(val)){ + } else if ("oneway".equals(tag) && "-1".equals(val)) { onewayReverseAttribute = id; - } else if("ref".equals(tag)){ + } else if ("ref".equals(tag)) { refEncodingType = id; - } else if("name:en".equals(tag)){ + } else if ("name:en".equals(tag)) { nameEnEncodingType = id; - } else if("tunnel".equals(tag)){ + } else if ("tunnel".equals(tag)) { negativeLayers.add(id); - } else if("bridge".equals(tag)){ + } else if ("bridge".equals(tag)) { positiveLayers.add(id); - } else if("layer".equals(tag)){ - if(val != null && !val.equals("0") && val.length() > 0) { - if(val.startsWith("-")) { + } else if ("layer".equals(tag)) { + if (val != null && !val.equals("0") && val.length() > 0) { + if (val.startsWith("-")) { negativeLayers.add(id); } else { positiveLayers.add(id); @@ -1826,7 +1823,7 @@ public class BinaryMapIndexReader { } } - public boolean isBaseMap(){ + public boolean isBaseMap() { return name != null && name.toLowerCase().contains(BASEMAP_NAME); } @@ -1838,21 +1835,21 @@ public class BinaryMapIndexReader { return OsmandOdb.OsmAndStructure.MAPINDEX_FIELD_NUMBER; } } - + public static class TagValuePair { public String tag; public String value; public int additionalAttribute; - - + + public TagValuePair(String tag, String value, int additionalAttribute) { super(); this.tag = tag; this.value = value; this.additionalAttribute = additionalAttribute; } - - public boolean isAdditional(){ + + public boolean isAdditional() { return additionalAttribute % 2 == 1; } @@ -1865,14 +1862,14 @@ public class BinaryMapIndexReader { result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } - - public String toSimpleString(){ - if(value == null){ + + public String toSimpleString() { + if (value == null) { return tag; } - return tag+"-"+value; + return tag + "-" + value; } - + @Override public String toString() { return "TagValuePair : " + tag + " - " + value; @@ -1901,66 +1898,71 @@ public class BinaryMapIndexReader { return false; return true; } - + } - - + + public static class MapRoot extends MapTree { int minZoom = 0; int maxZoom = 0; - - + + public int getMinZoom() { return minZoom; } + public int getMaxZoom() { return maxZoom; } - + private List trees = null; } - + private static class MapTree { int filePointer = 0; int length = 0; - + long mapDataBlock = 0; Boolean ocean = null; - + int left = 0; int right = 0; int top = 0; int bottom = 0; - + public int getLeft() { return left; } + public int getRight() { return right; } + public int getTop() { return top; } + public int getBottom() { return bottom; } - + public int getLength() { return length; } + public int getFilePointer() { return filePointer; } - + @Override - public String toString(){ + public String toString() { return "Top Lat " + ((float) MapUtils.get31LatitudeY(top)) + " lon " + ((float) MapUtils.get31LongitudeX(left)) + " Bottom lat " + ((float) MapUtils.get31LatitudeY(bottom)) + " lon " + ((float) MapUtils.get31LongitudeX(right)); } - + } - + private static boolean testMapSearch = false; private static boolean testAddressSearch = true; private static boolean testAddressJustifySearch = false; @@ -1972,16 +1974,16 @@ public class BinaryMapIndexReader { private static int stop = MapUtils.get31TileNumberY(49.9); private static int sbottom = MapUtils.get31TileNumberY(49.7); private static int szoom = 15; - - private static void println(String s){ + + private static void println(String s) { System.out.println(s); } - + public static void main(String[] args) throws IOException { // File fl = new File("/Users/victorshcherb/osmand/maps/Synthetic_test_rendering.obf"); File fl = new File("/Users/victorshcherb/osmand/maps/Argentina_southamerica_2.obf"); RandomAccessFile raf = new RandomAccessFile(fl, "r"); - + BinaryMapIndexReader reader = new BinaryMapIndexReader(raf, fl); println("VERSION " + reader.getVersion()); //$NON-NLS-1$ long time = System.currentTimeMillis(); @@ -1989,24 +1991,24 @@ public class BinaryMapIndexReader { if (testMapSearch) { testMapSearch(reader); } - if(testAddressSearch) { + if (testAddressSearch) { testAddressSearchByName(reader); testAddressSearch(reader); } - if(testAddressJustifySearch) { + if (testAddressJustifySearch) { testAddressJustifySearch(reader); } - if(testTransportSearch) { + if (testTransportSearch) { testTransportSearch(reader); } if (testPoiSearch || testPoiSearchOnPath) { PoiRegion poiRegion = reader.getPoiIndexes().get(0); - if(testPoiSearch) { + if (testPoiSearch) { testPoiSearch(reader, poiRegion); testPoiSearchByName(reader); } - if(testPoiSearchOnPath) { + if (testPoiSearchOnPath) { testSearchOnthePath(reader); } } @@ -2046,7 +2048,7 @@ public class BinaryMapIndexReader { for (Amenity a : results) { final float dds = dist(a.getLocation(), locations); if (dds <= radius) { - println("+ " + a.getType() + " " + a.getSubType() + " Dist " + dds + " (=" + (float)a.getRoutePoint().deviateDistance + ") " + a.getName() + " " + a.getLocation()); + println("+ " + a.getType() + " " + a.getSubType() + " Dist " + dds + " (=" + (float) a.getRoutePoint().deviateDistance + ") " + a.getName() + " " + a.getLocation()); k++; } else { println(a.getType() + " " + a.getSubType() + " Dist " + dds + " " + a.getName() + " " + a.getLocation()); @@ -2054,12 +2056,12 @@ public class BinaryMapIndexReader { } println("Filtered in " + (System.currentTimeMillis() - now) + "ms " + k + " of " + results.size()); } - + private static float dist(LatLon l, List locations) { float dist = Float.POSITIVE_INFINITY; - for(int i = 1; i < locations.size(); i++){ - dist = Math.min(dist,(float) MapUtils.getOrthogonalDistance(l.getLatitude(), l.getLongitude(), - locations.get(i-1).getLatitude(), locations.get(i-1).getLongitude(), + for (int i = 1; i < locations.size(); i++) { + dist = Math.min(dist, (float) MapUtils.getOrthogonalDistance(l.getLatitude(), l.getLongitude(), + locations.get(i - 1).getLatitude(), locations.get(i - 1).getLongitude(), locations.get(i).getLatitude(), locations.get(i).getLongitude())); } return dist; @@ -2080,14 +2082,14 @@ public class BinaryMapIndexReader { } return new InputStreamReader(bis, "UTF-8"); } - + private static List readGPX(File f) { - List res = new ArrayList(); - try { - StringBuilder content = new StringBuilder(); - BufferedReader reader = new BufferedReader(getUTF8Reader(new FileInputStream(f))); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dom = factory.newDocumentBuilder(); + List res = new ArrayList(); + try { + StringBuilder content = new StringBuilder(); + BufferedReader reader = new BufferedReader(getUTF8Reader(new FileInputStream(f))); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dom = factory.newDocumentBuilder(); // { // String s = null; // boolean fist = true; @@ -2099,38 +2101,38 @@ public class BinaryMapIndexReader { // } // } // Document doc = dom.parse(new InputSource(new StringReader(content.toString()))); - Document doc = dom.parse(new InputSource(reader)); - NodeList list = doc.getElementsByTagName("trkpt"); - Way w = new Way(-1); - for (int i = 0; i < list.getLength(); i++) { - Element item = (Element) list.item(i); - try { - double lon = Double.parseDouble(item.getAttribute("lon")); - double lat = Double.parseDouble(item.getAttribute("lat")); - final Location o = new Location(""); - o.setLatitude(lat); - o.setLongitude(lon); - res.add(o); - } catch (NumberFormatException e) { - } + Document doc = dom.parse(new InputSource(reader)); + NodeList list = doc.getElementsByTagName("trkpt"); + Way w = new Way(-1); + for (int i = 0; i < list.getLength(); i++) { + Element item = (Element) list.item(i); + try { + double lon = Double.parseDouble(item.getAttribute("lon")); + double lat = Double.parseDouble(item.getAttribute("lat")); + final Location o = new Location(""); + o.setLatitude(lat); + o.setLongitude(lon); + res.add(o); + } catch (NumberFormatException e) { } - } catch (IOException e) { - throw new RuntimeException(e); - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } catch (SAXException e) { - throw new RuntimeException(e); } - return res; + } catch (IOException e) { + throw new RuntimeException(e); + } catch (ParserConfigurationException e) { + throw new RuntimeException(e); + } catch (SAXException e) { + throw new RuntimeException(e); } + return res; + } private static void testPoiSearchByName(BinaryMapIndexReader reader) throws IOException { println("Searching by name..."); - SearchRequest req = buildSearchPoiRequest(0, 0, "aBS", + SearchRequest req = buildSearchPoiRequest(0, 0, "aBS", 0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE, null); reader.searchPoiByName(req); for (Amenity a : req.getSearchResults()) { - println(a.getType().getTranslation() + + println(a.getType().getTranslation() + " " + a.getSubType() + " " + a.getName() + " " + a.getLocation()); } } @@ -2180,26 +2182,26 @@ public class BinaryMapIndexReader { for (TransportStop s : reader.searchTransportIndex(buildSearchTransportRequest(sleft, sright, stop, sbottom, 16, null))) { println(s.getName()); TIntObjectHashMap routes = reader.getTransportRoutes(s.getReferencesToRoutes()); - for (net.osmand.data.TransportRoute route : routes.valueCollection()) { + for (net.osmand.data.TransportRoute route : routes.valueCollection()) { println(" " + route.getRef() + " " + route.getName() + " " + route.getDistance() + " " + route.getAvgBothDistance()); } } } } - - private static void updateFrequence(Map street , String key){ - if(!street.containsKey(key)){ + + private static void updateFrequence(Map street, String key) { + if (!street.containsKey(key)) { street.put(key, 1); } else { street.put(key, street.get(key) + 1); } - + } int readIndexedStringTable(Collator instance, String query, String prefix, TIntArrayList list, int charMatches) throws IOException { String key = null; - while(true){ + while (true) { int t = codedIS.readTag(); int tag = WireFormat.getTagFieldNumber(t); switch (tag) { @@ -2256,18 +2258,19 @@ public class BinaryMapIndexReader { } } } - + private static void testAddressSearchByName(BinaryMapIndexReader reader) throws IOException { SearchRequest req = buildAddressByNameRequest(new ResultMatcher() { @Override public boolean publish(MapObject object) { - if(object instanceof Street) { + if (object instanceof Street) { System.out.println(object + " " + ((Street) object).getCity()); } else { System.out.println(object + " " + object.getId()); } return false; } + @Override public boolean isCancelled() { return false; @@ -2275,7 +2278,7 @@ public class BinaryMapIndexReader { }, "Reynaldo"); reader.searchAddressDataByName(req); } - + /** * @param reader * @throws IOException @@ -2293,8 +2296,8 @@ public class BinaryMapIndexReader { SearchRequest req = buildAddressByNameRequest(new ResultMatcher() { @Override public boolean publish(MapObject object) { - if(object instanceof Street && object.getName().equalsIgnoreCase(streetName)) { - if(MapUtils.getDistance(object.getLocation(), lat, lon) < 20000) { + if (object instanceof Street && object.getName().equalsIgnoreCase(streetName)) { + if (MapUtils.getDistance(object.getLocation(), lat, lon) < 20000) { streetsList.add((Street) object); return true; } @@ -2302,6 +2305,7 @@ public class BinaryMapIndexReader { } return false; } + @Override public boolean isCancelled() { return false; @@ -2314,41 +2318,41 @@ public class BinaryMapIndexReader { public int compare(MapObject o1, MapObject o2) { LatLon l1 = o1.getLocation(); LatLon l2 = o2.getLocation(); - if(l1 == null || l2 == null){ + if (l1 == null || l2 == null) { return l2 == l1 ? 0 : (l1 == null ? -1 : 1); } return Double.compare(MapUtils.getDistance(l1, lat, lon), MapUtils.getDistance(l2, lat, lon)); } }); - for(Street s : streetsList) { + for (Street s : streetsList) { resMap.put(s, s); reader.preloadBuildings(s, null); - for(Building b : s.getBuildings()) { - if(MapUtils.getDistance(b.getLocation(), lat, lon) < 100) { + for (Building b : s.getBuildings()) { + if (MapUtils.getDistance(b.getLocation(), lat, lon) < 100) { resMap.put(b, s); } } } - for(MapObject e : resMap.keySet()) { + for (MapObject e : resMap.keySet()) { Street s = resMap.get(e); - if(e instanceof Building && MapUtils.getDistance(e.getLocation(), lat, lon) < 40) { + if (e instanceof Building && MapUtils.getDistance(e.getLocation(), lat, lon) < 40) { Building b = (Building) e; System.out.println(b.getName() + " " + s); - } else if(e instanceof Street){ + } else if (e instanceof Street) { System.out.println(s + " " + ((Street) s).getCity()); } } - + } - + private static void testAddressSearch(BinaryMapIndexReader reader) throws IOException { // test address index search final Map streetFreq = new HashMap(); List cs = reader.getCities(null, BinaryMapAddressReaderAdapter.CITY_TOWN_TYPE); - for(City c : cs){ + for (City c : cs) { int buildings = 0; reader.preloadStreets(c, null); - for(Street s : c.getStreets()){ + for (Street s : c.getStreets()) { updateFrequence(streetFreq, s.getName()); reader.preloadBuildings(s, buildAddressRequest((ResultMatcher) null)); buildings += s.getBuildings().size(); @@ -2358,29 +2362,29 @@ public class BinaryMapIndexReader { } // int[] count = new int[1]; List villages = reader.getCities(buildAddressRequest((ResultMatcher) null), BinaryMapAddressReaderAdapter.VILLAGES_TYPE); - for(City v : villages) { - reader.preloadStreets(v, null); - for(Street s : v.getStreets()){ + for (City v : villages) { + reader.preloadStreets(v, null); + for (Street s : v.getStreets()) { updateFrequence(streetFreq, s.getName()); } } System.out.println("Villages " + villages.size()); - + List sorted = new ArrayList(streetFreq.keySet()); Collections.sort(sorted, new Comparator() { @Override public int compare(String o1, String o2) { - return - streetFreq.get(o1) + streetFreq.get(o2); + return -streetFreq.get(o1) + streetFreq.get(o2); } }); System.out.println(streetFreq.size()); - for(String s : sorted) { + for (String s : sorted) { System.out.println(s + " " + streetFreq.get(s)); - if(streetFreq.get(s) < 10){ + if (streetFreq.get(s) < 10) { break; } } - + } private static void testMapSearch(BinaryMapIndexReader reader) throws IOException { @@ -2388,50 +2392,50 @@ public class BinaryMapIndexReader { println("SEARCH " + sleft + " " + sright + " " + stop + " " + sbottom); reader.searchMapIndex(buildSearchRequest(sleft, sright, stop, sbottom, szoom, null, new ResultMatcher() { - + @Override public boolean publish(BinaryMapDataObject obj) { - + StringBuilder b = new StringBuilder(); - b.append(obj.area? "Area" : (obj.getPointsLength() > 1? "Way" : "Point")); + b.append(obj.area ? "Area" : (obj.getPointsLength() > 1 ? "Way" : "Point")); int[] types = obj.getTypes(); b.append(" types ["); - for(int j = 0; j 0) { + for (int j = 0; j < types.length; j++) { + if (j > 0) { b.append(", "); } TagValuePair pair = obj.getMapIndex().decodeType(types[j]); - if(pair == null) { + if (pair == null) { throw new NullPointerException("Type " + types[j] + "was not found"); } b.append(pair.toSimpleString()).append("(").append(types[j]).append(")"); } b.append("]"); - if(obj.getAdditionalTypes() != null && obj.getAdditionalTypes().length > 0){ + if (obj.getAdditionalTypes() != null && obj.getAdditionalTypes().length > 0) { b.append(" add_types ["); - for(int j = 0; j 0) { + for (int j = 0; j < obj.getAdditionalTypes().length; j++) { + if (j > 0) { b.append(", "); } TagValuePair pair = obj.getMapIndex().decodeType(obj.getAdditionalTypes()[j]); - if(pair == null) { + if (pair == null) { throw new NullPointerException("Type " + obj.getAdditionalTypes()[j] + "was not found"); } b.append(pair.toSimpleString()).append("(").append(obj.getAdditionalTypes()[j]).append(")"); - + } b.append("]"); } TIntObjectHashMap names = obj.getObjectNames(); - if(names != null && !names.isEmpty()) { + if (names != null && !names.isEmpty()) { b.append(" Names ["); int[] keys = names.keys(); - for(int j = 0; j 0) { + for (int j = 0; j < keys.length; j++) { + if (j > 0) { b.append(", "); } TagValuePair pair = obj.getMapIndex().decodeType(keys[j]); - if(pair == null) { + if (pair == null) { throw new NullPointerException("Type " + keys[j] + "was not found"); } b.append(pair.toSimpleString()).append("(").append(keys[j]).append(")"); @@ -2439,10 +2443,10 @@ public class BinaryMapIndexReader { } b.append("]"); } - + b.append(" id ").append((obj.getId() >> 1)); b.append(" lat/lon : "); - for(int i=0; i searchRouteIndexTree(SearchRequest req, List list) throws IOException { req.numberOfVisitedObjects = 0; req.numberOfAcceptedObjects = 0; @@ -2473,24 +2477,23 @@ public class BinaryMapIndexReader { } public void loadRouteIndexData(List toLoad, ResultMatcher matcher) throws IOException { - if(routeAdapter != null){ + if (routeAdapter != null) { routeAdapter.loadRouteRegionData(toLoad, matcher); } } - + public List loadRouteIndexData(RouteSubregion rs) throws IOException { - if(routeAdapter != null){ + if (routeAdapter != null) { return routeAdapter.loadRouteRegionData(rs); } return Collections.emptyList(); } - + public void initRouteRegion(RouteRegion routeReg) throws IOException { - if(routeAdapter != null){ + if (routeAdapter != null) { routeAdapter.initRouteRegion(routeReg); } } - - -} \ No newline at end of file + +}