diff --git a/brouter-core/src/main/java/btools/router/RoutingEngine.java b/brouter-core/src/main/java/btools/router/RoutingEngine.java index 1f9c99b..18585a1 100644 --- a/brouter-core/src/main/java/btools/router/RoutingEngine.java +++ b/brouter-core/src/main/java/btools/router/RoutingEngine.java @@ -41,7 +41,7 @@ public class RoutingEngine extends Thread private volatile boolean terminated; - protected String segmentDir; + protected File segmentDir; private String outfileBase; private String logfileBase; private boolean infoLogEnabled; @@ -64,7 +64,7 @@ public class RoutingEngine extends Thread private boolean directWeaving = !Boolean.getBoolean( "disableDirectWeaving" ); - public RoutingEngine( String outfileBase, String logfileBase, String segmentDir, + public RoutingEngine( String outfileBase, String logfileBase, File segmentDir, List waypoints, RoutingContext rc ) { this.segmentDir = segmentDir; diff --git a/brouter-core/src/main/java/btools/router/RoutingHelper.java b/brouter-core/src/main/java/btools/router/RoutingHelper.java index 36866f8..ae723ea 100644 --- a/brouter-core/src/main/java/btools/router/RoutingHelper.java +++ b/brouter-core/src/main/java/btools/router/RoutingHelper.java @@ -11,20 +11,20 @@ import btools.mapaccess.StorageConfigHelper; public final class RoutingHelper { - public static File getAdditionalMaptoolDir( String segmentDir ) + public static File getAdditionalMaptoolDir( File segmentDir ) { return StorageConfigHelper.getAdditionalMaptoolDir(segmentDir); } - public static File getSecondarySegmentDir( String segmentDir ) + public static File getSecondarySegmentDir( File segmentDir ) { return StorageConfigHelper.getSecondarySegmentDir(segmentDir); } - public static boolean hasDirectoryAnyDatafiles( String segmentDir ) + public static boolean hasDirectoryAnyDatafiles( File segmentDir ) { - if ( hasAnyDatafiles( new File( segmentDir ) ) ) + if ( hasAnyDatafiles( segmentDir ) ) { return true; } diff --git a/brouter-mapaccess/src/main/java/btools/mapaccess/NodesCache.java b/brouter-mapaccess/src/main/java/btools/mapaccess/NodesCache.java index ebf4fe9..14d117f 100644 --- a/brouter-mapaccess/src/main/java/btools/mapaccess/NodesCache.java +++ b/brouter-mapaccess/src/main/java/btools/mapaccess/NodesCache.java @@ -56,10 +56,10 @@ public final class NodesCache return "collecting=" + garbageCollectionEnabled + " noGhosts=" + ghostCleaningDone + " cacheSum=" + cacheSum + " cacheSumClean=" + cacheSumClean + " ghostSum=" + ghostSum + " ghostWakeup=" + ghostWakeup ; } - public NodesCache( String segmentDir, BExpressionContextWay ctxWay, boolean forceSecondaryData, long maxmem, NodesCache oldCache, boolean detailed ) + public NodesCache( File segmentDir, BExpressionContextWay ctxWay, boolean forceSecondaryData, long maxmem, NodesCache oldCache, boolean detailed ) { this.maxmemtiles = maxmem / 8; - this.segmentDir = new File( segmentDir ); + this.segmentDir = segmentDir; this.nodesMap = new OsmNodesMap(); this.nodesMap.maxmem = (2L*maxmem) / 3L; this.expCtxWay = ctxWay; @@ -77,7 +77,7 @@ public final class NodesCache first_file_access_name = null; if ( !this.segmentDir.isDirectory() ) - throw new RuntimeException( "segment directory " + segmentDir + " does not exist" ); + throw new RuntimeException( "segment directory " + segmentDir.getAbsolutePath () + " does not exist" ); if ( oldCache != null ) { diff --git a/brouter-mapaccess/src/main/java/btools/mapaccess/StorageConfigHelper.java b/brouter-mapaccess/src/main/java/btools/mapaccess/StorageConfigHelper.java index 923d05d..094eb0e 100644 --- a/brouter-mapaccess/src/main/java/btools/mapaccess/StorageConfigHelper.java +++ b/brouter-mapaccess/src/main/java/btools/mapaccess/StorageConfigHelper.java @@ -11,21 +11,21 @@ import java.io.FileReader; public class StorageConfigHelper { - public static File getSecondarySegmentDir( String segmentDir ) + public static File getSecondarySegmentDir( File segmentDir ) { return getStorageLocation( segmentDir, "secondary_segment_dir=" ); } - public static File getAdditionalMaptoolDir( String segmentDir ) + public static File getAdditionalMaptoolDir( File segmentDir ) { return getStorageLocation( segmentDir, "additional_maptool_dir=" ); } - private static File getStorageLocation( String segmentDir, String tag ) + private static File getStorageLocation( File segmentDir, String tag ) { File res = null; BufferedReader br = null; - String configFile = segmentDir + "/storageconfig.txt"; + File configFile = new File (segmentDir, "storageconfig.txt"); try { br = new BufferedReader( new FileReader( configFile ) ); @@ -38,7 +38,7 @@ public class StorageConfigHelper if ( line.startsWith( tag ) ) { String path = line.substring( tag.length() ).trim(); - res = path.startsWith( "/" ) ? new File( path ) : new File( new File( segmentDir ), path ); + res = path.startsWith( "/" ) ? new File( path ) : new File( segmentDir, path ); if ( !res.exists() ) res = null; break; } diff --git a/brouter-routing-app/build.gradle b/brouter-routing-app/build.gradle index a54bf48..4ee2104 100644 --- a/brouter-routing-app/build.gradle +++ b/brouter-routing-app/build.gradle @@ -9,6 +9,7 @@ android { applicationId "btools.routingapp" minSdkVersion 19 targetSdkVersion 30 + versionCode 41 versionName "1.6.1" @@ -69,7 +70,7 @@ android { } dependencies { - + implementation 'androidx.appcompat:appcompat:1.3.0' implementation project(':brouter-mapaccess') diff --git a/brouter-routing-app/src/main/java/btools/routingapp/BInstallerView.java b/brouter-routing-app/src/main/java/btools/routingapp/BInstallerView.java index b5e0422..1e30a30 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/BInstallerView.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/BInstallerView.java @@ -58,7 +58,7 @@ public class BInstallerView extends View private boolean tilesVisible = false; private long availableSize; - private String baseDir; + private File baseDir; private boolean isDownloading = false; private volatile boolean downloadCanceled = false; @@ -207,7 +207,7 @@ public class BInstallerView extends View private void deleteRawTracks() { - File modeDir = new File( baseDir + "/brouter/modes" ); + File modeDir = new File( baseDir, "brouter/modes" ); String[] fileNames = modeDir.list(); if ( fileNames == null ) return; for( String fileName : fileNames ) @@ -224,9 +224,9 @@ public class BInstallerView extends View { clearTileSelection( MASK_INSTALLED_RD5 | MASK_CURRENT_RD5 ); - scanExistingFiles( new File( baseDir + "/brouter/segments4" ) ); + scanExistingFiles( new File( baseDir, "brouter/segments4" ) ); - File secondary = RoutingHelper.getSecondarySegmentDir( baseDir + "/brouter/segments4" ); + File secondary = RoutingHelper.getSecondarySegmentDir( new File ( baseDir, "brouter/segments4" ) ); if ( secondary != null ) { scanExistingFiles( secondary ); @@ -235,7 +235,7 @@ public class BInstallerView extends View availableSize = -1; try { - StatFs stat = new StatFs(baseDir); + StatFs stat = new StatFs(baseDir.getAbsolutePath ()); availableSize = (long)stat.getAvailableBlocks()*stat.getBlockSize(); } catch (Exception e) { /* ignore */ } @@ -472,7 +472,7 @@ float tx, ty; int tidx = gridPos2Tileindex( ix, iy ); if ( ( tileStatus[tidx] & MASK_DELETED_RD5 ) != 0 ) { - new File( baseDir + "/brouter/segments4/" + baseNameForTile( tidx ) + ".rd5").delete(); + new File( baseDir, "brouter/segments4/" + baseNameForTile( tidx ) + ".rd5").delete(); } } } @@ -667,7 +667,7 @@ float tx, ty; OutputStream output = null; HttpURLConnection connection = null; String surl = sUrls[0]; - String fname = null; + File fname = null; File tmp_file = null; try { @@ -676,17 +676,17 @@ float tx, ty; int slidx = surl.lastIndexOf( "segments4/" ); String name = surl.substring( slidx+10 ); String surlBase = surl.substring( 0, slidx+10 ); - fname = baseDir + "/brouter/segments4/" + name; + fname = new File (baseDir, "brouter/segments4/" + name); boolean delta = true; - File targetFile = new File( fname ); - if ( targetFile.exists() ) + if ( fname.exists() ) { updateProgress( "Calculating local checksum.." ); // first check for a delta file - String md5 = Rd5DiffManager.getMD5( targetFile ); + + String md5 = Rd5DiffManager.getMD5( fname ); String surlDelta = surlBase + "diff/" + name.replace( ".rd5", "/" + md5 + ".df5" ); URL urlDelta = new URL(surlDelta); @@ -728,7 +728,7 @@ float tx, ty; // download the file input = connection.getInputStream(); - tmp_file = new File( fname + ( delta ? "_diff" : "_tmp" ) ); + tmp_file = new File( fname.getAbsolutePath() + ( delta ? "_diff" : "_tmp" ) ); output = new FileOutputStream( tmp_file ); byte data[] = new byte[4096]; @@ -768,7 +768,7 @@ float tx, ty; updateProgress( "Applying delta.." ); File diffFile = tmp_file; tmp_file = new File( fname + "_tmp" ); - Rd5DiffTool.recoverFromDelta( targetFile, diffFile, tmp_file, this ); + Rd5DiffTool.recoverFromDelta( fname, diffFile, tmp_file, this ); diffFile.delete(); } if (isDownloadCanceled()) @@ -781,9 +781,9 @@ float tx, ty; String check_result = PhysicalFile.checkFileIntegrity( tmp_file ); if ( check_result != null ) return check_result; - if ( !tmp_file.renameTo( targetFile ) ) + if ( !tmp_file.renameTo( fname ) ) { - return "Could not rename to " + targetFile; + return "Could not rename to " + fname.getAbsolutePath(); } deleteRawTracks(); // invalidate raw-tracks after data update } diff --git a/brouter-routing-app/src/main/java/btools/routingapp/BRouterActivity.java b/brouter-routing-app/src/main/java/btools/routingapp/BRouterActivity.java index 21bbdb5..aba0eab 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/BRouterActivity.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/BRouterActivity.java @@ -1,5 +1,6 @@ package btools.routingapp; +import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; @@ -13,16 +14,22 @@ import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; +import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.os.Bundle; +import android.os.Environment; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.StatFs; import android.speech.tts.TextToSpeech.OnInitListener; +import android.util.Log; import android.widget.EditText; + +import androidx.core.app.ActivityCompat; + import btools.router.OsmNodeNamed; -public class BRouterActivity extends Activity implements OnInitListener +public class BRouterActivity extends Activity implements OnInitListener, ActivityCompat.OnRequestPermissionsResultCallback { private static final int DIALOG_SELECTPROFILE_ID = 1; private static final int DIALOG_EXCEPTION_ID = 2; @@ -268,13 +275,14 @@ public class BRouterActivity extends Activity implements OnInitListener public void onClick( DialogInterface dialog, int whichButton ) { String basedir = input.getText().toString(); - mBRouterView.startSetup( basedir, true ); + mBRouterView.startSetup( new File(basedir), true ); } } ); return builder.create(); case DIALOG_SELECTBASEDIR_ID: builder = new AlertDialog.Builder( this ); - builder.setTitle( "Select an SDCARD base dir:" ); + builder.setTitle( "Choose brouter data base dir:" ); + // builder.setMessage( message ); builder.setSingleChoiceItems( basedirOptions, 0, new DialogInterface.OnClickListener() { @Override @@ -428,7 +436,7 @@ public class BRouterActivity extends Activity implements OnInitListener private String[] availableProfiles; private String selectedProfile = null; - private List availableBasedirs; + private List availableBasedirs; private String[] basedirOptions; private int selectedBasedir; @@ -484,22 +492,21 @@ public class BRouterActivity extends Activity implements OnInitListener } @SuppressWarnings("deprecation") - public void selectBasedir( List items, String defaultBasedir, String message ) + public void selectBasedir( ArrayList items, String defaultBasedir, String message ) { this.defaultbasedir = defaultBasedir; this.message = message; - availableBasedirs = new ArrayList(); + availableBasedirs = items; ArrayList dirFreeSizes = new ArrayList(); - for ( String d : items ) + for ( File f : items ) { long size = 0L; try { - StatFs stat = new StatFs( d ); + StatFs stat = new StatFs( f.getAbsolutePath() ); size = (long) stat.getAvailableBlocks() * stat.getBlockSize(); } catch (Exception e) { /* ignore */ } - availableBasedirs.add( d ); dirFreeSizes.add( Long.valueOf( size ) ); } @@ -510,7 +517,7 @@ public class BRouterActivity extends Activity implements OnInitListener { basedirOptions[bdidx++] = availableBasedirs.get( idx ) + " (" + df.format( dirFreeSizes.get( idx ) / 1024. / 1024. / 1024. ) + " GB free)"; } - basedirOptions[bdidx] = "Other"; + basedirOptions[bdidx] = "Enter path manually"; showDialog( DIALOG_SELECTBASEDIR_ID ); } @@ -644,4 +651,15 @@ public class BRouterActivity extends Activity implements OnInitListener public void onInit( int i ) { } + + @Override + public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) { + if (requestCode == 0) { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + mBRouterView.startSetup(null, true); + } else { + mBRouterView.init(); + } + } + } } diff --git a/brouter-routing-app/src/main/java/btools/routingapp/BRouterService.java b/brouter-routing-app/src/main/java/btools/routingapp/BRouterService.java index 5b7d9fb..93d2c86 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/BRouterService.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/BRouterService.java @@ -11,6 +11,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; import java.util.zip.GZIPOutputStream; import java.util.ArrayList; @@ -58,7 +59,7 @@ public class BRouterService extends Service if ( configInput != null ) try { configInput.close(); } catch (Exception ee) {} } worker.baseDir = baseDir; - worker.segmentDir = baseDir + "/brouter/segments4"; + worker.segmentDir = new File (baseDir, "brouter/segments4" ); String remoteProfile = params.getString( "remoteProfile" ); @@ -85,9 +86,9 @@ public class BRouterService extends Service try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write( "z64".getBytes("UTF-8") ); // marker prefix + baos.write( "z64".getBytes(StandardCharsets.UTF_8) ); // marker prefix OutputStream os = new GZIPOutputStream( baos ); - byte[] ab = gpxMessage.getBytes("UTF-8"); + byte[] ab = gpxMessage.getBytes(StandardCharsets.UTF_8); gpxMessage = null; os.write( ab ); ab = null; diff --git a/brouter-routing-app/src/main/java/btools/routingapp/BRouterView.java b/brouter-routing-app/src/main/java/btools/routingapp/BRouterView.java index bfb1f98..146f28c 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/BRouterView.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/BRouterView.java @@ -12,6 +12,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.StringTokenizer; @@ -19,16 +20,24 @@ import java.util.TreeMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import android.Manifest; import android.app.Activity; import android.content.Context; +import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Environment; import android.util.DisplayMetrics; +import android.util.Log; import android.view.View; import android.widget.Toast; + +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.core.os.EnvironmentCompat; + import btools.expressions.BExpressionContextWay; import btools.expressions.BExpressionMetaData; import btools.mapaccess.OsmNode; @@ -57,10 +66,11 @@ public class BRouterView extends View private List nogoVetoList; private OsmTrack rawTrack; - private String modesDir; - private String tracksDir; - private String segmentDir; - private String profileDir; + private File retryBaseDir; + private File modesDir; + private File tracksDir; + private File segmentDir; + private File profileDir; private String profilePath; private String profileName; private String sourceHint; @@ -104,14 +114,13 @@ public class BRouterView extends View imgh = metrics.heightPixels; // get base dir from private file - String baseDir = ConfigHelper.getBaseDir( getContext() ); + File baseDir = ConfigHelper.getBaseDir( getContext() ); // check if valid boolean bdValid = false; if ( baseDir != null ) { - File bd = new File( baseDir ); - bdValid = bd.isDirectory(); - File brd = new File( bd, "brouter" ); + bdValid = baseDir.isDirectory(); + File brd = new File( baseDir, "brouter" ); if ( brd.isDirectory() ) { startSetup( baseDir, false ); @@ -135,64 +144,59 @@ public class BRouterView extends View } } - public void startSetup( String baseDir, boolean storeBasedir ) + public void startSetup( File baseDir, boolean storeBasedir ) { - cor = null; + if (baseDir == null) { + baseDir = retryBaseDir; + retryBaseDir = null; + } + + if ( storeBasedir ) + { + File td = new File( baseDir, "brouter" ); + try + { + td.mkdirs(); + } + catch (Exception e) { + Log.d ("BRouterView", "Error creating base directory: " + e.getMessage()); + e.printStackTrace(); + } + + if ( !td.isDirectory() ) { + if (ContextCompat.checkSelfPermission (getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { + retryBaseDir = baseDir; + ActivityCompat.requestPermissions ((BRouterActivity) getContext(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0); + } else { + ( (BRouterActivity) getContext() ).selectBasedir( getStorageDirectories (), guessBaseDir(), "Cannot access " + baseDir.getAbsolutePath () + "; select another"); + } + return; + } + ConfigHelper.writeBaseDir( getContext(), baseDir ); + } try { - File fbd = new File( baseDir ); - if ( !fbd.isDirectory() ) - { - throw new IllegalArgumentException( "Base-directory " + baseDir + " is not a directory " ); - } - if ( storeBasedir ) - { - // Android 4.4 patch: try extend the basedir if not valid - File td = new File( fbd, "brouter" ); - try - { - td.mkdir(); - } - catch (Exception e) {} - if ( !td.isDirectory() ) - { - File td1 = new File( fbd, "Android/data/btools/routingapp" ); - try - { - td1.mkdirs(); - } - catch (Exception e){} - td = new File( td1, "brouter" ); - try - { - td.mkdir(); - } - catch (Exception e) {} - if ( td.isDirectory() ) - fbd = td1; - } + cor = null; - ConfigHelper.writeBaseDir( getContext(), baseDir ); - } - String basedir = fbd.getAbsolutePath(); + String basedir = baseDir.getAbsolutePath(); AppLogger.log( "using basedir: " + basedir ); String version = "v1.6.1"; // create missing directories - assertDirectoryExists( "project directory", basedir + "/brouter", null, null ); - segmentDir = basedir + "/brouter/segments4"; + assertDirectoryExists( "project directory", new File (basedir, "brouter"), null, null ); + segmentDir = new File (basedir, "/brouter/segments4"); if ( assertDirectoryExists( "data directory", segmentDir, "segments4.zip", null ) ) { ConfigMigration.tryMigrateStorageConfig( new File( basedir + "/brouter/segments3/storageconfig.txt" ), new File( basedir + "/brouter/segments4/storageconfig.txt" ) ); } - profileDir = basedir + "/brouter/profiles2"; + profileDir = new File (basedir, "brouter/profiles2"); assertDirectoryExists( "profile directory", profileDir, "profiles2.zip", version ); - modesDir = basedir + "/brouter/modes"; + modesDir = new File (basedir, "/brouter/modes"); assertDirectoryExists( "modes directory", modesDir, "modes.zip", version ); - assertDirectoryExists( "readmes directory", basedir + "/brouter/readmes", "readmes.zip", version ); + assertDirectoryExists( "readmes directory", new File (basedir, "brouter/readmes"), "readmes.zip", version ); int deviceLevel = android.os.Build.VERSION.SDK_INT; int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; @@ -219,17 +223,18 @@ public class BRouterView extends View if ( cor.tracksdir != null ) { - tracksDir = cor.basedir + cor.tracksdir; + tracksDir = new File (cor.basedir, cor.tracksdir); assertDirectoryExists( "track directory", tracksDir, null, null ); // output redirect: look for a pointerfile in tracksdir - File tracksDirPointer = new File( tracksDir + "/brouter.redirect" ); + File tracksDirPointer = new File( tracksDir, "brouter.redirect" ); if ( tracksDirPointer.isFile() ) { - tracksDir = readSingleLineFile( tracksDirPointer ); - if ( tracksDir == null ) + String tracksDirStr = readSingleLineFile( tracksDirPointer ); + if ( tracksDirStr == null ) throw new IllegalArgumentException( "redirect pointer file is empty: " + tracksDirPointer ); - if ( !( new File( tracksDir ).isDirectory() ) ) + tracksDir = new File (tracksDirStr); + if ( !( tracksDir.isDirectory() ) ) throw new IllegalArgumentException( "redirect pointer file " + tracksDirPointer + " does not point to a directory: " + tracksDir ); } else @@ -248,10 +253,10 @@ public class BRouterView extends View } if ( tracksDir == null ) { - tracksDir = basedir + "/brouter"; // fallback + tracksDir = new File (basedir, "router"); // fallback } - String[] fileNames = new File( profileDir ).list(); + String[] fileNames = profileDir.list(); ArrayList profiles = new ArrayList(); boolean lookupsFound = false; @@ -387,7 +392,7 @@ public class BRouterView extends View { if ( wp.name.equals( waypoint ) ) { - if ( wp.ilat != 0 || wp.ilat != 0 ) + if ( wp.ilat != 0 || wp.ilon != 0 ) { int nwp = wpList.size(); if ( nwp == 0 || wpList.get( nwp-1 ) != wp ) @@ -513,10 +518,10 @@ public class BRouterView extends View OsmNode prev = null; for ( OsmNode n : wpList ) { - maxlon = n.ilon > maxlon ? n.ilon : maxlon; - minlon = n.ilon < minlon ? n.ilon : minlon; - maxlat = n.ilat > maxlat ? n.ilat : maxlat; - minlat = n.ilat < minlat ? n.ilat : minlat; + maxlon = Math.max(n.ilon, maxlon); + minlon = Math.min(n.ilon, minlon); + maxlat = Math.max(n.ilat, maxlat); + minlat = Math.min(n.ilat, minlat); if ( prev != null ) { plain_distance += n.calcDistance( prev ); @@ -536,7 +541,7 @@ public class BRouterView extends View scaleLon = imgw / ( difflon * 1.5 ); scaleLat = imgh / ( difflat * 1.5 ); - scaleMeter2Pixel = scaleLon < scaleLat ? scaleLon : scaleLat; + scaleMeter2Pixel = Math.min(scaleLon, scaleLat); scaleLon = scaleMeter2Pixel*dlon2m; scaleLat = scaleMeter2Pixel*dlat2m; @@ -570,18 +575,16 @@ public class BRouterView extends View } } - private boolean assertDirectoryExists( String message, String path, String assetZip, String versionTag ) + private boolean assertDirectoryExists( String message, File path, String assetZip, String versionTag ) { - File f = new File( path ); - - boolean exists = f.exists(); + boolean exists = path.exists(); if ( !exists ) { - f.mkdirs(); + path.mkdirs(); } if ( versionTag != null ) { - File vtag = new File( f, versionTag ); + File vtag = new File( path, versionTag ); try { exists = !vtag.createNewFile(); @@ -606,7 +609,7 @@ public class BRouterView extends View if ( ze == null ) break; String name = ze.getName(); - File outfile = new File( f, name ); + File outfile = new File( path, name ); outfile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream( outfile ); @@ -629,7 +632,7 @@ public class BRouterView extends View } } - if ( !f.exists() || !f.isDirectory() ) + if ( !path.exists() || !path.isDirectory() ) throw new IllegalArgumentException( message + ": " + path + " cannot be created" ); return false; } @@ -1071,76 +1074,29 @@ public class BRouterView extends View private String readSingleLineFile( File f ) { - BufferedReader br = null; - try - { - br = new BufferedReader( new InputStreamReader( new FileInputStream( f ) ) ); + try ( FileInputStream fis = new FileInputStream (f); + InputStreamReader isr = new InputStreamReader (fis); + BufferedReader br = new BufferedReader (isr)) { return br.readLine(); } catch (Exception e) { return null; } - finally - { - if ( br != null ) - try - { - br.close(); - } - catch (Exception ee) - { - } - } } - private List getStorageDirectories() - { - ArrayList res = new ArrayList(); - - // check write access on internal sd - try - { - File sd = Environment.getExternalStorageDirectory(); - File testDir = new File( sd, "brouter" ); - boolean didExist = testDir.isDirectory(); - if ( !didExist ) - { - testDir.mkdir(); - } - File testFile = new File( testDir, "test" + System.currentTimeMillis() ); - testFile.createNewFile(); - if ( testFile.exists() ) - { - testFile.delete(); - res.add( sd.getPath() ); - } - if ( !didExist ) - { - testDir.delete(); - } - } - catch( Throwable t ) - { - // ignore - } - + private ArrayList getStorageDirectories () { + ArrayList list = new ArrayList(Arrays.asList(getContext().getExternalFilesDirs(null))); + ArrayList res = new ArrayList(); - try - { - Method method = Context.class.getDeclaredMethod("getExternalFilesDirs", new Class[]{ String.class } ); - File[] paths = (File[])method.invoke( getContext(), new Object[1] ); - for( File path : paths ) - { - res.add( path.getPath() ); + for (File f : list) { + if (f != null) { + if (EnvironmentCompat.getStorageState(f).equals(Environment.MEDIA_MOUNTED)) + res.add (f); } } - catch( Exception e ) - { - res.add( e.toString() ); - res.add( Environment.getExternalStorageDirectory().getPath() ); - } + +// res.add(getContext().getFilesDir()); return res; } - } diff --git a/brouter-routing-app/src/main/java/btools/routingapp/BRouterWorker.java b/brouter-routing-app/src/main/java/btools/routingapp/BRouterWorker.java index 65e743f..c40ff9c 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/BRouterWorker.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/BRouterWorker.java @@ -1,230 +1,231 @@ -package btools.routingapp; - - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.StringTokenizer; - -import android.os.Bundle; -import btools.router.OsmNodeNamed; -import btools.router.OsmPathElement; -import btools.router.OsmTrack; -import btools.router.RoutingContext; -import btools.router.RoutingEngine; - -public class BRouterWorker -{ - private static final int OUTPUT_FORMAT_GPX = 0; - private static final int OUTPUT_FORMAT_KML = 1; - private static final int OUTPUT_FORMAT_JSON = 2; - - public String baseDir; - public String segmentDir; - public String profileName; - public String profilePath; - public String rawTrackPath; - public List waypoints; - public List nogoList; - - public String getTrackFromParams(Bundle params) - { - String pathToFileResult = params.getString("pathToFileResult"); - - if (pathToFileResult != null) - { - File f = new File (pathToFileResult); - File dir = f.getParentFile(); - if (!dir.exists() || !dir.canWrite()){ - return "file folder does not exists or can not be written!"; - } - } - - long maxRunningTime = 60000; - String sMaxRunningTime = params.getString( "maxRunningTime" ); - if ( sMaxRunningTime != null ) - { - maxRunningTime = Integer.parseInt( sMaxRunningTime ) * 1000; - } - - RoutingContext rc = new RoutingContext(); - rc.rawTrackPath = rawTrackPath; - rc.localFunction = profilePath; - - String tiFormat = params.getString( "turnInstructionFormat" ); - if ( tiFormat != null ) - { - if ( "osmand".equalsIgnoreCase( tiFormat ) ) - { - rc.turnInstructionMode = 3; - } - else if ( "locus".equalsIgnoreCase( tiFormat ) ) - { - rc.turnInstructionMode = 2; - } - } - - if ( params.containsKey( "direction" ) ) - { - rc.startDirection = Integer.valueOf( params.getInt( "direction" ) ); - } - if (params.containsKey( "extraParams" )) { // add user params - String extraParams = params.getString("extraParams"); - if (rc.keyValues == null) rc.keyValues = new HashMap(); - StringTokenizer tk = new StringTokenizer( extraParams, "?&" ); - while( tk.hasMoreTokens() ) { - String t = tk.nextToken(); - StringTokenizer tk2 = new StringTokenizer( t, "=" ); - if ( tk2.hasMoreTokens() ) { - String key = tk2.nextToken(); - if ( tk2.hasMoreTokens() ) { - String value = tk2.nextToken(); - rc.keyValues.put( key, value ); - } - } - } - } - - readNogos( params ); // add interface provided nogos - RoutingContext.prepareNogoPoints( nogoList ); - rc.nogopoints = nogoList; - - waypoints = readPositions(params); - - try - { - writeTimeoutData( rc ); - } - catch( Exception e ) {} - - RoutingEngine cr = new RoutingEngine( null, null, segmentDir, waypoints, rc ); - cr.quite = true; - cr.doRun( maxRunningTime ); - - // store new reference track if any - // (can exist for timed-out search) - if ( cr.getFoundRawTrack() != null ) - { - try - { - cr.getFoundRawTrack().writeBinary( rawTrackPath ); - } - catch( Exception e ) {} - } - - if ( cr.getErrorMessage() != null ) - { - return cr.getErrorMessage(); - } - - String format = params.getString("trackFormat"); - int writeFromat = OUTPUT_FORMAT_GPX; - if (format != null) { - if ("kml".equals(format)) writeFromat = OUTPUT_FORMAT_KML; - if ("json".equals(format)) writeFromat = OUTPUT_FORMAT_JSON; - } - - OsmTrack track = cr.getFoundTrack(); - if ( track != null ) - { - if ( pathToFileResult == null ) - { - switch ( writeFromat ) { - case OUTPUT_FORMAT_GPX: return track.formatAsGpx(); - case OUTPUT_FORMAT_KML: return track.formatAsKml(); - case OUTPUT_FORMAT_JSON: return track.formatAsGeoJson(); - default: return track.formatAsGpx(); - } - - } - try - { - switch ( writeFromat ) { - case OUTPUT_FORMAT_GPX: track.writeGpx(pathToFileResult); break; - case OUTPUT_FORMAT_KML: track.writeKml(pathToFileResult); break; - case OUTPUT_FORMAT_JSON: track.writeJson(pathToFileResult); break; - default: track.writeGpx(pathToFileResult); break; - } - } - catch( Exception e ) - { - return "error writing file: " + e; - } - } - return null; - } - - private List readPositions( Bundle params ) - { - List wplist = new ArrayList(); - - double[] lats = params.getDoubleArray("lats"); - double[] lons = params.getDoubleArray("lons"); - - if (lats == null || lats.length < 2 || lons == null || lons.length < 2) - { - throw new IllegalArgumentException( "we need two lat/lon points at least!" ); - } - - for( int i=0; i wps ) throws Exception - { - bw.write( wps.size() + "\n" ); - for( OsmNodeNamed wp : wps ) - { - bw.write( wp.toString() ); - bw.write( "\n" ); - } - } -} +package btools.routingapp; + + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.StringTokenizer; + +import android.os.Bundle; +import btools.router.OsmNodeNamed; +import btools.router.OsmPathElement; +import btools.router.OsmTrack; +import btools.router.RoutingContext; +import btools.router.RoutingEngine; + +public class BRouterWorker +{ + private static final int OUTPUT_FORMAT_GPX = 0; + private static final int OUTPUT_FORMAT_KML = 1; + private static final int OUTPUT_FORMAT_JSON = 2; + + public String baseDir; + public File segmentDir; + public String profileName; + public String profilePath; + public String rawTrackPath; + public List waypoints; + public List nogoList; + + public String getTrackFromParams(Bundle params) + { + String pathToFileResult = params.getString("pathToFileResult"); + + if (pathToFileResult != null) + { + File f = new File (pathToFileResult); + File dir = f.getParentFile(); + if (!dir.exists() || !dir.canWrite()){ + return "file folder does not exists or can not be written!"; + } + } + + long maxRunningTime = 60000; + String sMaxRunningTime = params.getString( "maxRunningTime" ); + if ( sMaxRunningTime != null ) + { + maxRunningTime = Integer.parseInt( sMaxRunningTime ) * 1000; + } + + RoutingContext rc = new RoutingContext(); + rc.rawTrackPath = rawTrackPath; + rc.localFunction = profilePath; + + String tiFormat = params.getString( "turnInstructionFormat" ); + if ( tiFormat != null ) + { + if ( "osmand".equalsIgnoreCase( tiFormat ) ) + { + rc.turnInstructionMode = 3; + } + else if ( "locus".equalsIgnoreCase( tiFormat ) ) + { + rc.turnInstructionMode = 2; + } + } + + if ( params.containsKey( "direction" ) ) + { + rc.startDirection = Integer.valueOf( params.getInt( "direction" ) ); + } + if (params.containsKey( "extraParams" )) { // add user params + String extraParams = params.getString("extraParams"); + if (rc.keyValues == null) rc.keyValues = new HashMap(); + StringTokenizer tk = new StringTokenizer( extraParams, "?&" ); + while( tk.hasMoreTokens() ) { + String t = tk.nextToken(); + StringTokenizer tk2 = new StringTokenizer( t, "=" ); + if ( tk2.hasMoreTokens() ) { + String key = tk2.nextToken(); + if ( tk2.hasMoreTokens() ) { + String value = tk2.nextToken(); + rc.keyValues.put( key, value ); + } + } + } + } + + readNogos( params ); // add interface provided nogos + RoutingContext.prepareNogoPoints( nogoList ); + rc.nogopoints = nogoList; + + waypoints = readPositions(params); + + try + { + writeTimeoutData( rc ); + } + catch( Exception e ) {} + + RoutingEngine cr = new RoutingEngine( null, null, segmentDir, waypoints, rc ); + cr.quite = true; + cr.doRun( maxRunningTime ); + + // store new reference track if any + // (can exist for timed-out search) + if ( cr.getFoundRawTrack() != null ) + { + try + { + cr.getFoundRawTrack().writeBinary( rawTrackPath ); + } + catch( Exception e ) {} + } + + if ( cr.getErrorMessage() != null ) + { + return cr.getErrorMessage(); + } + + String format = params.getString("trackFormat"); + int writeFromat = OUTPUT_FORMAT_GPX; + if (format != null) { + if ("kml".equals(format)) writeFromat = OUTPUT_FORMAT_KML; + if ("json".equals(format)) writeFromat = OUTPUT_FORMAT_JSON; + } + + OsmTrack track = cr.getFoundTrack(); + if ( track != null ) + { + if ( pathToFileResult == null ) + { + switch ( writeFromat ) { + case OUTPUT_FORMAT_GPX: return track.formatAsGpx(); + case OUTPUT_FORMAT_KML: return track.formatAsKml(); + case OUTPUT_FORMAT_JSON: return track.formatAsGeoJson(); + default: return track.formatAsGpx(); + } + + } + try + { + switch ( writeFromat ) { + case OUTPUT_FORMAT_GPX: track.writeGpx(pathToFileResult); break; + case OUTPUT_FORMAT_KML: track.writeKml(pathToFileResult); break; + case OUTPUT_FORMAT_JSON: track.writeJson(pathToFileResult); break; + default: track.writeGpx(pathToFileResult); break; + } + } + catch( Exception e ) + { + return "error writing file: " + e; + } + } + return null; + } + + private List readPositions( Bundle params ) + { + List wplist = new ArrayList(); + + double[] lats = params.getDoubleArray("lats"); + double[] lons = params.getDoubleArray("lons"); + + if (lats == null || lats.length < 2 || lons == null || lons.length < 2) + { + throw new IllegalArgumentException( "we need two lat/lon points at least!" ); + } + + for( int i=0; i wps ) throws Exception + { + bw.write( wps.size() + "\n" ); + for( OsmNodeNamed wp : wps ) + { + bw.write( wp.toString() ); + bw.write( "\n" ); + } + } +} + diff --git a/brouter-routing-app/src/main/java/btools/routingapp/ConfigHelper.java b/brouter-routing-app/src/main/java/btools/routingapp/ConfigHelper.java index 3b5da85..9575871 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/ConfigHelper.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/ConfigHelper.java @@ -6,59 +6,35 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; +import java.io.File; import android.content.Context; public class ConfigHelper { - public static String getBaseDir( Context ctx ) + public static File getBaseDir( Context ctx ) { // get base dir from private file - InputStream configInput = null; - try - { - configInput = ctx.openFileInput( "config15.dat" ); - BufferedReader br = new BufferedReader( new InputStreamReader( configInput ) ); - return br.readLine(); + + try (InputStream configInput = ctx.openFileInput( "config15.dat" ); + InputStreamReader isr = new InputStreamReader( configInput ); + BufferedReader br = new BufferedReader(isr)) { + return new File ( br.readLine() ); } catch (Exception e) { return null; } - finally - { - if ( configInput != null ) - { - try - { - configInput.close(); - } - catch (Exception ee) - { - } - } - } } - public static void writeBaseDir( Context ctx, String baseDir ) + public static void writeBaseDir( Context ctx, File baseDir ) { - BufferedWriter bw = null; - try - { - OutputStream configOutput = ctx.openFileOutput( "config15.dat", Context.MODE_PRIVATE ); - bw = new BufferedWriter( new OutputStreamWriter( configOutput ) ); - bw.write( baseDir ); + try (OutputStream configOutput = ctx.openFileOutput( "config15.dat", Context.MODE_PRIVATE ); + OutputStreamWriter osw = new OutputStreamWriter( configOutput ); + BufferedWriter bw = new BufferedWriter( osw)) { + bw.write( baseDir.getAbsolutePath () ); bw.write( '\n' ); } catch (Exception e){ /* ignore */ } - finally - { - if ( bw != null ) - try - { - bw.close(); - } - catch (Exception ee) { /* ignore */ } - } } } diff --git a/brouter-routing-app/src/main/java/btools/routingapp/ConfigMigration.java b/brouter-routing-app/src/main/java/btools/routingapp/ConfigMigration.java index 88645e1..593b338 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/ConfigMigration.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/ConfigMigration.java @@ -87,17 +87,17 @@ public class ConfigMigration } } - public static File saveAdditionalMaptoolDir( String segmentDir, String value ) + public static File saveAdditionalMaptoolDir( File segmentDir, String value ) { return saveStorageLocation( segmentDir, "additional_maptool_dir=", value ); } - private static File saveStorageLocation( String segmentDir, String tag, String value ) + private static File saveStorageLocation( File segmentDir, String tag, String value ) { File res = null; BufferedReader br = null; BufferedWriter bw = null; - String configFile = segmentDir + "/storageconfig.txt"; + File configFile = new File (segmentDir, "storageconfig.txt"); List lines = new ArrayList(); try { diff --git a/brouter-routing-app/src/main/java/btools/routingapp/CoordinateReader.java b/brouter-routing-app/src/main/java/btools/routingapp/CoordinateReader.java index ccfca86..4926b70 100644 --- a/brouter-routing-app/src/main/java/btools/routingapp/CoordinateReader.java +++ b/brouter-routing-app/src/main/java/btools/routingapp/CoordinateReader.java @@ -149,12 +149,12 @@ public abstract class CoordinateReader protected abstract void readPointmap() throws Exception; - public static CoordinateReader obtainValidReader( String basedir, String segmentDir ) throws Exception + public static CoordinateReader obtainValidReader( String basedir, File segmentDir ) throws Exception { return obtainValidReader( basedir, segmentDir, false ); } - public static CoordinateReader obtainValidReader( String basedir, String segmentDir, boolean nogosOnly ) throws Exception + public static CoordinateReader obtainValidReader( String basedir, File segmentDir, boolean nogosOnly ) throws Exception { CoordinateReader cor = null; ArrayList rl = new ArrayList(); diff --git a/brouter-server/src/main/java/btools/server/BRouter.java b/brouter-server/src/main/java/btools/server/BRouter.java index c2b544b..ea340b8 100644 --- a/brouter-server/src/main/java/btools/server/BRouter.java +++ b/brouter-server/src/main/java/btools/server/BRouter.java @@ -6,6 +6,7 @@ import java.io.FileOutputStream; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; +import java.io.File; import btools.router.OsmNodeNamed; import btools.router.RoutingContext; @@ -75,7 +76,7 @@ public class BRouter wplist.add( from ); wplist.add( to ); - RoutingEngine re = new RoutingEngine( null, null, args[0], wplist, readRoutingContext(a2) ); + RoutingEngine re = new RoutingEngine( null, null, new File (args[0]), wplist, readRoutingContext(a2) ); re.doRun( maxRunningTime ); if ( re.getErrorMessage() != null ) { @@ -111,7 +112,7 @@ public class BRouter SearchBoundary boundary = new SearchBoundary( wplist.get(0), searchRadius, direction/2 ); rc.trafficOutputStream = dos; rc.inverseDirection = (direction & 1 ) != 0; - re = new RoutingEngine( "mytrack", "mylog", args[0], wplist, rc ); + re = new RoutingEngine( "mytrack", "mylog", new File ( args[0] ), wplist, rc ); re.boundary = boundary; re.airDistanceCostFactor = rc.trafficDirectionFactor; rc.countTraffic = true; @@ -127,7 +128,7 @@ public class BRouter { wplist.add( readPosition( args, 3, "to" ) ); RoutingContext rc = readRoutingContext(args); - re = new RoutingEngine( "mytrack", "mylog", args[0], wplist, rc ); + re = new RoutingEngine( "mytrack", "mylog", new File ( args[0] ), wplist, rc ); re.doRun( 0 ); } diff --git a/brouter-server/src/main/java/btools/server/RouteServer.java b/brouter-server/src/main/java/btools/server/RouteServer.java index 7125dc8..93eb041 100644 --- a/brouter-server/src/main/java/btools/server/RouteServer.java +++ b/brouter-server/src/main/java/btools/server/RouteServer.java @@ -336,7 +336,7 @@ public class RouteServer extends Thread implements Comparable } ServiceContext serviceContext = new ServiceContext(); - serviceContext.segmentDir = args[0]; + serviceContext.segmentDir = new File ( args[0] ); serviceContext.profileDir = args[1]; System.setProperty( "profileBaseDir", serviceContext.profileDir ); String dirs = args[2]; diff --git a/brouter-server/src/main/java/btools/server/ServiceContext.java b/brouter-server/src/main/java/btools/server/ServiceContext.java index 28d6fc0..1d1b950 100644 --- a/brouter-server/src/main/java/btools/server/ServiceContext.java +++ b/brouter-server/src/main/java/btools/server/ServiceContext.java @@ -2,6 +2,7 @@ package btools.server; import java.util.List; import java.util.Map; +import java.io.File; import btools.router.OsmNodeNamed; @@ -10,7 +11,7 @@ import btools.router.OsmNodeNamed; */ public class ServiceContext { - public String segmentDir; + public File segmentDir; public String profileDir; public String customProfileDir; public String sharedProfileDir; diff --git a/brouter-server/src/test/java/btools/server/RouterTest.java b/brouter-server/src/test/java/btools/server/RouterTest.java index e272770..334e8bf 100644 --- a/brouter-server/src/test/java/btools/server/RouterTest.java +++ b/brouter-server/src/test/java/btools/server/RouterTest.java @@ -67,7 +67,10 @@ public class RouterTest RoutingEngine re = new RoutingEngine( wd + "/" + trackname, wd + "/" + trackname, - wd + "/../../../../brouter-map-creator/build/resources/test/tmp/segments", wplist, rctx ); + new File ( wd, "/../../../../brouter-map-creator/build/resources/test/tmp/segments"), + wplist, + rctx ); + re.doRun( 0 ); return re.getErrorMessage();