From 82f77f0c076d86a4674a81af4090048d15f1ffb8 Mon Sep 17 00:00:00 2001 From: mendhak Date: Sun, 20 Apr 2014 11:01:28 +0100 Subject: [PATCH] Refactoring - applied IDEA code style settings --- .../java/com/mendhak/gpslogger/Faqtivity.java | 13 +- .../gpslogger/GeneralLocationListener.java | 68 +- .../mendhak/gpslogger/GpsLoggingService.java | 30 +- .../mendhak/gpslogger/GpsMainActivity.java | 33 +- .../gpslogger/IGpsLoggerServiceClient.java | 4 +- .../mendhak/gpslogger/StartupReceiver.java | 16 +- .../mendhak/gpslogger/common/AppSettings.java | 281 +++---- .../common/FileDialog/FileDialog.java | 722 +++++++++--------- .../common/FileDialog/SelectionMode.java | 4 +- .../common/GpsRollingFileAppender.java | 5 +- .../gpslogger/common/IActionListener.java | 3 +- .../gpslogger/common/IMessageBoxCallback.java | 3 +- .../gpslogger/common/OpenGTSClient.java | 85 +-- .../gpslogger/common/RejectionHandler.java | 6 +- .../com/mendhak/gpslogger/common/Session.java | 172 ++--- .../mendhak/gpslogger/common/Utilities.java | 424 ++++------ .../gpslogger/loggers/FileLoggerFactory.java | 26 +- .../gpslogger/loggers/Gpx10FileLogger.java | 123 ++- .../gpslogger/loggers/IFileLogger.java | 3 +- .../gpslogger/loggers/Kml22FileLogger.java | 75 +- .../gpslogger/loggers/OpenGTSLogger.java | 25 +- .../loggers/PlainTextFileLogger.java | 25 +- .../customurl/CustomUrlLoggerActivity.java | 28 +- .../loggers/customurl/HttpUrlLogger.java | 6 +- .../loggers/nmea/NmeaFileLogger.java | 11 +- .../gpslogger/senders/AlarmReceiver.java | 15 +- .../gpslogger/senders/FileSenderFactory.java | 66 +- .../gpslogger/senders/IFileSender.java | 3 +- .../mendhak/gpslogger/senders/ZipHelper.java | 22 +- .../dropbox/DropBoxAuthorizationActivity.java | 46 +- .../senders/dropbox/DropBoxHelper.java | 94 +-- .../senders/email/AutoEmailActivity.java | 72 +- .../senders/email/AutoEmailHelper.java | 83 +- .../mendhak/gpslogger/senders/email/Mail.java | 79 +- .../senders/ftp/AutoFtpActivity.java | 77 +- .../mendhak/gpslogger/senders/ftp/Ftp.java | 63 +- .../gpslogger/senders/ftp/FtpHelper.java | 66 +- .../gpslogger/senders/gdocs/GDocsHelper.java | 187 ++--- .../senders/gdocs/GDocsSettingsActivity.java | 156 ++-- .../gpslogger/senders/opengts/GpxReader.java | 42 +- .../senders/opengts/OpenGTSActivity.java | 45 +- .../senders/opengts/OpenGTSHelper.java | 57 +- .../senders/osm/OSMAuthorizationActivity.java | 50 +- .../gpslogger/senders/osm/OSMHelper.java | 68 +- .../settings/LoggingSettingsActivity.java | 10 +- .../settings/UploadSettingsActivity.java | 4 +- .../gpslogger/shortcuts/ShortcutCreate.java | 19 +- .../gpslogger/shortcuts/ShortcutStart.java | 6 +- .../gpslogger/shortcuts/ShortcutStop.java | 6 +- .../gpslogger/views/GenericViewFragment.java | 11 +- .../gpslogger/views/GpsBigViewFragment.java | 26 +- .../views/GpsDetailedViewFragment.java | 188 ++--- .../views/GpsSimpleViewFragment.java | 28 +- .../views/component/ToggleComponent.java | 10 +- 54 files changed, 1427 insertions(+), 2363 deletions(-) diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/Faqtivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/Faqtivity.java index 8ea429b8a..d9cba05d6 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/Faqtivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/Faqtivity.java @@ -26,20 +26,16 @@ import android.webkit.WebView; import org.slf4j.LoggerFactory; -import java.util.HashMap; -import java.util.Map; - -public class Faqtivity extends Activity -{ +public class Faqtivity extends Activity { WebView browser; private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Faqtivity.class.getSimpleName()); + /** * Event raised when the form is created for the first time */ @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { tracer.debug("Faqtivity.onCreate"); @@ -49,7 +45,7 @@ public void onCreate(Bundle savedInstanceState) setContentView(R.layout.activity_faq); - browser = (WebView)findViewById(R.id.faqwebview); + browser = (WebView) findViewById(R.id.faqwebview); WebSettings settings = browser.getSettings(); settings.setLoadWithOverviewMode(true); settings.setUseWideViewPort(true); @@ -76,7 +72,6 @@ public boolean onOptionsItemSelected(MenuItem item) { } - @Override protected void onStop() { super.onStop(); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/GeneralLocationListener.java b/gpslogger/src/main/java/com/mendhak/gpslogger/GeneralLocationListener.java index a8bf2c20e..12903f739 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/GeneralLocationListener.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/GeneralLocationListener.java @@ -28,8 +28,7 @@ import java.util.Iterator; -class GeneralLocationListener implements LocationListener, GpsStatus.Listener, GpsStatus.NmeaListener -{ +class GeneralLocationListener implements LocationListener, GpsStatus.Listener, GpsStatus.NmeaListener { private static GpsLoggingService loggingService; private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(GeneralLocationListener.class.getSimpleName()); @@ -40,8 +39,7 @@ class GeneralLocationListener implements LocationListener, GpsStatus.Listener, G private String ageOfDgpsData; private String dgpsId; - GeneralLocationListener(GpsLoggingService activity) - { + GeneralLocationListener(GpsLoggingService activity) { tracer.debug("GeneralLocationListener constructor"); loggingService = activity; } @@ -49,13 +47,10 @@ class GeneralLocationListener implements LocationListener, GpsStatus.Listener, G /** * Event raised when a new fix is received. */ - public void onLocationChanged(Location loc) - { + public void onLocationChanged(Location loc) { - try - { - if (loc != null) - { + try { + if (loc != null) { tracer.debug("GeneralLocationListener.onLocationChanged"); Bundle b = new Bundle(); b.putString("HDOP", this.latestHdop); @@ -68,57 +63,47 @@ public void onLocationChanged(Location loc) loggingService.OnLocationChanged(loc); this.latestHdop = ""; - this.latestPdop=""; - this.latestVdop=""; + this.latestPdop = ""; + this.latestVdop = ""; } - } - catch (Exception ex) - { + } catch (Exception ex) { tracer.error("GeneralLocationListener.onLocationChanged", ex); loggingService.SetStatus(ex.getMessage()); } } - public void onProviderDisabled(String provider) - { + public void onProviderDisabled(String provider) { tracer.info("Provider disabled: " + provider); loggingService.RestartGpsManagers(); } - public void onProviderEnabled(String provider) - { + public void onProviderEnabled(String provider) { tracer.info("Provider enabled: " + provider); loggingService.RestartGpsManagers(); } - public void onStatusChanged(String provider, int status, Bundle extras) - { - if (status == LocationProvider.OUT_OF_SERVICE) - { + public void onStatusChanged(String provider, int status, Bundle extras) { + if (status == LocationProvider.OUT_OF_SERVICE) { tracer.debug(provider + " is out of service"); loggingService.StopManagerAndResetAlarm(); } - if (status == LocationProvider.AVAILABLE) - { + if (status == LocationProvider.AVAILABLE) { tracer.debug(provider + " is available"); } - if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) - { + if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) { tracer.debug(provider + " is temporarily unavailable"); loggingService.StopManagerAndResetAlarm(); } } - public void onGpsStatusChanged(int event) - { + public void onGpsStatusChanged(int event) { - switch (event) - { + switch (event) { case GpsStatus.GPS_EVENT_FIRST_FIX: tracer.debug("GPS Event First Fix"); loggingService.SetStatus(loggingService.getString(R.string.fix_obtained)); @@ -133,8 +118,7 @@ public void onGpsStatusChanged(int event) Iterator it = status.getSatellites().iterator(); int count = 0; - while (it.hasNext() && count <= maxSatellites) - { + while (it.hasNext() && count <= maxSatellites) { it.next(); count++; } @@ -162,37 +146,37 @@ public void onNmeaReceived(long timestamp, String nmeaSentence) { String[] nmeaParts = nmeaSentence.split(","); - if(nmeaParts[0].equalsIgnoreCase("$GPGSA")){ + if (nmeaParts[0].equalsIgnoreCase("$GPGSA")) { - if(!Utilities.IsNullOrEmpty(nmeaParts[15])){ + if (!Utilities.IsNullOrEmpty(nmeaParts[15])) { this.latestPdop = nmeaParts[15]; } - if(!Utilities.IsNullOrEmpty(nmeaParts[16])){ + if (!Utilities.IsNullOrEmpty(nmeaParts[16])) { this.latestHdop = nmeaParts[16]; } - if(!Utilities.IsNullOrEmpty(nmeaParts[17]) && !nmeaParts[17].startsWith("*")){ + if (!Utilities.IsNullOrEmpty(nmeaParts[17]) && !nmeaParts[17].startsWith("*")) { this.latestVdop = nmeaParts[17].split("\\*")[0]; } } - if(nmeaParts[0].equalsIgnoreCase("$GPGGA")){ - if(!Utilities.IsNullOrEmpty(nmeaParts[8])){ + if (nmeaParts[0].equalsIgnoreCase("$GPGGA")) { + if (!Utilities.IsNullOrEmpty(nmeaParts[8])) { this.latestHdop = nmeaParts[8]; } - if(!Utilities.IsNullOrEmpty(nmeaParts[11])){ + if (!Utilities.IsNullOrEmpty(nmeaParts[11])) { this.geoIdHeight = nmeaParts[11]; } - if(!Utilities.IsNullOrEmpty(nmeaParts[13])){ + if (!Utilities.IsNullOrEmpty(nmeaParts[13])) { this.ageOfDgpsData = nmeaParts[13]; } - if(!Utilities.IsNullOrEmpty(nmeaParts[14]) && !nmeaParts[14].startsWith("*")){ + if (!Utilities.IsNullOrEmpty(nmeaParts[14]) && !nmeaParts[14].startsWith("*")) { this.dgpsId = nmeaParts[14].split("\\*")[0]; } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/GpsLoggingService.java b/gpslogger/src/main/java/com/mendhak/gpslogger/GpsLoggingService.java index f8897c28e..de3d4ba32 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/GpsLoggingService.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/GpsLoggingService.java @@ -29,7 +29,11 @@ import android.content.Intent; import android.location.Location; import android.location.LocationManager; -import android.os.*; +import android.os.Binder; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import com.mendhak.gpslogger.common.AppSettings; @@ -42,6 +46,7 @@ import com.mendhak.gpslogger.senders.AlarmReceiver; import com.mendhak.gpslogger.senders.FileSenderFactory; import org.slf4j.LoggerFactory; + import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; @@ -207,14 +212,11 @@ public void SetupAutoSendTimers() { } - protected void ForceAutoSendNow() - { + protected void ForceAutoSendNow() { tracer.debug("."); - if (AppSettings.isAutoSendEnabled() && Session.getCurrentFileName() != null && Session.getCurrentFileName().length() > 0) - { - if (IsMainFormVisible()) - { + if (AppSettings.isAutoSendEnabled() && Session.getCurrentFileName() != null && Session.getCurrentFileName().length() > 0) { + if (IsMainFormVisible()) { SetStatus(R.string.autosend_sending); } @@ -481,9 +483,9 @@ private void StartGpsManager() { } private void startAbsoluteTimer() { - if(AppSettings.getAbsoluteTimeout() >= 1){ + if (AppSettings.getAbsoluteTimeout() >= 1) { tracer.debug("Starting absolute timer"); - handler.postDelayed(stopManagerRunnable, AppSettings.getAbsoluteTimeout()*1000); + handler.postDelayed(stopManagerRunnable, AppSettings.getAbsoluteTimeout() * 1000); } } @@ -495,7 +497,7 @@ public void run() { } }; - private void stopAbsoluteTimer(){ + private void stopAbsoluteTimer() { tracer.debug("Stopping absolute timer"); handler.removeCallbacks(stopManagerRunnable); } @@ -648,18 +650,18 @@ void OnLocationChanged(Location loc) { if (AppSettings.getMinimumAccuracyInMeters() > 0) { if (AppSettings.getMinimumAccuracyInMeters() < Math.abs(loc.getAccuracy())) { - if(this.firstRetryTimeStamp == 0){ + if (this.firstRetryTimeStamp == 0) { this.firstRetryTimeStamp = System.currentTimeMillis(); } - if(currentTimeStamp - this.firstRetryTimeStamp <= AppSettings.getRetryInterval()*1000){ + if (currentTimeStamp - this.firstRetryTimeStamp <= AppSettings.getRetryInterval() * 1000) { tracer.warn("Only accuracy of " + String.valueOf(Math.floor(loc.getAccuracy())) + " m. Point discarded."); SetStatus("Inaccurate point discarded."); //return and keep trying return; } - if (currentTimeStamp - this.firstRetryTimeStamp > AppSettings.getRetryInterval()*1000) { + if (currentTimeStamp - this.firstRetryTimeStamp > AppSettings.getRetryInterval() * 1000) { tracer.warn("Only accuracy of " + String.valueOf(Math.floor(loc.getAccuracy())) + " m and timeout reached"); SetStatus("Inaccurate points discarded and retries timed out."); //Give up for now @@ -812,7 +814,7 @@ private boolean IsMainFormVisible() { public void OnNmeaSentence(long timestamp, String nmeaSentence) { - if(AppSettings.shouldLogToNmea()) { + if (AppSettings.shouldLogToNmea()) { NmeaFileLogger nmeaLogger = new NmeaFileLogger(Session.getCurrentFileName()); nmeaLogger.Write(timestamp, nmeaSentence); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/GpsMainActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/GpsMainActivity.java index 1ba4cc1ca..cabec4610 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/GpsMainActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/GpsMainActivity.java @@ -105,8 +105,6 @@ protected void onCreate(Bundle savedInstanceState) { } - - @Override protected void onStart() { super.onStart(); @@ -164,7 +162,6 @@ private void SetUpNavigationDrawer() { } - /** * Handles drawer item selection */ @@ -306,10 +303,10 @@ private void enableDisableMenuItems() { if (mnuOnePoint != null) { mnuOnePoint.setEnabled(!Session.isStarted()); - mnuOnePoint.setIcon( (Session.isStarted() ? R.drawable.singlepoint_disabled : R.drawable.singlepoint ) ); + mnuOnePoint.setIcon((Session.isStarted() ? R.drawable.singlepoint_disabled : R.drawable.singlepoint)); } - if(mnuAutoSendNow != null){ + if (mnuAutoSendNow != null) { mnuAutoSendNow.setEnabled(Session.isStarted()); } @@ -378,21 +375,17 @@ public boolean onOptionsItemSelected(MenuItem item) { } - private void ForceAutoSendNow() - { + private void ForceAutoSendNow() { tracer.debug("Auto send now"); - if (AppSettings.isAutoSendEnabled()) - { + if (AppSettings.isAutoSendEnabled()) { - Utilities.ShowProgress(this, getString(R.string.autosend_sending), - getString(R.string.please_wait)); - loggingService.ForceAutoSendNow(); + Utilities.ShowProgress(this, getString(R.string.autosend_sending), + getString(R.string.please_wait)); + loggingService.ForceAutoSendNow(); - } - else - { + } else { Intent pref = new Intent().setClass(this, UploadSettingsActivity.class); startActivity(pref); } @@ -551,7 +544,7 @@ private void ShowFileListDialog(final Intent settingsIntent, final IFileSender s Arrays.sort(enumeratedFiles, new Comparator() { public int compare(File f1, File f2) { - if(f1 != null && f2 != null){ + if (f1 != null && f2 != null) { return -1 * Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } return -1; @@ -732,10 +725,10 @@ private void StopAndUnbindServiceIfRequired() { tracer.debug("."); if (Session.isBoundToService()) { - try{ + try { unbindService(gpsServiceConnection); Session.setBoundToService(false); - }catch (Exception e){ + } catch (Exception e) { tracer.error("Could not unbind service", e); } } @@ -743,9 +736,9 @@ private void StopAndUnbindServiceIfRequired() { if (!Session.isStarted()) { tracer.debug("Stopping the service"); //serviceIntent = new Intent(this, GpsLoggingService.class); - try{ + try { stopService(serviceIntent); - } catch(Exception e){ + } catch (Exception e) { tracer.error("Could not stop the service", e); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/IGpsLoggerServiceClient.java b/gpslogger/src/main/java/com/mendhak/gpslogger/IGpsLoggerServiceClient.java index bbd11e1de..80c0af73a 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/IGpsLoggerServiceClient.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/IGpsLoggerServiceClient.java @@ -19,8 +19,7 @@ import android.location.Location; -interface IGpsLoggerServiceClient -{ +interface IGpsLoggerServiceClient { /** @@ -47,6 +46,7 @@ interface IGpsLoggerServiceClient /** * A new NMEA sentence was received + * * @param timestamp * @param nmeaSentence */ diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/StartupReceiver.java b/gpslogger/src/main/java/com/mendhak/gpslogger/StartupReceiver.java index bcc546314..84cf1dc18 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/StartupReceiver.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/StartupReceiver.java @@ -26,32 +26,26 @@ import org.slf4j.LoggerFactory; -public class StartupReceiver extends BroadcastReceiver -{ +public class StartupReceiver extends BroadcastReceiver { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(StartupReceiver.class.getSimpleName()); @Override - public void onReceive(Context context, Intent intent) - { - try - { + public void onReceive(Context context, Intent intent) { + try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean startImmediately = prefs.getBoolean("startonbootup", false); tracer.info("Did the user ask for start on bootup? - " + String.valueOf(startImmediately)); - if (startImmediately) - { + if (startImmediately) { tracer.info("Launching GPSLoggingService"); Intent serviceIntent = new Intent(context, GpsLoggingService.class); serviceIntent.putExtra("immediate", true); context.startService(serviceIntent); } - } - catch (Exception ex) - { + } catch (Exception ex) { tracer.error("StartupReceiver", ex); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/AppSettings.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/AppSettings.java index 66d21076d..48abbd398 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/AppSettings.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/AppSettings.java @@ -19,8 +19,7 @@ import android.app.Application; -public class AppSettings extends Application -{ +public class AppSettings extends Application { // --------------------------------------------------- // User Preferences // --------------------------------------------------- @@ -84,48 +83,42 @@ public class AppSettings extends Application /** * @return the useImperial */ - public static boolean shouldUseImperial() - { + public static boolean shouldUseImperial() { return useImperial; } /** * @param useImperial the useImperial to set */ - static void setUseImperial(boolean useImperial) - { + static void setUseImperial(boolean useImperial) { AppSettings.useImperial = useImperial; } /** * @return the newFileOnceADay */ - public static boolean shouldCreateNewFileOnceADay() - { + public static boolean shouldCreateNewFileOnceADay() { return newFileOnceADay; } /** * @param newFileOnceADay the newFileOnceADay to set */ - static void setNewFileOnceADay(boolean newFileOnceADay) - { + static void setNewFileOnceADay(boolean newFileOnceADay) { AppSettings.newFileOnceADay = newFileOnceADay; } /** * @return the preferCellTower */ - public static boolean shouldPreferCellTower() - { + public static boolean shouldPreferCellTower() { return preferCellTower; } /** * @param preferCellTower the preferCellTower to set */ - static void setPreferCellTower(boolean preferCellTower) - { + static void setPreferCellTower(boolean preferCellTower) { AppSettings.preferCellTower = preferCellTower; } @@ -133,42 +126,36 @@ static void setPreferCellTower(boolean preferCellTower) /** * @return the logToKml */ - public static boolean shouldLogToKml() - { + public static boolean shouldLogToKml() { return logToKml; } /** * @param logToKml the logToKml to set */ - static void setLogToKml(boolean logToKml) - { + static void setLogToKml(boolean logToKml) { AppSettings.logToKml = logToKml; } /** * @return the logToGpx */ - public static boolean shouldLogToGpx() - { + public static boolean shouldLogToGpx() { return logToGpx; } /** * @param logToGpx the logToGpx to set */ - static void setLogToGpx(boolean logToGpx) - { + static void setLogToGpx(boolean logToGpx) { AppSettings.logToGpx = logToGpx; } - public static boolean shouldLogToPlainText() - { + public static boolean shouldLogToPlainText() { return logToPlainText; } - static void setLogToPlainText(boolean logToPlainText) - { + static void setLogToPlainText(boolean logToPlainText) { AppSettings.logToPlainText = logToPlainText; } @@ -176,16 +163,14 @@ static void setLogToPlainText(boolean logToPlainText) /** * @return the minimumSeconds */ - public static int getMinimumSeconds() - { + public static int getMinimumSeconds() { return minimumSeconds; } /** * @param minimumSeconds the minimumSeconds to set */ - static void setMinimumSeconds(int minimumSeconds) - { + static void setMinimumSeconds(int minimumSeconds) { AppSettings.minimumSeconds = minimumSeconds; } @@ -193,32 +178,28 @@ static void setMinimumSeconds(int minimumSeconds) /** * @return the keepFix */ - public static boolean shouldkeepFix() - { + public static boolean shouldkeepFix() { return keepFix; } /** * @param keepFix the keepFix to set */ - static void setKeepFix(boolean keepFix) - { + static void setKeepFix(boolean keepFix) { AppSettings.keepFix = keepFix; } - - /** + + /** * @return the retryInterval */ - public static int getRetryInterval() - { + public static int getRetryInterval() { return retryInterval; } /** * @param retryInterval the retryInterval to set */ - static void setRetryInterval(int retryInterval) - { + static void setRetryInterval(int retryInterval) { AppSettings.retryInterval = retryInterval; } @@ -226,32 +207,28 @@ static void setRetryInterval(int retryInterval) /** * @return the minimumDistance */ - public static int getMinimumDistanceInMeters() - { + public static int getMinimumDistanceInMeters() { return minimumDistance; } /** * @param minimumDistance the minimumDistance to set */ - static void setMinimumDistanceInMeters(int minimumDistance) - { + static void setMinimumDistanceInMeters(int minimumDistance) { AppSettings.minimumDistance = minimumDistance; } - /** + /** * @return the minimumAccuracy */ - public static int getMinimumAccuracyInMeters() - { + public static int getMinimumAccuracyInMeters() { return minimumAccuracy; } /** * @param minimumAccuracy the minimumAccuracy to set */ - static void setMinimumAccuracyInMeters(int minimumAccuracy) - { + static void setMinimumAccuracyInMeters(int minimumAccuracy) { AppSettings.minimumAccuracy = minimumAccuracy; } @@ -259,16 +236,14 @@ static void setMinimumAccuracyInMeters(int minimumAccuracy) /** * @return the newFileCreation */ - static String getNewFileCreation() - { + static String getNewFileCreation() { return newFileCreation; } /** * @param newFileCreation the newFileCreation to set */ - static void setNewFileCreation(String newFileCreation) - { + static void setNewFileCreation(String newFileCreation) { AppSettings.newFileCreation = newFileCreation; } @@ -276,14 +251,10 @@ static void setNewFileCreation(String newFileCreation) /** * @return the autoSendDelay */ - public static Float getAutoSendDelay() - { - if (autoSendDelay >= 8f) - { + public static Float getAutoSendDelay() { + if (autoSendDelay >= 8f) { return 8f; - } - else - { + } else { return autoSendDelay; } @@ -293,15 +264,11 @@ public static Float getAutoSendDelay() /** * @param autoSendDelay the autoSendDelay to set */ - static void setAutoSendDelay(Float autoSendDelay) - { + static void setAutoSendDelay(Float autoSendDelay) { - if (autoSendDelay >= 8f) - { + if (autoSendDelay >= 8f) { AppSettings.autoSendDelay = 8f; - } - else - { + } else { AppSettings.autoSendDelay = autoSendDelay; } @@ -311,109 +278,89 @@ static void setAutoSendDelay(Float autoSendDelay) /** * @return the autoEmailEnabled */ - public static boolean isAutoEmailEnabled() - { + public static boolean isAutoEmailEnabled() { return autoEmailEnabled; } /** * @param autoEmailEnabled the autoEmailEnabled to set */ - static void setAutoEmailEnabled(boolean autoEmailEnabled) - { + static void setAutoEmailEnabled(boolean autoEmailEnabled) { AppSettings.autoEmailEnabled = autoEmailEnabled; } - static void setSmtpServer(String smtpServer) - { + static void setSmtpServer(String smtpServer) { AppSettings.smtpServer = smtpServer; } - public static String getSmtpServer() - { + public static String getSmtpServer() { return smtpServer; } - static void setSmtpPort(String smtpPort) - { + static void setSmtpPort(String smtpPort) { AppSettings.smtpPort = smtpPort; } - public static String getSmtpPort() - { + public static String getSmtpPort() { return smtpPort; } - static void setSmtpUsername(String smtpUsername) - { + static void setSmtpUsername(String smtpUsername) { AppSettings.smtpUsername = smtpUsername; } - public static String getSmtpUsername() - { + public static String getSmtpUsername() { return smtpUsername; } - static void setSmtpPassword(String smtpPassword) - { + static void setSmtpPassword(String smtpPassword) { AppSettings.smtpPassword = smtpPassword; } - public static String getSmtpPassword() - { + public static String getSmtpPassword() { return smtpPassword; } - static void setSmtpSsl(boolean smtpSsl) - { + static void setSmtpSsl(boolean smtpSsl) { AppSettings.smtpSsl = smtpSsl; } - public static boolean isSmtpSsl() - { + public static boolean isSmtpSsl() { return smtpSsl; } - static void setAutoEmailTargets(String autoEmailTargets) - { + static void setAutoEmailTargets(String autoEmailTargets) { AppSettings.autoEmailTargets = autoEmailTargets; } - public static String getAutoEmailTargets() - { + public static String getAutoEmailTargets() { return autoEmailTargets; } - public static boolean isDebugToFile() - { + public static boolean isDebugToFile() { return debugToFile; } - public static void setDebugToFile(boolean debugToFile) - { + public static void setDebugToFile(boolean debugToFile) { AppSettings.debugToFile = debugToFile; } - public static boolean shouldSendZipFile() - { + public static boolean shouldSendZipFile() { return shouldSendZipFile; } - public static void setShouldSendZipFile(boolean shouldSendZipFile) - { + public static void setShouldSendZipFile(boolean shouldSendZipFile) { AppSettings.shouldSendZipFile = shouldSendZipFile; } - private static String getSmtpFrom() - { + private static String getSmtpFrom() { return smtpFrom; } - public static void setSmtpFrom(String smtpFrom) - { + public static void setSmtpFrom(String smtpFrom) { AppSettings.smtpFrom = smtpFrom; } @@ -422,204 +369,164 @@ public static void setSmtpFrom(String smtpFrom) * * @return */ - public static String getSenderAddress() - { - if (getSmtpFrom() != null && getSmtpFrom().length() > 0) - { + public static String getSenderAddress() { + if (getSmtpFrom() != null && getSmtpFrom().length() > 0) { return getSmtpFrom(); } return getSmtpUsername(); } - public static boolean isAutoSendEnabled() - { + public static boolean isAutoSendEnabled() { return autoSendEnabled; } - public static void setAutoSendEnabled(boolean autoSendEnabled) - { + public static void setAutoSendEnabled(boolean autoSendEnabled) { AppSettings.autoSendEnabled = autoSendEnabled; } - public static boolean shouldLogToOpenGTS() - { + public static boolean shouldLogToOpenGTS() { return LogToOpenGTS; } - public static void setLogToOpenGTS(boolean logToOpenGTS) - { + public static void setLogToOpenGTS(boolean logToOpenGTS) { AppSettings.LogToOpenGTS = logToOpenGTS; } - public static boolean isOpenGTSEnabled() - { + public static boolean isOpenGTSEnabled() { return openGTSEnabled; } - public static void setOpenGTSEnabled(boolean openGTSEnabled) - { + public static void setOpenGTSEnabled(boolean openGTSEnabled) { AppSettings.openGTSEnabled = openGTSEnabled; } - public static boolean isAutoOpenGTSEnabled() - { + public static boolean isAutoOpenGTSEnabled() { return autoOpenGTSEnabled; } - public static void setAutoOpenGTSEnabled(boolean autoOpenGTSEnabled) - { + public static void setAutoOpenGTSEnabled(boolean autoOpenGTSEnabled) { AppSettings.autoOpenGTSEnabled = autoOpenGTSEnabled; } - public static String getOpenGTSServer() - { + public static String getOpenGTSServer() { return openGTSServer; } - public static void setOpenGTSServer(String openGTSServer) - { + public static void setOpenGTSServer(String openGTSServer) { AppSettings.openGTSServer = openGTSServer; } - public static String getOpenGTSServerPort() - { + public static String getOpenGTSServerPort() { return openGTSServerPort; } - public static void setOpenGTSServerPort(String openGTSServerPort) - { + public static void setOpenGTSServerPort(String openGTSServerPort) { AppSettings.openGTSServerPort = openGTSServerPort; } - public static String getOpenGTSServerCommunicationMethod() - { + public static String getOpenGTSServerCommunicationMethod() { return openGTSServerCommunicationMethod; } - public static void setOpenGTSServerCommunicationMethod(String openGTSServerCommunicationMethod) - { + public static void setOpenGTSServerCommunicationMethod(String openGTSServerCommunicationMethod) { AppSettings.openGTSServerCommunicationMethod = openGTSServerCommunicationMethod; } - public static String getOpenGTSServerPath() - { + public static String getOpenGTSServerPath() { return openGTSServerPath; } - public static void setOpenGTSServerPath(String openGTSServerPath) - { + public static void setOpenGTSServerPath(String openGTSServerPath) { AppSettings.openGTSServerPath = openGTSServerPath; } - public static String getOpenGTSDeviceId() - { + public static String getOpenGTSDeviceId() { return openGTSDeviceId; } - public static void setOpenGTSDeviceId(String openGTSDeviceId) - { + public static void setOpenGTSDeviceId(String openGTSDeviceId) { AppSettings.openGTSDeviceId = openGTSDeviceId; } - public static String getFtpServerName() - { + public static String getFtpServerName() { return ftpServerName; } - public static void setFtpServerName(String ftpServerName) - { + public static void setFtpServerName(String ftpServerName) { AppSettings.ftpServerName = ftpServerName; } - public static int getFtpPort() - { + public static int getFtpPort() { return ftpPort; } - public static void setFtpPort(int ftpPort) - { + public static void setFtpPort(int ftpPort) { AppSettings.ftpPort = ftpPort; } - public static String getFtpUsername() - { + public static String getFtpUsername() { return ftpUsername; } - public static void setFtpUsername(String ftpUsername) - { + public static void setFtpUsername(String ftpUsername) { AppSettings.ftpUsername = ftpUsername; } - public static String getFtpPassword() - { + public static String getFtpPassword() { return ftpPassword; } - public static void setFtpPassword(String ftpPassword) - { + public static void setFtpPassword(String ftpPassword) { AppSettings.ftpPassword = ftpPassword; } - public static boolean FtpUseFtps() - { + public static boolean FtpUseFtps() { return ftpUseFtps; } - public static void setFtpUseFtps(boolean ftpUseFtps) - { + public static void setFtpUseFtps(boolean ftpUseFtps) { AppSettings.ftpUseFtps = ftpUseFtps; } - public static String getFtpProtocol() - { + public static String getFtpProtocol() { return ftpProtocol; } - public static void setFtpProtocol(String ftpProtocol) - { + public static void setFtpProtocol(String ftpProtocol) { AppSettings.ftpProtocol = ftpProtocol; } - public static boolean FtpImplicit() - { + public static boolean FtpImplicit() { return ftpImplicit; } - public static void setFtpImplicit(boolean ftpImplicit) - { + public static void setFtpImplicit(boolean ftpImplicit) { AppSettings.ftpImplicit = ftpImplicit; } - public static boolean isAutoFtpEnabled() - { + public static boolean isAutoFtpEnabled() { return autoFtpEnabled; } - public static void setAutoFtpEnabled(boolean autoFtpEnabled) - { + public static void setAutoFtpEnabled(boolean autoFtpEnabled) { AppSettings.autoFtpEnabled = autoFtpEnabled; } - public static String getCustomFileName() - { + public static String getCustomFileName() { return customFileName; } - public static void setCustomFileName(String customFileName) - { + public static void setCustomFileName(String customFileName) { AppSettings.customFileName = customFileName; } - public static boolean isCustomFile() - { + public static boolean isCustomFile() { return isCustomFile; } - public static void setCustomFile(boolean customFile) - { + public static void setCustomFile(boolean customFile) { AppSettings.isCustomFile = customFile; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/FileDialog.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/FileDialog.java index 0a7e28ee1..2d1d102f7 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/FileDialog.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/FileDialog.java @@ -1,11 +1,5 @@ package com.mendhak.gpslogger.common.FileDialog; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.TreeMap; - import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; @@ -23,367 +17,371 @@ import com.mendhak.gpslogger.R; import com.mendhak.gpslogger.common.Utilities; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.TreeMap; + /** * https://code.google.com/p/android-file-dialog/ * Activity para escolha de arquivos/diretorios. - * + * * @author android - * */ public class FileDialog extends ListActivity { - /** - * Chave de um item da lista de paths. - */ - private static final String ITEM_KEY = "key"; - - /** - * Imagem de um item da lista de paths (diretorio ou arquivo). - */ - private static final String ITEM_IMAGE = "image"; - - /** - * Diretorio raiz. - */ - private static final String ROOT = "/"; - - /** - * Parametro de entrada da Activity: path inicial. Padrao: ROOT. - */ - public static final String START_PATH = "START_PATH"; - - /** - * Parametro de entrada da Activity: filtro de formatos de arquivos. Padrao: - * null. - */ - public static final String FORMAT_FILTER = "FORMAT_FILTER"; - - /** - * Parametro de saida da Activity: path escolhido. Padrao: null. - */ - public static final String RESULT_PATH = "RESULT_PATH"; - - /** - * Parametro de entrada da Activity: tipo de selecao: pode criar novos paths - * ou nao. Padrao: nao permite. - * - * @see {@link SelectionMode} - */ - public static final String SELECTION_MODE = "SELECTION_MODE"; - - /** - * Parametro de entrada da Activity: se e permitido escolher diretorios. - * Padrao: falso. - */ - public static final String CAN_SELECT_DIR = "CAN_SELECT_DIR"; - - private List path = null; - private TextView myPath; - private EditText mFileName; - private ArrayList> mList; - - private Button selectButton; - - private LinearLayout layoutSelect; - private LinearLayout layoutCreate; - private InputMethodManager inputManager; - private String parentPath; - private String currentPath = ROOT; - - private int selectionMode = SelectionMode.MODE_CREATE; - - private String[] formatFilter = null; - - private boolean canSelectDir = false; - - private File selectedFile; - private HashMap lastPositions = new HashMap(); - - /** - * Called when the activity is first created. Configura todos os parametros - * de entrada e das VIEWS.. - */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setResult(RESULT_CANCELED, getIntent()); - - setContentView(R.layout.file_dialog_main); - myPath = (TextView) findViewById(R.id.path); - mFileName = (EditText) findViewById(R.id.fdEditTextFile); - - inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); - - selectButton = (Button) findViewById(R.id.fdButtonSelect); - selectButton.setEnabled(false); - selectButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - if (selectedFile != null) { - getIntent().putExtra(RESULT_PATH, selectedFile.getPath()); - setResult(RESULT_OK, getIntent()); - finish(); - } - } - }); - - final Button newButton = (Button) findViewById(R.id.fdButtonNew); - newButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - setCreateVisible(v); - - mFileName.setText(""); - mFileName.requestFocus(); - } - }); - - selectionMode = getIntent().getIntExtra(SELECTION_MODE, SelectionMode.MODE_CREATE); - - formatFilter = getIntent().getStringArrayExtra(FORMAT_FILTER); - - canSelectDir = getIntent().getBooleanExtra(CAN_SELECT_DIR, false); - - if (selectionMode == SelectionMode.MODE_OPEN) { - newButton.setEnabled(false); - } - - layoutSelect = (LinearLayout) findViewById(R.id.fdLinearLayoutSelect); - layoutCreate = (LinearLayout) findViewById(R.id.fdLinearLayoutCreate); - layoutCreate.setVisibility(View.GONE); - - final Button cancelButton = (Button) findViewById(R.id.fdButtonCancel); - cancelButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - setSelectVisible(v); - } - - }); - final Button createButton = (Button) findViewById(R.id.fdButtonCreate); - createButton.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - if (mFileName.getText().length() > 0) { - getIntent().putExtra(RESULT_PATH, currentPath + "/" + mFileName.getText()); - setResult(RESULT_OK, getIntent()); - finish(); - } - } - }); - - String startPath = getIntent().getStringExtra(START_PATH); - startPath = startPath != null ? startPath : ROOT; - if (canSelectDir) { - File file = new File(startPath); - selectedFile = file; - selectButton.setEnabled(true); - } - getDir(startPath); - } - - private void getDir(String dirPath) { - - boolean useAutoSelection = dirPath.length() < currentPath.length(); - - Integer position = lastPositions.get(parentPath); - - getDirImpl(dirPath); - - if (position != null && useAutoSelection) { - getListView().setSelection(position); - } - - } - - /** - * Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido. - * - * @param dirPath - * Diretorio pai. - */ - private void getDirImpl(final String dirPath) { - - currentPath = dirPath; - - final List item = new ArrayList(); - path = new ArrayList(); - mList = new ArrayList>(); - - File f = new File(currentPath); - File[] files = Utilities.GetFilesInFolder(f); - if (files == null) { - currentPath = ROOT; - f = new File(currentPath); - files = Utilities.GetFilesInFolder(f); - } - myPath.setText(getText(R.string.filedialog_location) + ": " + currentPath); - - if (!currentPath.equals(ROOT)) { - - item.add(ROOT); - addItem(ROOT, R.drawable.folder); - path.add(ROOT); - - item.add("../"); - addItem("../", R.drawable.folder); - path.add(f.getParent()); - parentPath = f.getParent(); - - } - - TreeMap dirsMap = new TreeMap(); - TreeMap dirsPathMap = new TreeMap(); - TreeMap filesMap = new TreeMap(); - TreeMap filesPathMap = new TreeMap(); - for (File file : files) { - if (file.isDirectory()) { - String dirName = file.getName(); - dirsMap.put(dirName, dirName); - dirsPathMap.put(dirName, file.getPath()); - } else { - final String fileName = file.getName(); - final String fileNameLwr = fileName.toLowerCase(); - // se ha um filtro de formatos, utiliza-o - if (formatFilter != null) { - boolean contains = false; - for (int i = 0; i < formatFilter.length; i++) { - final String formatLwr = formatFilter[i].toLowerCase(); - if (fileNameLwr.endsWith(formatLwr)) { - contains = true; - break; - } - } - if (contains) { - filesMap.put(fileName, fileName); - filesPathMap.put(fileName, file.getPath()); - } - // senao, adiciona todos os arquivos - } else { - filesMap.put(fileName, fileName); - filesPathMap.put(fileName, file.getPath()); - } - } - } - item.addAll(dirsMap.tailMap("").values()); - item.addAll(filesMap.tailMap("").values()); - path.addAll(dirsPathMap.tailMap("").values()); - path.addAll(filesPathMap.tailMap("").values()); - - SimpleAdapter fileList = new SimpleAdapter(this, mList, R.layout.file_dialog_row, new String[] { - ITEM_KEY, ITEM_IMAGE }, new int[] { R.id.fdrowtext, R.id.fdrowimage }); - - for (String dir : dirsMap.tailMap("").values()) { - addItem(dir, R.drawable.folder); - } - - for (String file : filesMap.tailMap("").values()) { - addItem(file, R.drawable.file); - } - - fileList.notifyDataSetChanged(); - - setListAdapter(fileList); - - } - - private void addItem(String fileName, int imageId) { - HashMap item = new HashMap(); - item.put(ITEM_KEY, fileName); - item.put(ITEM_IMAGE, imageId); - mList.add(item); - } - - /** - * Quando clica no item da lista, deve-se: 1) Se for diretorio, abre seus - * arquivos filhos; 2) Se puder escolher diretorio, define-o como sendo o - * path escolhido. 3) Se for arquivo, define-o como path escolhido. 4) Ativa - * botao de selecao. - */ - @Override - protected void onListItemClick(ListView l, View v, int position, long id) { - - File file = new File(path.get(position)); - - setSelectVisible(v); - - if (file.isDirectory()) { - selectButton.setEnabled(false); - if (file.canRead()) { - lastPositions.put(currentPath, position); - getDir(path.get(position)); - if (canSelectDir) { - selectedFile = file; - v.setSelected(true); - selectButton.setEnabled(true); - } - } else { - new AlertDialog.Builder(this).setIcon(R.drawable.gpsloggericon2) - .setTitle("[" + file.getName() + "] " + getText(R.string.filedialog_cantreadfolder)) - .setPositiveButton("OK", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - - } - }).show(); - } - } else { - selectedFile = file; - v.setSelected(true); - selectButton.setEnabled(true); - } - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if ((keyCode == KeyEvent.KEYCODE_BACK)) { - selectButton.setEnabled(false); - - if (layoutCreate.getVisibility() == View.VISIBLE) { - layoutCreate.setVisibility(View.GONE); - layoutSelect.setVisibility(View.VISIBLE); - } else { - if (!currentPath.equals(ROOT)) { - getDir(parentPath); - } else { - return super.onKeyDown(keyCode, event); - } - } - - return true; - } else { - return super.onKeyDown(keyCode, event); - } - } - - /** - * Define se o botao de CREATE e visivel. - * - * @param v - */ - private void setCreateVisible(View v) { - layoutCreate.setVisibility(View.VISIBLE); - layoutSelect.setVisibility(View.GONE); - - inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); - selectButton.setEnabled(false); - } - - /** - * Define se o botao de SELECT e visivel. - * - * @param v - */ - private void setSelectVisible(View v) { - layoutCreate.setVisibility(View.GONE); - layoutSelect.setVisibility(View.VISIBLE); - - inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); - selectButton.setEnabled(false); - } + /** + * Chave de um item da lista de paths. + */ + private static final String ITEM_KEY = "key"; + + /** + * Imagem de um item da lista de paths (diretorio ou arquivo). + */ + private static final String ITEM_IMAGE = "image"; + + /** + * Diretorio raiz. + */ + private static final String ROOT = "/"; + + /** + * Parametro de entrada da Activity: path inicial. Padrao: ROOT. + */ + public static final String START_PATH = "START_PATH"; + + /** + * Parametro de entrada da Activity: filtro de formatos de arquivos. Padrao: + * null. + */ + public static final String FORMAT_FILTER = "FORMAT_FILTER"; + + /** + * Parametro de saida da Activity: path escolhido. Padrao: null. + */ + public static final String RESULT_PATH = "RESULT_PATH"; + + /** + * Parametro de entrada da Activity: tipo de selecao: pode criar novos paths + * ou nao. Padrao: nao permite. + * + * @see {@link SelectionMode} + */ + public static final String SELECTION_MODE = "SELECTION_MODE"; + + /** + * Parametro de entrada da Activity: se e permitido escolher diretorios. + * Padrao: falso. + */ + public static final String CAN_SELECT_DIR = "CAN_SELECT_DIR"; + + private List path = null; + private TextView myPath; + private EditText mFileName; + private ArrayList> mList; + + private Button selectButton; + + private LinearLayout layoutSelect; + private LinearLayout layoutCreate; + private InputMethodManager inputManager; + private String parentPath; + private String currentPath = ROOT; + + private int selectionMode = SelectionMode.MODE_CREATE; + + private String[] formatFilter = null; + + private boolean canSelectDir = false; + + private File selectedFile; + private HashMap lastPositions = new HashMap(); + + /** + * Called when the activity is first created. Configura todos os parametros + * de entrada e das VIEWS.. + */ + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setResult(RESULT_CANCELED, getIntent()); + + setContentView(R.layout.file_dialog_main); + myPath = (TextView) findViewById(R.id.path); + mFileName = (EditText) findViewById(R.id.fdEditTextFile); + + inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); + + selectButton = (Button) findViewById(R.id.fdButtonSelect); + selectButton.setEnabled(false); + selectButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + if (selectedFile != null) { + getIntent().putExtra(RESULT_PATH, selectedFile.getPath()); + setResult(RESULT_OK, getIntent()); + finish(); + } + } + }); + + final Button newButton = (Button) findViewById(R.id.fdButtonNew); + newButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + setCreateVisible(v); + + mFileName.setText(""); + mFileName.requestFocus(); + } + }); + + selectionMode = getIntent().getIntExtra(SELECTION_MODE, SelectionMode.MODE_CREATE); + + formatFilter = getIntent().getStringArrayExtra(FORMAT_FILTER); + + canSelectDir = getIntent().getBooleanExtra(CAN_SELECT_DIR, false); + + if (selectionMode == SelectionMode.MODE_OPEN) { + newButton.setEnabled(false); + } + + layoutSelect = (LinearLayout) findViewById(R.id.fdLinearLayoutSelect); + layoutCreate = (LinearLayout) findViewById(R.id.fdLinearLayoutCreate); + layoutCreate.setVisibility(View.GONE); + + final Button cancelButton = (Button) findViewById(R.id.fdButtonCancel); + cancelButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + setSelectVisible(v); + } + + }); + final Button createButton = (Button) findViewById(R.id.fdButtonCreate); + createButton.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + if (mFileName.getText().length() > 0) { + getIntent().putExtra(RESULT_PATH, currentPath + "/" + mFileName.getText()); + setResult(RESULT_OK, getIntent()); + finish(); + } + } + }); + + String startPath = getIntent().getStringExtra(START_PATH); + startPath = startPath != null ? startPath : ROOT; + if (canSelectDir) { + File file = new File(startPath); + selectedFile = file; + selectButton.setEnabled(true); + } + getDir(startPath); + } + + private void getDir(String dirPath) { + + boolean useAutoSelection = dirPath.length() < currentPath.length(); + + Integer position = lastPositions.get(parentPath); + + getDirImpl(dirPath); + + if (position != null && useAutoSelection) { + getListView().setSelection(position); + } + + } + + /** + * Monta a estrutura de arquivos e diretorios filhos do diretorio fornecido. + * + * @param dirPath Diretorio pai. + */ + private void getDirImpl(final String dirPath) { + + currentPath = dirPath; + + final List item = new ArrayList(); + path = new ArrayList(); + mList = new ArrayList>(); + + File f = new File(currentPath); + File[] files = Utilities.GetFilesInFolder(f); + if (files == null) { + currentPath = ROOT; + f = new File(currentPath); + files = Utilities.GetFilesInFolder(f); + } + myPath.setText(getText(R.string.filedialog_location) + ": " + currentPath); + + if (!currentPath.equals(ROOT)) { + + item.add(ROOT); + addItem(ROOT, R.drawable.folder); + path.add(ROOT); + + item.add("../"); + addItem("../", R.drawable.folder); + path.add(f.getParent()); + parentPath = f.getParent(); + + } + + TreeMap dirsMap = new TreeMap(); + TreeMap dirsPathMap = new TreeMap(); + TreeMap filesMap = new TreeMap(); + TreeMap filesPathMap = new TreeMap(); + for (File file : files) { + if (file.isDirectory()) { + String dirName = file.getName(); + dirsMap.put(dirName, dirName); + dirsPathMap.put(dirName, file.getPath()); + } else { + final String fileName = file.getName(); + final String fileNameLwr = fileName.toLowerCase(); + // se ha um filtro de formatos, utiliza-o + if (formatFilter != null) { + boolean contains = false; + for (int i = 0; i < formatFilter.length; i++) { + final String formatLwr = formatFilter[i].toLowerCase(); + if (fileNameLwr.endsWith(formatLwr)) { + contains = true; + break; + } + } + if (contains) { + filesMap.put(fileName, fileName); + filesPathMap.put(fileName, file.getPath()); + } + // senao, adiciona todos os arquivos + } else { + filesMap.put(fileName, fileName); + filesPathMap.put(fileName, file.getPath()); + } + } + } + item.addAll(dirsMap.tailMap("").values()); + item.addAll(filesMap.tailMap("").values()); + path.addAll(dirsPathMap.tailMap("").values()); + path.addAll(filesPathMap.tailMap("").values()); + + SimpleAdapter fileList = new SimpleAdapter(this, mList, R.layout.file_dialog_row, new String[]{ + ITEM_KEY, ITEM_IMAGE}, new int[]{R.id.fdrowtext, R.id.fdrowimage}); + + for (String dir : dirsMap.tailMap("").values()) { + addItem(dir, R.drawable.folder); + } + + for (String file : filesMap.tailMap("").values()) { + addItem(file, R.drawable.file); + } + + fileList.notifyDataSetChanged(); + + setListAdapter(fileList); + + } + + private void addItem(String fileName, int imageId) { + HashMap item = new HashMap(); + item.put(ITEM_KEY, fileName); + item.put(ITEM_IMAGE, imageId); + mList.add(item); + } + + /** + * Quando clica no item da lista, deve-se: 1) Se for diretorio, abre seus + * arquivos filhos; 2) Se puder escolher diretorio, define-o como sendo o + * path escolhido. 3) Se for arquivo, define-o como path escolhido. 4) Ativa + * botao de selecao. + */ + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + + File file = new File(path.get(position)); + + setSelectVisible(v); + + if (file.isDirectory()) { + selectButton.setEnabled(false); + if (file.canRead()) { + lastPositions.put(currentPath, position); + getDir(path.get(position)); + if (canSelectDir) { + selectedFile = file; + v.setSelected(true); + selectButton.setEnabled(true); + } + } else { + new AlertDialog.Builder(this).setIcon(R.drawable.gpsloggericon2) + .setTitle("[" + file.getName() + "] " + getText(R.string.filedialog_cantreadfolder)) + .setPositiveButton("OK", new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + + } + }).show(); + } + } else { + selectedFile = file; + v.setSelected(true); + selectButton.setEnabled(true); + } + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if ((keyCode == KeyEvent.KEYCODE_BACK)) { + selectButton.setEnabled(false); + + if (layoutCreate.getVisibility() == View.VISIBLE) { + layoutCreate.setVisibility(View.GONE); + layoutSelect.setVisibility(View.VISIBLE); + } else { + if (!currentPath.equals(ROOT)) { + getDir(parentPath); + } else { + return super.onKeyDown(keyCode, event); + } + } + + return true; + } else { + return super.onKeyDown(keyCode, event); + } + } + + /** + * Define se o botao de CREATE e visivel. + * + * @param v + */ + private void setCreateVisible(View v) { + layoutCreate.setVisibility(View.VISIBLE); + layoutSelect.setVisibility(View.GONE); + + inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); + selectButton.setEnabled(false); + } + + /** + * Define se o botao de SELECT e visivel. + * + * @param v + */ + private void setSelectVisible(View v) { + layoutCreate.setVisibility(View.GONE); + layoutSelect.setVisibility(View.VISIBLE); + + inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); + selectButton.setEnabled(false); + } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/SelectionMode.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/SelectionMode.java index ac8dd063e..6bd70dcc2 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/SelectionMode.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/FileDialog/SelectionMode.java @@ -1,7 +1,7 @@ package com.mendhak.gpslogger.common.FileDialog; public class SelectionMode { - public static final int MODE_CREATE = 0; + public static final int MODE_CREATE = 0; - public static final int MODE_OPEN = 1; + public static final int MODE_OPEN = 1; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/GpsRollingFileAppender.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/GpsRollingFileAppender.java index aca50695d..ba8096513 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/GpsRollingFileAppender.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/GpsRollingFileAppender.java @@ -3,8 +3,7 @@ import ch.qos.logback.core.rolling.RollingFileAppender; -public class GpsRollingFileAppender extends RollingFileAppender { - +public class GpsRollingFileAppender extends RollingFileAppender { @Override @@ -14,7 +13,7 @@ protected void subAppend(E e) { // It checks if the user has requested a // debug log file and only then writes // to a file. - if(AppSettings.isDebugToFile()){ + if (AppSettings.isDebugToFile()) { super.subAppend(e); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/IActionListener.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/IActionListener.java index aed0ab555..4b923e8f4 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/IActionListener.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/IActionListener.java @@ -17,8 +17,7 @@ package com.mendhak.gpslogger.common; -public interface IActionListener -{ +public interface IActionListener { public void OnComplete(); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/IMessageBoxCallback.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/IMessageBoxCallback.java index 239cc5234..bcdce1d7a 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/IMessageBoxCallback.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/IMessageBoxCallback.java @@ -17,8 +17,7 @@ package com.mendhak.gpslogger.common; -public interface IMessageBoxCallback -{ +public interface IMessageBoxCallback { public void MessageBoxResult(int which); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/OpenGTSClient.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/OpenGTSClient.java index 93301ab37..3bc53c2f0 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/OpenGTSClient.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/OpenGTSClient.java @@ -37,8 +37,7 @@ * * @author Francisco Reynoso */ -public class OpenGTSClient -{ +public class OpenGTSClient { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(OpenGTSClient.class.getSimpleName()); @@ -52,8 +51,7 @@ public class OpenGTSClient private int sentLocationsCount = 0; - public OpenGTSClient(String server, Integer port, String path, IActionListener callback, Context applicationContext) - { + public OpenGTSClient(String server, Integer port, String path, IActionListener callback, Context applicationContext) { this.server = server; this.port = port; this.path = path; @@ -61,8 +59,7 @@ public OpenGTSClient(String server, Integer port, String path, IActionListener c this.applicationContext = applicationContext; } - public void sendHTTP(String id, Location location) - { + public void sendHTTP(String id, Location location) { sendHTTP(id, new Location[]{location}); } @@ -76,10 +73,8 @@ public void sendHTTP(String id, Location location) * @param locations locations */ - public void sendHTTP(String id, Location[] locations) - { - try - { + public void sendHTTP(String id, Location[] locations) { + try { locationsCount = locations.length; StringBuilder url = new StringBuilder(); url.append("http://"); @@ -87,8 +82,7 @@ public void sendHTTP(String id, Location[] locations) httpClient = new AsyncHttpClient(); - for (Location loc : locations) - { + for (Location loc : locations) { RequestParams params = new RequestParams(); params.put("id", id); params.put("code", "0xF020"); @@ -99,83 +93,68 @@ public void sendHTTP(String id, Location[] locations) tracer.debug("Sending URL " + url + " with params " + params.toString()); httpClient.get(applicationContext, url.toString(), params, new MyAsyncHttpResponseHandler(this)); } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("OpenGTSClient.sendHTTP", e); OnFailure(); } } - public void sendRAW(String id, Location location) - { + public void sendRAW(String id, Location location) { // TODO } - private void sendRAW(String id, Location[] locations) - { + private void sendRAW(String id, Location[] locations) { // TODO } - private String getURL() - { + private String getURL() { StringBuilder url = new StringBuilder(); url.append(server); - if (port != null) - { + if (port != null) { url.append(":"); url.append(port); } - if (path != null) - { + if (path != null) { url.append(path); } return url.toString(); } - private class MyAsyncHttpResponseHandler extends AsyncHttpResponseHandler - { + private class MyAsyncHttpResponseHandler extends AsyncHttpResponseHandler { private OpenGTSClient callback; - public MyAsyncHttpResponseHandler(OpenGTSClient callback) - { + public MyAsyncHttpResponseHandler(OpenGTSClient callback) { super(); this.callback = callback; } @Override - public void onSuccess(String response) - { + public void onSuccess(String response) { tracer.info("Response Success :" + response); callback.OnCompleteLocation(); } @Override - public void onFailure(Throwable e, String response) - { + public void onFailure(Throwable e, String response) { tracer.error("OnCompleteLocation.MyAsyncHttpResponseHandler Failure with response :" + response, new Exception(e)); callback.OnFailure(); } } - public void OnCompleteLocation() - { + public void OnCompleteLocation() { sentLocationsCount += 1; tracer.debug("Sent locations count: " + sentLocationsCount + "/" + locationsCount); - if (locationsCount == sentLocationsCount) - { + if (locationsCount == sentLocationsCount) { OnComplete(); } } - public void OnComplete() - { + public void OnComplete() { callback.OnComplete(); } - public void OnFailure() - { + public void OnFailure() { httpClient.cancelRequests(applicationContext, true); callback.OnFailure(); } @@ -189,8 +168,7 @@ public void OnFailure() * @param loc location * @return GPRMC data */ - public static String GPRMCEncode(Location loc) - { + public static String GPRMCEncode(Location loc) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US); DecimalFormat f = new DecimalFormat("0.000000", dfs); @@ -212,22 +190,19 @@ public static String GPRMCEncode(Location loc) return gprmc; } - public static String NMEAGPRMCTime(Date dateToFormat) - { + public static String NMEAGPRMCTime(Date dateToFormat) { SimpleDateFormat sdf = new SimpleDateFormat("HHmmss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(dateToFormat); } - public static String NMEAGPRMCDate(Date dateToFormat) - { + public static String NMEAGPRMCDate(Date dateToFormat) { SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(dateToFormat); } - public static String NMEAGPRMCCoord(double coord) - { + public static String NMEAGPRMCCoord(double coord) { // “DDDMM.MMMMM” int degrees = (int) coord; double minutes = (coord - degrees) * 60; @@ -241,16 +216,13 @@ public static String NMEAGPRMCCoord(double coord) } - public static String NMEACheckSum(String msg) - { + public static String NMEACheckSum(String msg) { int chk = 0; - for (int i = 1; i < msg.length(); i++) - { + for (int i = 1; i < msg.length(); i++) { chk ^= msg.charAt(i); } String chk_s = Integer.toHexString(chk).toUpperCase(); - while (chk_s.length() < 2) - { + while (chk_s.length() < 2) { chk_s = "0" + chk_s; } return chk_s; @@ -262,8 +234,7 @@ public static String NMEACheckSum(String msg) * @param mps meters per second * @return knots */ - public static double MetersPerSecondToKnots(double mps) - { + public static double MetersPerSecondToKnots(double mps) { // Google "meters per second to knots" return mps * 1.94384449; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/RejectionHandler.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/RejectionHandler.java index cacc33afa..276173170 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/RejectionHandler.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/RejectionHandler.java @@ -22,14 +22,12 @@ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; -public class RejectionHandler implements RejectedExecutionHandler -{ +public class RejectionHandler implements RejectedExecutionHandler { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(RejectionHandler.class.getSimpleName()); @Override - public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) - { + public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) { tracer.warn("Could not queue task, some points may not be logged."); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/Session.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/Session.java index 37ac3805e..8ce8007d2 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/Session.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/Session.java @@ -22,8 +22,7 @@ import android.location.Location; import org.slf4j.LoggerFactory; -public class Session extends Application -{ +public class Session extends Application { private static org.slf4j.Logger tracer = LoggerFactory.getLogger(Session.class.getSimpleName()); @@ -49,16 +48,14 @@ public class Session extends Application private static boolean readyToBeAutoSent = false; private static String description = ""; private static boolean isSinglePointMode = false; - private static int retryTimeout=0; + private static int retryTimeout = 0; private static boolean waitingForLocation; - public static boolean isSinglePointMode() - { + public static boolean isSinglePointMode() { return isSinglePointMode; } - public static void setSinglePointMode(boolean singlePointMode) - { + public static void setSinglePointMode(boolean singlePointMode) { isSinglePointMode = singlePointMode; } @@ -67,84 +64,70 @@ public static void setSinglePointMode(boolean singlePointMode) /** * @return whether GPS (tower) is enabled */ - public static boolean isTowerEnabled() - { + public static boolean isTowerEnabled() { return towerEnabled; } /** * @param towerEnabled set whether GPS (tower) is enabled */ - public static void setTowerEnabled(boolean towerEnabled) - { + public static void setTowerEnabled(boolean towerEnabled) { Session.towerEnabled = towerEnabled; } /** * @return whether GPS (satellite) is enabled */ - public static boolean isGpsEnabled() - { + public static boolean isGpsEnabled() { return gpsEnabled; } /** * @param gpsEnabled set whether GPS (satellite) is enabled */ - public static void setGpsEnabled(boolean gpsEnabled) - { + public static void setGpsEnabled(boolean gpsEnabled) { Session.gpsEnabled = gpsEnabled; } /** * @return whether logging has started */ - public static boolean isStarted() - { + public static boolean isStarted() { return isStarted; } /** * @param isStarted set whether logging has started */ - public static void setStarted(boolean isStarted) - { + public static void setStarted(boolean isStarted) { Session.isStarted = isStarted; - if (isStarted) - { - Session.startTimeStamp = System.currentTimeMillis(); + if (isStarted) { + Session.startTimeStamp = System.currentTimeMillis(); } } /** * @return the isUsingGps */ - public static boolean isUsingGps() - { + public static boolean isUsingGps() { return isUsingGps; } /** * @param isUsingGps the isUsingGps to set */ - public static void setUsingGps(boolean isUsingGps) - { + public static void setUsingGps(boolean isUsingGps) { Session.isUsingGps = isUsingGps; } /** * @return the currentFileName (without extension) */ - public static String getCurrentFileName() - { - if(AppSettings.isCustomFile() && !Utilities.IsNullOrEmpty(currentFileName)) - { + public static String getCurrentFileName() { + if (AppSettings.isCustomFile() && !Utilities.IsNullOrEmpty(currentFileName)) { return Utilities.GetFormattedCustomFileName(currentFileName); - } - else - { - if(!Utilities.IsNullOrEmpty(currentFileName) && AppSettings.shouldPrefixSerialToFileName() && !currentFileName.contains(Utilities.GetBuildSerial())) - { + } else { + if (!Utilities.IsNullOrEmpty(currentFileName) && AppSettings.shouldPrefixSerialToFileName() && !currentFileName.contains(Utilities.GetBuildSerial())) { currentFileName = String.valueOf(Utilities.GetBuildSerial()) + "_" + currentFileName; } } @@ -152,12 +135,10 @@ public static String getCurrentFileName() } - /** * @param currentFileName the currentFileName to set */ - public static void setCurrentFileName(String currentFileName) - { + public static void setCurrentFileName(String currentFileName) { tracer.info("Setting file name - " + currentFileName); Session.currentFileName = currentFileName; } @@ -165,78 +146,61 @@ public static void setCurrentFileName(String currentFileName) /** * @return the number of satellites visible */ - public static int getSatelliteCount() - { + public static int getSatelliteCount() { return satellites; } /** * @param satellites sets the number of visible satellites */ - public static void setSatelliteCount(int satellites) - { + public static void setSatelliteCount(int satellites) { Session.satellites = satellites; } - /** * @return the currentLatitude */ - public static double getCurrentLatitude() - { - if (getCurrentLocationInfo() != null) - { + public static double getCurrentLatitude() { + if (getCurrentLocationInfo() != null) { return getCurrentLocationInfo().getLatitude(); - } - else - { + } else { return 0; } } - public static double getPreviousLatitude() - { + public static double getPreviousLatitude() { Location loc = getPreviousLocationInfo(); return loc != null ? loc.getLatitude() : 0; } - public static double getPreviousLongitude() - { + public static double getPreviousLongitude() { Location loc = getPreviousLocationInfo(); return loc != null ? loc.getLongitude() : 0; } - public static double getTotalTravelled() - { + public static double getTotalTravelled() { return totalTravelled; } - public static int getNumLegs() - { + public static int getNumLegs() { return numLegs; } - public static void setTotalTravelled(double totalTravelled) - { - if (totalTravelled == 0) - { + public static void setTotalTravelled(double totalTravelled) { + if (totalTravelled == 0) { Session.numLegs = 0; - } - else - { + } else { Session.numLegs++; } Session.totalTravelled = totalTravelled; } - public static Location getPreviousLocationInfo() - { + public static Location getPreviousLocationInfo() { return previousLocationInfo; } - public static void setPreviousLocationInfo(Location previousLocationInfo) - { + public static void setPreviousLocationInfo(Location previousLocationInfo) { Session.previousLocationInfo = previousLocationInfo; } @@ -244,22 +208,17 @@ public static void setPreviousLocationInfo(Location previousLocationInfo) /** * Determines whether a valid location is available */ - public static boolean hasValidLocation() - { + public static boolean hasValidLocation() { return (getCurrentLocationInfo() != null && getCurrentLatitude() != 0 && getCurrentLongitude() != 0); } /** * @return the currentLongitude */ - public static double getCurrentLongitude() - { - if (getCurrentLocationInfo() != null) - { + public static double getCurrentLongitude() { + if (getCurrentLocationInfo() != null) { return getCurrentLocationInfo().getLongitude(); - } - else - { + } else { return 0; } } @@ -267,88 +226,77 @@ public static double getCurrentLongitude() /** * @return the latestTimeStamp (for location info) */ - public static long getLatestTimeStamp() - { + public static long getLatestTimeStamp() { return latestTimeStamp; } - + /** * @return the timestamp when measuring was started */ - public static long getStartTimeStamp() - { - return startTimeStamp; + public static long getStartTimeStamp() { + return startTimeStamp; } /** * @param latestTimeStamp the latestTimeStamp (for location info) to set */ - public static void setLatestTimeStamp(long latestTimeStamp) - { + public static void setLatestTimeStamp(long latestTimeStamp) { Session.latestTimeStamp = latestTimeStamp; } /** * @return whether to create a new track segment */ - public static boolean shouldAddNewTrackSegment() - { + public static boolean shouldAddNewTrackSegment() { return addNewTrackSegment; } /** * @param addNewTrackSegment set whether to create a new track segment */ - public static void setAddNewTrackSegment(boolean addNewTrackSegment) - { + public static void setAddNewTrackSegment(boolean addNewTrackSegment) { Session.addNewTrackSegment = addNewTrackSegment; } /** * @param autoSendDelay the autoSendDelay to set */ - public static void setAutoSendDelay(float autoSendDelay) - { + public static void setAutoSendDelay(float autoSendDelay) { Session.autoSendDelay = autoSendDelay; } /** * @return the autoSendDelay to use for the timer */ - public static float getAutoSendDelay() - { + public static float getAutoSendDelay() { return autoSendDelay; } /** * @param currentLocationInfo the latest Location class */ - public static void setCurrentLocationInfo(Location currentLocationInfo) - { + public static void setCurrentLocationInfo(Location currentLocationInfo) { Session.currentLocationInfo = currentLocationInfo; } /** * @return the Location class containing latest lat-long information */ - public static Location getCurrentLocationInfo() - { + public static Location getCurrentLocationInfo() { return currentLocationInfo; } /** * @param isBound set whether the activity is bound to the GpsLoggingService */ - public static void setBoundToService(boolean isBound) - { + public static void setBoundToService(boolean isBound) { Session.isBound = isBound; } /** * @return whether the activity is bound to the GpsLoggingService */ - public static boolean isBoundToService() - { + public static boolean isBoundToService() { return isBound; } @@ -357,8 +305,7 @@ public static boolean isBoundToService() * * @param readyToBeAutoSent */ - public static void setReadyToBeAutoSent(boolean readyToBeAutoSent) - { + public static void setReadyToBeAutoSent(boolean readyToBeAutoSent) { Session.readyToBeAutoSent = readyToBeAutoSent; } @@ -367,28 +314,23 @@ public static void setReadyToBeAutoSent(boolean readyToBeAutoSent) * * @return */ - public static boolean isReadyToBeAutoSent() - { + public static boolean isReadyToBeAutoSent() { return readyToBeAutoSent; } - public static boolean hasDescription() - { - return !(description.length()==0); + public static boolean hasDescription() { + return !(description.length() == 0); } - public static String getDescription() - { + public static String getDescription() { return description; } - public static void clearDescription() - { + public static void clearDescription() { description = ""; } - public static void setDescription(String newDescription) - { + public static void setDescription(String newDescription) { description = newDescription; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/common/Utilities.java b/gpslogger/src/main/java/com/mendhak/gpslogger/common/Utilities.java index 0a42d0795..83f335067 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/common/Utilities.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/common/Utilities.java @@ -45,14 +45,20 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; -public class Utilities -{ +public class Utilities { private static final int LOGLEVEL = 5; private static ProgressDialog pd; @@ -117,8 +123,7 @@ public static void ConfigureLogbackDirectly(Context context) { /** * Gets user preferences, populates the AppSettings class. */ - public static void PopulateAppSettings(Context context) - { + public static void PopulateAppSettings(Context context) { tracer.info("Getting preferences"); SharedPreferences prefs = PreferenceManager @@ -147,31 +152,24 @@ public static void PopulateAppSettings(Context context) String minimumDistanceString = prefs.getString( "distance_before_logging", "0"); - if (minimumDistanceString != null && minimumDistanceString.length() > 0) - { + if (minimumDistanceString != null && minimumDistanceString.length() > 0) { AppSettings.setMinimumDistanceInMeters(Integer .valueOf(minimumDistanceString)); - } - else - { + } else { AppSettings.setMinimumDistanceInMeters(0); } String minimumAccuracyString = prefs.getString( "accuracy_before_logging", "0"); - if (minimumAccuracyString != null && minimumAccuracyString.length() > 0) - { + if (minimumAccuracyString != null && minimumAccuracyString.length() > 0) { AppSettings.setMinimumAccuracyInMeters(Integer .valueOf(minimumAccuracyString)); - } - else - { + } else { AppSettings.setMinimumAccuracyInMeters(0); } - if (AppSettings.shouldUseImperial()) - { + if (AppSettings.shouldUseImperial()) { AppSettings.setMinimumDistanceInMeters(Utilities.FeetToMeters(AppSettings .getMinimumDistanceInMeters())); @@ -183,13 +181,10 @@ public static void PopulateAppSettings(Context context) String minimumSecondsString = prefs.getString("time_before_logging", "60"); - if (minimumSecondsString != null && minimumSecondsString.length() > 0) - { + if (minimumSecondsString != null && minimumSecondsString.length() > 0) { AppSettings .setMinimumSeconds(Integer.valueOf(minimumSecondsString)); - } - else - { + } else { AppSettings.setMinimumSeconds(60); } @@ -199,17 +194,14 @@ public static void PopulateAppSettings(Context context) String retryIntervalString = prefs.getString("retry_time", "60"); - if (retryIntervalString != null && retryIntervalString.length() > 0) - { + if (retryIntervalString != null && retryIntervalString.length() > 0) { AppSettings .setRetryInterval(Integer.valueOf(retryIntervalString)); - } - else - { - AppSettings.setRetryInterval(60); + } else { + AppSettings.setRetryInterval(60); } - /** + /** * New file creation preference: * onceaday, * custom file (static), @@ -218,18 +210,13 @@ public static void PopulateAppSettings(Context context) AppSettings.setNewFileCreation(prefs.getString("new_file_creation", "onceaday")); - if (AppSettings.getNewFileCreation().equals("onceaday")) - { + if (AppSettings.getNewFileCreation().equals("onceaday")) { AppSettings.setNewFileOnceADay(true); AppSettings.setCustomFile(false); - } - else if(AppSettings.getNewFileCreation().equals("custom") || AppSettings.getNewFileCreation().equals("static")) - { + } else if (AppSettings.getNewFileCreation().equals("custom") || AppSettings.getNewFileCreation().equals("static")) { AppSettings.setCustomFile(true); AppSettings.setCustomFileName(prefs.getString("new_file_custom_name", "gpslogger")); - } - else /* new log with each start */ - { + } else /* new log with each start */ { AppSettings.setNewFileOnceADay(false); AppSettings.setCustomFile(false); } @@ -239,8 +226,7 @@ else if(AppSettings.getNewFileCreation().equals("custom") || AppSettings.getNew AppSettings.setAutoEmailEnabled(prefs.getBoolean("autoemail_enabled", false)); - if (Float.valueOf(prefs.getString("autosend_frequency", "0")) >= 8f) - { + if (Float.valueOf(prefs.getString("autosend_frequency", "0")) >= 8f) { SharedPreferences.Editor editor = prefs.edit(); editor.putString("autosend_frequency", "8"); editor.commit(); @@ -266,34 +252,31 @@ else if(AppSettings.getNewFileCreation().equals("custom") || AppSettings.getNew AppSettings.setOpenGTSServerPath(prefs.getString("autoopengts_server_path", "")); AppSettings.setOpenGTSDeviceId(prefs.getString("opengts_device_id", "")); - AppSettings.setAutoFtpEnabled(prefs.getBoolean("autoftp_enabled",false)); - AppSettings.setFtpServerName(prefs.getString("autoftp_server","")); - AppSettings.setFtpUsername(prefs.getString("autoftp_username","")); - AppSettings.setFtpPassword(prefs.getString("autoftp_password","")); + AppSettings.setAutoFtpEnabled(prefs.getBoolean("autoftp_enabled", false)); + AppSettings.setFtpServerName(prefs.getString("autoftp_server", "")); + AppSettings.setFtpUsername(prefs.getString("autoftp_username", "")); + AppSettings.setFtpPassword(prefs.getString("autoftp_password", "")); AppSettings.setFtpDirectory(prefs.getString("autoftp_directory", "GPSLogger")); AppSettings.setFtpPort(Integer.valueOf(prefs.getString("autoftp_port", "21"))); AppSettings.setFtpUseFtps(prefs.getBoolean("autoftp_useftps", false)); - AppSettings.setFtpProtocol(prefs.getString("autoftp_ssltls","")); + AppSettings.setFtpProtocol(prefs.getString("autoftp_ssltls", "")); AppSettings.setFtpImplicit(prefs.getBoolean("autoftp_implicit", false)); AppSettings.setGpsLoggerFolder(prefs.getString("gpslogger_folder", Environment.getExternalStorageDirectory() + "/GPSLogger")); - AppSettings.setFileNamePrefixSerial(prefs.getBoolean("new_file_prefix_serial",false)); + AppSettings.setFileNamePrefixSerial(prefs.getBoolean("new_file_prefix_serial", false)); String absoluteTimeoutString = prefs.getString("absolute_timeout", "0"); if (absoluteTimeoutString != null && absoluteTimeoutString.length() > 0) { AppSettings.setAbsoluteTimeout(Integer.valueOf(absoluteTimeoutString)); - } - else { + } else { AppSettings.setAbsoluteTimeout(0); } } - public static void ShowProgress(Context ctx, String title, String message) - { - if (ctx != null) - { + public static void ShowProgress(Context ctx, String title, String message) { + if (ctx != null) { pd = new ProgressDialog(ctx, ProgressDialog.STYLE_HORIZONTAL); pd.setMax(100); pd.setIndeterminate(true); @@ -302,10 +285,8 @@ public static void ShowProgress(Context ctx, String title, String message) } } - public static void HideProgress() - { - if (pd != null) - { + public static void HideProgress() { + if (pd != null) { pd.dismiss(); } } @@ -318,8 +299,7 @@ public static void HideProgress() * @param className The calling class, such as GpsMainActivity.this or * mainActivity. */ - public static void MsgBox(String title, String message, Context className) - { + public static void MsgBox(String title, String message, Context className) { MsgBox(title, message, className, null); } @@ -330,36 +310,33 @@ public static void MsgBox(String title, String message, Context className) * @param message * @param className The calling class, such as GpsMainActivity.this or * mainActivity. - * @param msgCallback An object which implements IHasACallBack so that the + * @param msgCallback An object which implements IHasACallBack so that the * click event can call the callback method. */ private static void MsgBox(String title, String message, Context className, - final IMessageBoxCallback msgCallback) - { - AlertDialog.Builder alertBuilder = new AlertDialog.Builder(className); - alertBuilder.setTitle(title) - .setMessage(message) - .setCancelable(false) - .setPositiveButton(className.getString(R.string.ok), + final IMessageBoxCallback msgCallback) { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(className); + alertBuilder.setTitle(title) + .setMessage(message) + .setCancelable(false) + .setPositiveButton(className.getString(R.string.ok), new DialogInterface.OnClickListener() { - - public void onClick(final DialogInterface dialog, - final int which) { - - if (msgCallback != null) - { - msgCallback.MessageBoxResult(which); - } + + public void onClick(final DialogInterface dialog, + final int which) { + + if (msgCallback != null) { + msgCallback.MessageBoxResult(which); + } } - } - ); - + } + ); + AlertDialog alertDialog = alertBuilder.create(); - if(className instanceof Activity && !((Activity)className).isFinishing()){ + if (className instanceof Activity && !((Activity) className).isFinishing()) { alertDialog.show(); - } - else { + } else { alertDialog.show(); } @@ -372,8 +349,7 @@ public void onClick(final DialogInterface dialog, * @return */ public static String GetDescriptiveTimeString(int numberOfSeconds, - Context context) - { + Context context) { String descriptive; int hours; @@ -383,43 +359,35 @@ public static String GetDescriptiveTimeString(int numberOfSeconds, int remainingSeconds; // Special cases - if (numberOfSeconds == 1) - { + if (numberOfSeconds == 1) { return context.getString(R.string.time_onesecond); } - if (numberOfSeconds == 30) - { + if (numberOfSeconds == 30) { return context.getString(R.string.time_halfminute); } - if (numberOfSeconds == 60) - { + if (numberOfSeconds == 60) { return context.getString(R.string.time_oneminute); } - if (numberOfSeconds == 900) - { + if (numberOfSeconds == 900) { return context.getString(R.string.time_quarterhour); } - if (numberOfSeconds == 1800) - { + if (numberOfSeconds == 1800) { return context.getString(R.string.time_halfhour); } - if (numberOfSeconds == 3600) - { + if (numberOfSeconds == 3600) { return context.getString(R.string.time_onehour); } - if (numberOfSeconds == 4800) - { + if (numberOfSeconds == 4800) { return context.getString(R.string.time_oneandhalfhours); } - if (numberOfSeconds == 9000) - { + if (numberOfSeconds == 9000) { return context.getString(R.string.time_twoandhalfhours); } @@ -449,78 +417,44 @@ public static String GetDescriptiveTimeString(int numberOfSeconds, * @return */ public static String GetBearingDescription(float bearingDegrees, - Context context) - { + Context context) { String direction; String cardinal; - if (bearingDegrees > 348.75 || bearingDegrees <= 11.25) - { + if (bearingDegrees > 348.75 || bearingDegrees <= 11.25) { cardinal = context.getString(R.string.direction_north); - } - else if (bearingDegrees > 11.25 && bearingDegrees <= 33.75) - { + } else if (bearingDegrees > 11.25 && bearingDegrees <= 33.75) { cardinal = context.getString(R.string.direction_northnortheast); - } - else if (bearingDegrees > 33.75 && bearingDegrees <= 56.25) - { + } else if (bearingDegrees > 33.75 && bearingDegrees <= 56.25) { cardinal = context.getString(R.string.direction_northeast); - } - else if (bearingDegrees > 56.25 && bearingDegrees <= 78.75) - { + } else if (bearingDegrees > 56.25 && bearingDegrees <= 78.75) { cardinal = context.getString(R.string.direction_eastnortheast); - } - else if (bearingDegrees > 78.75 && bearingDegrees <= 101.25) - { + } else if (bearingDegrees > 78.75 && bearingDegrees <= 101.25) { cardinal = context.getString(R.string.direction_east); - } - else if (bearingDegrees > 101.25 && bearingDegrees <= 123.75) - { + } else if (bearingDegrees > 101.25 && bearingDegrees <= 123.75) { cardinal = context.getString(R.string.direction_eastsoutheast); - } - else if (bearingDegrees > 123.75 && bearingDegrees <= 146.26) - { + } else if (bearingDegrees > 123.75 && bearingDegrees <= 146.26) { cardinal = context.getString(R.string.direction_southeast); - } - else if (bearingDegrees > 146.25 && bearingDegrees <= 168.75) - { + } else if (bearingDegrees > 146.25 && bearingDegrees <= 168.75) { cardinal = context.getString(R.string.direction_southsoutheast); - } - else if (bearingDegrees > 168.75 && bearingDegrees <= 191.25) - { + } else if (bearingDegrees > 168.75 && bearingDegrees <= 191.25) { cardinal = context.getString(R.string.direction_south); - } - else if (bearingDegrees > 191.25 && bearingDegrees <= 213.75) - { + } else if (bearingDegrees > 191.25 && bearingDegrees <= 213.75) { cardinal = context.getString(R.string.direction_southsouthwest); - } - else if (bearingDegrees > 213.75 && bearingDegrees <= 236.25) - { + } else if (bearingDegrees > 213.75 && bearingDegrees <= 236.25) { cardinal = context.getString(R.string.direction_southwest); - } - else if (bearingDegrees > 236.25 && bearingDegrees <= 258.75) - { + } else if (bearingDegrees > 236.25 && bearingDegrees <= 258.75) { cardinal = context.getString(R.string.direction_westsouthwest); - } - else if (bearingDegrees > 258.75 && bearingDegrees <= 281.25) - { + } else if (bearingDegrees > 258.75 && bearingDegrees <= 281.25) { cardinal = context.getString(R.string.direction_west); - } - else if (bearingDegrees > 281.25 && bearingDegrees <= 303.75) - { + } else if (bearingDegrees > 281.25 && bearingDegrees <= 303.75) { cardinal = context.getString(R.string.direction_westnorthwest); - } - else if (bearingDegrees > 303.75 && bearingDegrees <= 326.25) - { + } else if (bearingDegrees > 303.75 && bearingDegrees <= 326.25) { cardinal = context.getString(R.string.direction_northwest); - } - else if (bearingDegrees > 326.25 && bearingDegrees <= 348.75) - { + } else if (bearingDegrees > 326.25 && bearingDegrees <= 348.75) { cardinal = context.getString(R.string.direction_northnorthwest); - } - else - { + } else { direction = context.getString(R.string.unknown_direction); return direction; } @@ -537,8 +471,7 @@ else if (bearingDegrees > 326.25 && bearingDegrees <= 348.75) * @param desc * @return */ - public static String CleanDescription(String desc) - { + public static String CleanDescription(String desc) { desc = desc.replace("<", ""); desc = desc.replace(">", ""); desc = desc.replace("&", "&"); @@ -555,33 +488,31 @@ public static String CleanDescription(String desc) * @param dateToFormat The Date object to format. * @return The ISO 8601 formatted string. */ - public static String GetIsoDateTime(Date dateToFormat) - { - /** - * This function is used in gpslogger.loggers.* and for most of them the - * default locale should be fine, but in the case of HttpUrlLogger we - * want machine-readable output, thus Locale.US. - * - * Be wary of the default locale - * http://developer.android.com/reference/java/util/Locale.html#default_locale - */ - + public static String GetIsoDateTime(Date dateToFormat) { + /** + * This function is used in gpslogger.loggers.* and for most of them the + * default locale should be fine, but in the case of HttpUrlLogger we + * want machine-readable output, thus Locale.US. + * + * Be wary of the default locale + * http://developer.android.com/reference/java/util/Locale.html#default_locale + */ + // GPX specs say that time given should be in UTC, no local time. - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", - Locale.US); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", + Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(dateToFormat); } - public static String GetReadableDateTime(Date dateToFormat) - { - /** - * Similar to GetIsoDateTime(), this function is used in - * AutoEmailHelper, and we want machine-readable output. - */ - SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm", - Locale.US); + public static String GetReadableDateTime(Date dateToFormat) { + /** + * Similar to GetIsoDateTime(), this function is used in + * AutoEmailHelper, and we want machine-readable output. + */ + SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm", + Locale.US); return sdf.format(dateToFormat); } @@ -591,8 +522,7 @@ public static String GetReadableDateTime(Date dateToFormat) * @param m * @return */ - public static int MetersToFeet(int m) - { + public static int MetersToFeet(int m) { return (int) Math.round(m * 3.2808399); } @@ -603,8 +533,7 @@ public static int MetersToFeet(int m) * @param f * @return */ - public static int FeetToMeters(int f) - { + public static int FeetToMeters(int f) { return (int) Math.round(f / 3.2808399); } @@ -615,13 +544,11 @@ public static int FeetToMeters(int f) * @param m * @return */ - public static int MetersToFeet(double m) - { + public static int MetersToFeet(double m) { return MetersToFeet((int) m); } - public static boolean IsEmailSetup() - { + public static boolean IsEmailSetup() { return AppSettings.isAutoEmailEnabled() && AppSettings.getAutoEmailTargets().length() > 0 && AppSettings.getSmtpServer().length() > 0 @@ -630,8 +557,7 @@ public static boolean IsEmailSetup() } - public static boolean IsOpenGTSSetup() - { + public static boolean IsOpenGTSSetup() { return AppSettings.isOpenGTSEnabled() && AppSettings.getOpenGTSServer().length() > 0 && AppSettings.getOpenGTSServerPort().length() > 0 @@ -640,8 +566,7 @@ public static boolean IsOpenGTSSetup() } - public static boolean IsFtpSetup() - { + public static boolean IsFtpSetup() { FtpHelper helper = new FtpHelper(null); @@ -664,8 +589,7 @@ public static boolean IsDropBoxSetup(Context context) { * @param longitude2 The second point's longitude * @return The distance between the two points in meters */ - public static double CalculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) - { + public static double CalculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) { /* Haversine formula: A = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2) @@ -696,52 +620,38 @@ public static double CalculateDistance(double latitude1, double longitude1, doub * @param text * @return */ - public static boolean IsNullOrEmpty(String text) - { + public static boolean IsNullOrEmpty(String text) { return text == null || text.length() == 0; } - public static byte[] GetByteArrayFromInputStream(InputStream is) - { + public static byte[] GetByteArrayFromInputStream(InputStream is) { - try - { + try { int length; int size = 1024; byte[] buffer; - if (is instanceof ByteArrayInputStream) - { + if (is instanceof ByteArrayInputStream) { size = is.available(); buffer = new byte[size]; is.read(buffer, 0, size); - } - else - { + } else { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); buffer = new byte[size]; - while ((length = is.read(buffer, 0, size)) != -1) - { + while ((length = is.read(buffer, 0, size)) != -1) { outputStream.write(buffer, 0, length); } buffer = outputStream.toByteArray(); } return buffer; - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); - } - finally - { - try - { + } finally { + try { is.close(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.warn("GetStringFromInputStream - could not close stream"); } } @@ -756,8 +666,7 @@ public static byte[] GetByteArrayFromInputStream(InputStream is) * @param is * @return */ - public static String GetStringFromInputStream(InputStream is) - { + public static String GetStringFromInputStream(InputStream is) { String line; StringBuilder total = new StringBuilder(); @@ -765,25 +674,16 @@ public static String GetStringFromInputStream(InputStream is) BufferedReader rd = new BufferedReader(new InputStreamReader(is)); // Read response until the end - try - { - while ((line = rd.readLine()) != null) - { + try { + while ((line = rd.readLine()) != null) { total.append(line); } - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); - } - finally - { - try - { + } finally { + try { is.close(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.warn("GetStringFromInputStream - could not close stream"); } } @@ -799,19 +699,15 @@ public static String GetStringFromInputStream(InputStream is) * @param stream * @return */ - public static Document GetDocumentFromInputStream(InputStream stream) - { + public static Document GetDocumentFromInputStream(InputStream stream) { Document doc; - try - { + try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); xmlFactory.setNamespaceAware(true); DocumentBuilder builder = xmlFactory.newDocumentBuilder(); doc = builder.parse(stream); - } - catch (Exception e) - { + } catch (Exception e) { doc = null; } @@ -824,36 +720,26 @@ public static Document GetDocumentFromInputStream(InputStream stream) * @param fileName * @return */ - public static String GetMimeTypeFromFileName(String fileName) - { + public static String GetMimeTypeFromFileName(String fileName) { - if (fileName == null || fileName.length() == 0) - { + if (fileName == null || fileName.length() == 0) { return ""; } int pos = fileName.lastIndexOf("."); - if (pos == -1) - { + if (pos == -1) { return "application/octet-stream"; - } - else - { + } else { String extension = fileName.substring(pos + 1, fileName.length()); - if (extension.equalsIgnoreCase("gpx")) - { + if (extension.equalsIgnoreCase("gpx")) { return "application/gpx+xml"; - } - else if (extension.equalsIgnoreCase("kml")) - { + } else if (extension.equalsIgnoreCase("kml")) { return "application/vnd.google-earth.kml+xml"; - } - else if (extension.equalsIgnoreCase("zip")) - { + } else if (extension.equalsIgnoreCase("zip")) { return "application/zip"; } } @@ -864,53 +750,50 @@ else if (extension.equalsIgnoreCase("zip")) } public static float GetBatteryLevel(Context context) { - Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); - if(level == -1 || scale == -1) { + if (level == -1 || scale == -1) { return 50.0f; } - return ((float)level / (float)scale) * 100.0f; + return ((float) level / (float) scale) * 100.0f; } - public static String GetAndroidId(Context context){ - return Settings.Secure.getString(context.getContentResolver(), + public static String GetAndroidId(Context context) { + return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); } public static String HtmlDecode(String text) { - if(IsNullOrEmpty(text)){ + if (IsNullOrEmpty(text)) { return text; } return text.replace("&", "&").replace(""", "\""); } - public static String GetBuildSerial() - { - try{ + public static String GetBuildSerial() { + try { return Build.SERIAL; - } - catch(Throwable t){ + } catch (Throwable t) { return ""; } } - public static File[] GetFilesInFolder(File folder){ + public static File[] GetFilesInFolder(File folder) { return GetFilesInFolder(folder, null); } - public static File[] GetFilesInFolder(File folder, FilenameFilter filter){ + public static File[] GetFilesInFolder(File folder, FilenameFilter filter) { - if( folder == null || !folder.exists() || folder.listFiles() == null){ + if (folder == null || !folder.exists() || folder.listFiles() == null) { return new File[]{}; - } - else{ - if(filter != null){ + } else { + if (filter != null) { return folder.listFiles(filter); } return folder.listFiles(); @@ -918,7 +801,7 @@ public static File[] GetFilesInFolder(File folder, FilenameFilter filter){ } - public static String GetFormattedCustomFileName(String baseName){ + public static String GetFormattedCustomFileName(String baseName) { Time t = new Time(); t.setToNow(); @@ -935,7 +818,4 @@ public static String GetFormattedCustomFileName(String baseName){ } - - - } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/FileLoggerFactory.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/FileLoggerFactory.java index a6e0b80ed..d5c416e0e 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/FileLoggerFactory.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/FileLoggerFactory.java @@ -27,43 +27,35 @@ import java.util.ArrayList; import java.util.List; -public class FileLoggerFactory -{ - public static List GetFileLoggers(Context context) - { +public class FileLoggerFactory { + public static List GetFileLoggers(Context context) { File gpxFolder = new File(AppSettings.getGpsLoggerFolder()); - if (!gpxFolder.exists()) - { + if (!gpxFolder.exists()) { gpxFolder.mkdirs(); } List loggers = new ArrayList(); - if (AppSettings.shouldLogToGpx()) - { + if (AppSettings.shouldLogToGpx()) { File gpxFile = new File(gpxFolder.getPath(), Session.getCurrentFileName() + ".gpx"); - loggers.add(new Gpx10FileLogger(gpxFile, Session.shouldAddNewTrackSegment(), Session.getSatelliteCount())); + loggers.add(new Gpx10FileLogger(gpxFile, Session.shouldAddNewTrackSegment(), Session.getSatelliteCount())); } - if (AppSettings.shouldLogToKml()) - { + if (AppSettings.shouldLogToKml()) { File kmlFile = new File(gpxFolder.getPath(), Session.getCurrentFileName() + ".kml"); loggers.add(new Kml22FileLogger(kmlFile, Session.shouldAddNewTrackSegment())); } - if (AppSettings.shouldLogToPlainText()) - { + if (AppSettings.shouldLogToPlainText()) { File file = new File(gpxFolder.getPath(), Session.getCurrentFileName() + ".txt"); loggers.add(new PlainTextFileLogger(file)); } - if (AppSettings.shouldLogToOpenGTS()) - { + if (AppSettings.shouldLogToOpenGTS()) { loggers.add(new OpenGTSLogger()); } - if(AppSettings.shouldLogToCustomUrl()) - { + if (AppSettings.shouldLogToCustomUrl()) { float batteryLevel = Utilities.GetBatteryLevel(context); String androidId = Utilities.GetAndroidId(context); loggers.add(new HttpUrlLogger(AppSettings.getCustomLoggingUrl(), Session.getSatelliteCount(), batteryLevel, androidId)); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java index f8d0b30d2..7f88ca00a 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Gpx10FileLogger.java @@ -22,15 +22,19 @@ import com.mendhak.gpslogger.common.Utilities; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.RandomAccessFile; import java.util.Date; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -public class Gpx10FileLogger implements IFileLogger -{ +public class Gpx10FileLogger implements IFileLogger { protected final static Object lock = new Object(); private final static ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, @@ -41,19 +45,16 @@ public class Gpx10FileLogger implements IFileLogger protected final String name = "GPX"; private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Gpx10FileLogger.class.getSimpleName()); - Gpx10FileLogger(File gpxFile, boolean addNewTrackSegment, int satelliteCount) - { + Gpx10FileLogger(File gpxFile, boolean addNewTrackSegment, int satelliteCount) { this.gpxFile = gpxFile; this.addNewTrackSegment = addNewTrackSegment; this.satelliteCount = satelliteCount; } - public void Write(Location loc) throws Exception - { + public void Write(Location loc) throws Exception { long time = loc.getTime(); - if(time <= 0) - { + if (time <= 0) { time = System.currentTimeMillis(); } String dateTimeString = Utilities.GetIsoDateTime(new Date(time)); @@ -63,12 +64,10 @@ public void Write(Location loc) throws Exception EXECUTOR.execute(writeHandler); } - public void Annotate(String description, Location loc) throws Exception - { + public void Annotate(String description, Location loc) throws Exception { long time = loc.getTime(); - if(time <= 0) - { + if (time <= 0) { time = System.currentTimeMillis(); } String dateTimeString = Utilities.GetIsoDateTime(new Date(time)); @@ -80,24 +79,21 @@ public void Annotate(String description, Location loc) throws Exception } @Override - public String getName() - { + public String getName() { return name; } } -class Gpx10AnnotateHandler implements Runnable -{ +class Gpx10AnnotateHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Gpx10AnnotateHandler.class.getSimpleName()); String description; File gpxFile; Location loc; String dateTimeString; - public Gpx10AnnotateHandler(String description, File gpxFile, Location loc, String dateTimeString) - { + public Gpx10AnnotateHandler(String description, File gpxFile, Location loc, String dateTimeString) { this.description = description; this.gpxFile = gpxFile; this.loc = loc; @@ -105,18 +101,14 @@ public Gpx10AnnotateHandler(String description, File gpxFile, Location loc, Stri } @Override - public void run() - { + public void run() { - synchronized (Gpx10FileLogger.lock) - { - if (!gpxFile.exists()) - { + synchronized (Gpx10FileLogger.lock) { + if (!gpxFile.exists()) { return; } - if (!gpxFile.exists()) - { + if (!gpxFile.exists()) { return; } @@ -124,8 +116,7 @@ public void run() String wpt = GetWaypointXml(loc, dateTimeString, description); - try - { + try { //Write to a temp file, delete original file, move temp to original File gpxTempFile = new File(gpxFile.getAbsolutePath() + ".tmp"); @@ -136,15 +127,13 @@ public void run() int written = 0; int readSize; byte[] buffer = new byte[startPosition]; - while ((readSize = bis.read(buffer)) > 0) - { + while ((readSize = bis.read(buffer)) > 0) { bos.write(buffer, 0, readSize); written += readSize; System.out.println(written); - if (written == startPosition) - { + if (written == startPosition) { bos.write(wpt.getBytes()); buffer = new byte[20480]; } @@ -158,17 +147,14 @@ public void run() gpxTempFile.renameTo(gpxFile); tracer.debug("Finished annotation to GPX10 File"); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Gpx10FileLogger.Annotate", e); } } } - String GetWaypointXml(Location loc, String dateTimeString, String description) - { + String GetWaypointXml(Location loc, String dateTimeString, String description) { StringBuilder waypoint = new StringBuilder(); @@ -178,8 +164,7 @@ String GetWaypointXml(Location loc, String dateTimeString, String description) .append(String.valueOf(loc.getLongitude())) .append("\">"); - if (loc.hasAltitude()) - { + if (loc.hasAltitude()) { waypoint.append("").append(String.valueOf(loc.getAltitude())).append(""); } @@ -194,8 +179,7 @@ String GetWaypointXml(Location loc, String dateTimeString, String description) } -class Gpx10WriteHandler implements Runnable -{ +class Gpx10WriteHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Gpx10WriteHandler.class.getSimpleName()); String dateTimeString; Location loc; @@ -203,8 +187,7 @@ class Gpx10WriteHandler implements Runnable private boolean addNewTrackSegment; private int satelliteCount; - public Gpx10WriteHandler(String dateTimeString, File gpxFile, Location loc, boolean addNewTrackSegment, int satelliteCount) - { + public Gpx10WriteHandler(String dateTimeString, File gpxFile, Location loc, boolean addNewTrackSegment, int satelliteCount) { this.dateTimeString = dateTimeString; this.addNewTrackSegment = addNewTrackSegment; this.gpxFile = gpxFile; @@ -214,15 +197,11 @@ public Gpx10WriteHandler(String dateTimeString, File gpxFile, Location loc, bool @Override - public void run() - { - synchronized (Gpx10FileLogger.lock) - { - - try - { - if (!gpxFile.exists()) - { + public void run() { + synchronized (Gpx10FileLogger.lock) { + + try { + if (!gpxFile.exists()) { gpxFile.createNewFile(); FileOutputStream initialWriter = new FileOutputStream(gpxFile, true); @@ -254,9 +233,7 @@ public void run() raf.close(); tracer.debug("Finished writing to GPX10 file"); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Gpx10FileLogger.Write", e); } @@ -264,13 +241,11 @@ public void run() } - String GetTrackPointXml(Location loc, String dateTimeString) - { + String GetTrackPointXml(Location loc, String dateTimeString) { StringBuilder track = new StringBuilder(); - if (addNewTrackSegment) - { + if (addNewTrackSegment) { track.append(""); } @@ -280,31 +255,27 @@ String GetTrackPointXml(Location loc, String dateTimeString) .append(String.valueOf(loc.getLongitude())) .append("\">"); - if (loc.hasAltitude()) - { + if (loc.hasAltitude()) { track.append("").append(String.valueOf(loc.getAltitude())).append(""); } track.append(""); - if (loc.hasBearing()) - { + if (loc.hasBearing()) { track.append("").append(String.valueOf(loc.getBearing())).append(""); } - if (loc.hasSpeed()) - { + if (loc.hasSpeed()) { track.append("").append(String.valueOf(loc.getSpeed())).append(""); } track.append("").append(loc.getProvider()).append(""); - if (satelliteCount > 0) - { + if (satelliteCount > 0) { track.append("").append(String.valueOf(satelliteCount)).append(""); } - if(loc.getExtras()!=null){ + if (loc.getExtras() != null) { String hdop = loc.getExtras().getString("HDOP"); String pdop = loc.getExtras().getString("PDOP"); String vdop = loc.getExtras().getString("VDOP"); @@ -312,34 +283,32 @@ String GetTrackPointXml(Location loc, String dateTimeString) String ageofdgpsdata = loc.getExtras().getString("AGEOFDGPSDATA"); String dgpsid = loc.getExtras().getString("DGPSID"); - if(!Utilities.IsNullOrEmpty(hdop)){ + if (!Utilities.IsNullOrEmpty(hdop)) { track.append("").append(hdop).append(""); } - if(!Utilities.IsNullOrEmpty(vdop)){ + if (!Utilities.IsNullOrEmpty(vdop)) { track.append("").append(vdop).append(""); } - if(!Utilities.IsNullOrEmpty(pdop)){ + if (!Utilities.IsNullOrEmpty(pdop)) { track.append("").append(pdop).append(""); } - if(!Utilities.IsNullOrEmpty(geoidheight)){ + if (!Utilities.IsNullOrEmpty(geoidheight)) { track.append("").append(geoidheight).append(""); } - if(!Utilities.IsNullOrEmpty(ageofdgpsdata)){ + if (!Utilities.IsNullOrEmpty(ageofdgpsdata)) { track.append("").append(ageofdgpsdata).append(""); } - if(!Utilities.IsNullOrEmpty(dgpsid)){ + if (!Utilities.IsNullOrEmpty(dgpsid)) { track.append("").append(dgpsid).append(""); } } - - track.append("\n"); track.append(""); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/IFileLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/IFileLogger.java index 7784cb41c..65119abb6 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/IFileLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/IFileLogger.java @@ -19,8 +19,7 @@ import android.location.Location; -public interface IFileLogger -{ +public interface IFileLogger { void Write(Location loc) throws Exception; diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Kml22FileLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Kml22FileLogger.java index 4bf940358..f2fd497bf 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Kml22FileLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/Kml22FileLogger.java @@ -22,14 +22,18 @@ import com.mendhak.gpslogger.common.Utilities; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.RandomAccessFile; import java.util.Date; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -public class Kml22FileLogger implements IFileLogger -{ +public class Kml22FileLogger implements IFileLogger { protected final static Object lock = new Object(); private final static ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(128), new RejectionHandler()); @@ -38,41 +42,35 @@ public class Kml22FileLogger implements IFileLogger protected final String name = "KML"; - public Kml22FileLogger(File kmlFile, boolean addNewTrackSegment) - { + public Kml22FileLogger(File kmlFile, boolean addNewTrackSegment) { this.kmlFile = kmlFile; this.addNewTrackSegment = addNewTrackSegment; } - public void Write(Location loc) throws Exception - { + public void Write(Location loc) throws Exception { Kml22WriteHandler writeHandler = new Kml22WriteHandler(loc, kmlFile, addNewTrackSegment); EXECUTOR.execute(writeHandler); } - public void Annotate(String description, Location loc) throws Exception - { + public void Annotate(String description, Location loc) throws Exception { Kml22AnnotateHandler annotateHandler = new Kml22AnnotateHandler(kmlFile, description, loc); EXECUTOR.execute(annotateHandler); } @Override - public String getName() - { + public String getName() { return name; } } -class Kml22AnnotateHandler implements Runnable -{ +class Kml22AnnotateHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Kml22AnnotateHandler.class.getSimpleName()); File kmlFile; String description; Location loc; - public Kml22AnnotateHandler(File kmlFile, String description, Location loc) - { + public Kml22AnnotateHandler(File kmlFile, String description, Location loc) { this.kmlFile = kmlFile; this.description = description; this.loc = loc; @@ -80,17 +78,13 @@ public Kml22AnnotateHandler(File kmlFile, String description, Location loc) @Override - public void run() - { - if (!kmlFile.exists()) - { + public void run() { + if (!kmlFile.exists()) { return; } - try - { - synchronized (Kml22FileLogger.lock) - { + try { + synchronized (Kml22FileLogger.lock) { String descriptionNode = GetPlacemarkXml(description, loc); @@ -101,10 +95,8 @@ public void run() String currentLine; int lineNumber = 1; - while ((currentLine = bf.readLine()) != null) - { - if (lineNumber > 1) - { + while ((currentLine = bf.readLine()) != null) { + if (lineNumber > 1) { restOfFile.append(currentLine); restOfFile.append("\n"); } @@ -121,9 +113,7 @@ public void run() raf.close(); } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Kml22FileLogger.Annotate", e); } } @@ -144,8 +134,7 @@ String GetPlacemarkXml(String description, Location loc) { } } -class Kml22WriteHandler implements Runnable -{ +class Kml22WriteHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Kml22WriteHandler.class.getSimpleName()); boolean addNewTrackSegment; @@ -153,8 +142,7 @@ class Kml22WriteHandler implements Runnable Location loc; - public Kml22WriteHandler( Location loc, File kmlFile, boolean addNewTrackSegment) - { + public Kml22WriteHandler(Location loc, File kmlFile, boolean addNewTrackSegment) { this.loc = loc; this.kmlFile = kmlFile; @@ -163,10 +151,8 @@ public Kml22WriteHandler( Location loc, File kmlFile, boolean addNewTrackSegment @Override - public void run() - { - try - { + public void run() { + try { RandomAccessFile raf; @@ -174,11 +160,9 @@ public void run() String placemarkHead = "\n\n"; String placemarkTail = "\n\n"; - synchronized (Kml22FileLogger.lock) - { + synchronized (Kml22FileLogger.lock) { - if (!kmlFile.exists()) - { + if (!kmlFile.exists()) { kmlFile.createNewFile(); FileOutputStream initialWriter = new FileOutputStream(kmlFile, true); @@ -203,8 +187,7 @@ public void run() } - if (addNewTrackSegment) - { + if (addNewTrackSegment) { raf = new RandomAccessFile(kmlFile, "rw"); raf.seek(kmlFile.length() - 18); raf.write((placemarkHead + placemarkTail).getBytes()); @@ -231,9 +214,7 @@ public void run() tracer.debug("Finished writing to KML22 File"); } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Kml22FileLogger.Write", e); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/OpenGTSLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/OpenGTSLogger.java index 317d22ebb..bf0da40ba 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/OpenGTSLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/OpenGTSLogger.java @@ -23,24 +23,20 @@ import com.mendhak.gpslogger.common.OpenGTSClient; - /** * Send locations directly to an OpenGTS server
* * @author Francisco Reynoso */ -public class OpenGTSLogger implements IFileLogger -{ +public class OpenGTSLogger implements IFileLogger { protected final String name = "OpenGTS"; - public OpenGTSLogger() - { + public OpenGTSLogger() { } @Override - public void Write(Location loc) throws Exception - { + public void Write(Location loc) throws Exception { String server = AppSettings.getOpenGTSServer(); @@ -48,16 +44,13 @@ public void Write(Location loc) throws Exception String path = AppSettings.getOpenGTSServerPath(); String deviceId = AppSettings.getOpenGTSDeviceId(); - IActionListener al = new IActionListener() - { + IActionListener al = new IActionListener() { @Override - public void OnComplete() - { + public void OnComplete() { } @Override - public void OnFailure() - { + public void OnFailure() { } }; @@ -67,15 +60,13 @@ public void OnFailure() } @Override - public void Annotate(String description, Location loc) throws Exception - { + public void Annotate(String description, Location loc) throws Exception { // TODO Auto-generated method stub } @Override - public String getName() - { + public String getName() { return name; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/PlainTextFileLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/PlainTextFileLogger.java index a51637e2b..42a80ce45 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/PlainTextFileLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/PlainTextFileLogger.java @@ -17,16 +17,15 @@ package com.mendhak.gpslogger.loggers; +import android.location.Location; +import com.mendhak.gpslogger.common.Utilities; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import java.util.Locale; -import android.location.Location; - -import com.mendhak.gpslogger.common.Utilities; - /** * Writes a comma separated plain text file.
@@ -35,22 +34,18 @@ * @author Jeroen van Wilgenburg * https://github.com/jvwilge/gpslogger/commit/a7d45bcc1d5012513ff2246022ce4da2708adf47 */ -public class PlainTextFileLogger implements IFileLogger -{ +public class PlainTextFileLogger implements IFileLogger { private File file; protected final String name = "TXT"; - public PlainTextFileLogger(File file) - { + public PlainTextFileLogger(File file) { this.file = file; } @Override - public void Write(Location loc) throws Exception - { - if (!file.exists()) - { + public void Write(Location loc) throws Exception { + if (!file.exists()) { file.createNewFile(); FileOutputStream writer = new FileOutputStream(file, true); @@ -80,15 +75,13 @@ public void Write(Location loc) throws Exception } @Override - public void Annotate(String description, Location loc) throws Exception - { + public void Annotate(String description, Location loc) throws Exception { // TODO Auto-generated method stub } @Override - public String getName() - { + public String getName() { return name; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/CustomUrlLoggerActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/CustomUrlLoggerActivity.java index fd445f29b..8652ae3d1 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/CustomUrlLoggerActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/CustomUrlLoggerActivity.java @@ -5,7 +5,11 @@ import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; -import android.widget.*; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; import com.mendhak.gpslogger.R; import org.slf4j.LoggerFactory; @@ -17,17 +21,16 @@ public class CustomUrlLoggerActivity extends Activity implements View.OnClickLis private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(CustomUrlLoggerActivity.class.getSimpleName()); - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { tracer.debug("CustomUrlLogger Settings Screen"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_customurl); - EditText urlText = (EditText)findViewById(R.id.customUrlText); - CheckBox urlEnabled = (CheckBox)findViewById(R.id.customUrlEnabled); + EditText urlText = (EditText) findViewById(R.id.customUrlText); + CheckBox urlEnabled = (CheckBox) findViewById(R.id.customUrlEnabled); - Button btnSave = (Button)findViewById(R.id.customurl_btnSave); + Button btnSave = (Button) findViewById(R.id.customurl_btnSave); btnSave.setOnClickListener(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); @@ -37,12 +40,11 @@ public void onCreate(Bundle savedInstanceState) String customUrl = prefs.getString("log_customurl_url", ""); - if(customUrl.length() > 0) - { + if (customUrl.length() > 0) { urlText.setText(customUrl); } - TextView legendView = (TextView)findViewById(R.id.textViewLegend); + TextView legendView = (TextView) findViewById(R.id.textViewLegend); String legend = MessageFormat.format("{0} %LAT\n{1} %LON\n{2} %DESC\n{3} %SAT\n{4} %ALT\n{5} %SPD\n{6} %ACC\n{7} %DIR\n{8} %PROV\n{9} %TIME\n{10} %BATT\n{11} %AID\n{12} %SER", getString(R.string.txt_latitude), getString(R.string.txt_longitude), getString(R.string.txt_annotation), @@ -54,17 +56,15 @@ public void onCreate(Bundle savedInstanceState) } - - @Override public void onClick(View view) { tracer.debug("Saving values"); - EditText urlText = (EditText)findViewById(R.id.customUrlText); - CheckBox urlEnabled = (CheckBox)findViewById(R.id.customUrlEnabled); + EditText urlText = (EditText) findViewById(R.id.customUrlText); + CheckBox urlEnabled = (CheckBox) findViewById(R.id.customUrlEnabled); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - SharedPreferences.Editor editor = prefs.edit(); + SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("log_customurl_enabled", urlEnabled.isChecked()); editor.putString("log_customurl_url", urlText.getText().toString()); editor.commit(); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/HttpUrlLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/HttpUrlLogger.java index d53886a39..4d6d4b080 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/HttpUrlLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/customurl/HttpUrlLogger.java @@ -46,8 +46,7 @@ public class HttpUrlLogger implements IFileLogger { private final float batteryLevel; private final String androidId; - public HttpUrlLogger(String customLoggingUrl, int satellites, float batteryLevel, String androidId) - { + public HttpUrlLogger(String customLoggingUrl, int satellites, float batteryLevel, String androidId) { this.satellites = satellites; this.customLoggingUrl = customLoggingUrl; this.batteryLevel = batteryLevel; @@ -56,7 +55,7 @@ public HttpUrlLogger(String customLoggingUrl, int satellites, float batteryLevel @Override public void Write(Location loc) throws Exception { - if(!Session.hasDescription()){ + if (!Session.hasDescription()) { Annotate("", loc); } @@ -118,7 +117,6 @@ public void run() { logUrl = logUrl.replaceAll("(?i)%ser", String.valueOf(Utilities.GetBuildSerial())); - tracer.debug(logUrl); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/nmea/NmeaFileLogger.java b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/nmea/NmeaFileLogger.java index db71e51ab..3336b3cba 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/nmea/NmeaFileLogger.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/loggers/nmea/NmeaFileLogger.java @@ -19,15 +19,14 @@ public class NmeaFileLogger { private final static ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(128), new RejectionHandler()); - public NmeaFileLogger(String fileName){ + public NmeaFileLogger(String fileName) { this.fileName = fileName; } - public void Write(long timestamp, String nmeaSentence){ + public void Write(long timestamp, String nmeaSentence) { File gpxFolder = new File(AppSettings.getGpsLoggerFolder()); - if (!gpxFolder.exists()) - { + if (!gpxFolder.exists()) { gpxFolder.mkdirs(); } @@ -44,7 +43,7 @@ class NmeaWriteHandler implements Runnable { File gpxFile; String nmeaSentence; - NmeaWriteHandler(File gpxFile, String nmeaSentence){ + NmeaWriteHandler(File gpxFile, String nmeaSentence) { this.gpxFile = gpxFile; this.nmeaSentence = nmeaSentence; } @@ -52,7 +51,7 @@ class NmeaWriteHandler implements Runnable { @Override public void run() { - synchronized (NmeaFileLogger.lock){ + synchronized (NmeaFileLogger.lock) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(gpxFile, true)); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/AlarmReceiver.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/AlarmReceiver.java index 0ae21bfa6..d73d3be56 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/AlarmReceiver.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/AlarmReceiver.java @@ -23,25 +23,20 @@ import org.slf4j.LoggerFactory; -public class AlarmReceiver extends BroadcastReceiver -{ +public class AlarmReceiver extends BroadcastReceiver { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(AlarmReceiver.class.getSimpleName()); @Override - public void onReceive(Context context, Intent intent) - { - try - { + public void onReceive(Context context, Intent intent) { + try { tracer.info("Email alarm received"); Intent serviceIntent = new Intent(context.getPackageName() + ".GpsLoggingService"); serviceIntent.putExtra("emailAlarm", true); // Start the service in case it isn't already running context.startService(serviceIntent); - } - catch (Exception ex) - { - tracer.error("AlarmReceiver.onReceive", ex); + } catch (Exception ex) { + tracer.error("AlarmReceiver.onReceive", ex); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/FileSenderFactory.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/FileSenderFactory.java index c0b264006..00f11c7f4 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/FileSenderFactory.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/FileSenderFactory.java @@ -36,43 +36,35 @@ import java.util.Arrays; import java.util.List; -public class FileSenderFactory -{ +public class FileSenderFactory { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(FileSenderFactory.class.getSimpleName()); - public static IFileSender GetOsmSender(Context applicationContext, IActionListener callback) - { + public static IFileSender GetOsmSender(Context applicationContext, IActionListener callback) { return new OSMHelper(applicationContext, callback); } - public static IFileSender GetDropBoxSender(Context applicationContext, IActionListener callback) - { + public static IFileSender GetDropBoxSender(Context applicationContext, IActionListener callback) { return new DropBoxHelper(applicationContext, callback); } - public static IFileSender GetGDocsSender(Context applicationContext, IActionListener callback) - { + public static IFileSender GetGDocsSender(Context applicationContext, IActionListener callback) { return new GDocsHelper(applicationContext, callback); } - public static IFileSender GetEmailSender(IActionListener callback) - { + public static IFileSender GetEmailSender(IActionListener callback) { return new AutoEmailHelper(callback); } - public static IFileSender GetOpenGTSSender(Context applicationContext, IActionListener callback) - { + public static IFileSender GetOpenGTSSender(Context applicationContext, IActionListener callback) { return new OpenGTSHelper(applicationContext, callback); } - public static IFileSender GetFtpSender(Context applicationContext, IActionListener callback) - { + public static IFileSender GetFtpSender(Context applicationContext, IActionListener callback) { return new FtpHelper(callback); } - public static void SendFiles(Context applicationContext, IActionListener callback) - { + public static void SendFiles(Context applicationContext, IActionListener callback) { final String currentFileName = Session.getCurrentFileName(); @@ -80,34 +72,28 @@ public static void SendFiles(Context applicationContext, IActionListener callbac File gpxFolder = new File(AppSettings.getGpsLoggerFolder()); - if (Utilities.GetFilesInFolder(gpxFolder).length < 1) - { + if (Utilities.GetFilesInFolder(gpxFolder).length < 1) { callback.OnFailure(); return; } - List files = new ArrayList(Arrays.asList(Utilities.GetFilesInFolder(gpxFolder, new FilenameFilter() - { + List files = new ArrayList(Arrays.asList(Utilities.GetFilesInFolder(gpxFolder, new FilenameFilter() { @Override - public boolean accept(File file, String s) - { + public boolean accept(File file, String s) { return s.contains(currentFileName) && !s.contains("zip"); } }))); - if (files.size() == 0) - { + if (files.size() == 0) { callback.OnFailure(); return; } - if (AppSettings.shouldSendZipFile()) - { + if (AppSettings.shouldSendZipFile()) { File zipFile = new File(gpxFolder.getPath(), currentFileName + ".zip"); ArrayList filePaths = new ArrayList(); - for (File f : files) - { + for (File f : files) { filePaths.add(f.getAbsolutePath()); } @@ -121,46 +107,38 @@ public boolean accept(File file, String s) List senders = GetFileSenders(applicationContext, callback); - for (IFileSender sender : senders) - { + for (IFileSender sender : senders) { sender.UploadFile(files); } } - public static List GetFileSenders(Context applicationContext, IActionListener callback) - { + public static List GetFileSenders(Context applicationContext, IActionListener callback) { List senders = new ArrayList(); - if (GDocsHelper.IsLinked(applicationContext)) - { + if (GDocsHelper.IsLinked(applicationContext)) { senders.add(new GDocsHelper(applicationContext, callback)); } - if (OSMHelper.IsOsmAuthorized(applicationContext)) - { + if (OSMHelper.IsOsmAuthorized(applicationContext)) { senders.add(new OSMHelper(applicationContext, callback)); } - if (AppSettings.isAutoEmailEnabled()) - { + if (AppSettings.isAutoEmailEnabled()) { senders.add(new AutoEmailHelper(callback)); } DropBoxHelper dh = new DropBoxHelper(applicationContext, callback); - if (dh.IsLinked()) - { + if (dh.IsLinked()) { senders.add(dh); } - if (AppSettings.isAutoOpenGTSEnabled()) - { + if (AppSettings.isAutoOpenGTSEnabled()) { senders.add(new OpenGTSHelper(applicationContext, callback)); } - if(AppSettings.isAutoFtpEnabled()) - { + if (AppSettings.isAutoFtpEnabled()) { senders.add(new FtpHelper(callback)); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/IFileSender.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/IFileSender.java index 2b0fe9788..0477b7bf5 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/IFileSender.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/IFileSender.java @@ -21,8 +21,7 @@ import java.io.FilenameFilter; import java.util.List; -public interface IFileSender extends FilenameFilter -{ +public interface IFileSender extends FilenameFilter { /// Upload or send this specific file void UploadFile(List files); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ZipHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ZipHelper.java index 80d32a9f8..457720605 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ZipHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ZipHelper.java @@ -24,23 +24,19 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -public class ZipHelper -{ +public class ZipHelper { private static final int BUFFER = 2048; private final String[] files; private final String zipFile; - public ZipHelper(String[] files, String zipFile) - { + public ZipHelper(String[] files, String zipFile) { this.files = files; this.zipFile = zipFile; } - public void Zip() - { - try - { + public void Zip() { + try { BufferedInputStream origin; FileOutputStream dest = new FileOutputStream(zipFile); @@ -48,15 +44,13 @@ public void Zip() byte data[] = new byte[BUFFER]; - for (String f : files) - { + for (String f : files) { FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(f.substring(f.lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) - { + while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } out.closeEntry(); @@ -64,9 +58,7 @@ public void Zip() } out.close(); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxAuthorizationActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxAuthorizationActivity.java index dae75edfe..f9d42977e 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxAuthorizationActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxAuthorizationActivity.java @@ -29,15 +29,13 @@ import com.mendhak.gpslogger.common.Utilities; import org.slf4j.LoggerFactory; -public class DropBoxAuthorizationActivity extends PreferenceActivity -{ +public class DropBoxAuthorizationActivity extends PreferenceActivity { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(DropBoxAuthorizationActivity.class.getSimpleName()); DropBoxHelper helper; @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); @@ -47,37 +45,26 @@ public void onCreate(Bundle savedInstanceState) helper = new DropBoxHelper(getApplicationContext(), null); - if (helper.IsLinked()) - { + if (helper.IsLinked()) { pref.setTitle(R.string.dropbox_unauthorize); pref.setSummary(R.string.dropbox_unauthorize_description); - } - else - { + } else { pref.setTitle(R.string.dropbox_authorize); pref.setSummary(R.string.dropbox_authorize_description); } - pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() - { + pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override - public boolean onPreferenceClick(Preference preference) - { + public boolean onPreferenceClick(Preference preference) { // This logs you out if you're logged in, or vice versa - if (helper.IsLinked()) - { + if (helper.IsLinked()) { helper.UnLink(); startActivity(new Intent(getApplicationContext(), GpsMainActivity.class)); finish(); - } - else - { - try - { + } else { + try { helper.StartAuthentication(DropBoxAuthorizationActivity.this); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("DropBoxAuthorizationActivity.onPreferenceClick", e); } } @@ -104,20 +91,15 @@ public boolean onOptionsItemSelected(MenuItem item) { @Override - protected void onResume() - { + protected void onResume() { super.onResume(); - try - { - if (helper.FinishAuthorization()) - { + try { + if (helper.FinishAuthorization()) { startActivity(new Intent(getApplicationContext(), GpsMainActivity.class)); finish(); } - } - catch (Exception e) - { + } catch (Exception e) { Utilities.MsgBox(getString(R.string.error), getString(R.string.dropbox_couldnotauthorize), DropBoxAuthorizationActivity.this); tracer.error("DropBoxAuthorizationActivity.onResume", e); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxHelper.java index a4c409248..3188f5928 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/dropbox/DropBoxHelper.java @@ -36,8 +36,7 @@ import java.util.List; -public class DropBoxHelper implements IActionListener, IFileSender -{ +public class DropBoxHelper implements IActionListener, IFileSender { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(DropBoxHelper.class.getSimpleName()); final static public String ACCESS_KEY_NAME = "DROPBOX_ACCESS_KEY"; @@ -47,8 +46,7 @@ public class DropBoxHelper implements IActionListener, IFileSender DropboxAPI dropboxApi; IActionListener callback; - public DropBoxHelper(Context context, IActionListener listener) - { + public DropBoxHelper(Context context, IActionListener listener) { ctx = context; AndroidAuthSession session = buildSession(); dropboxApi = new DropboxAPI(session); @@ -60,16 +58,13 @@ public DropBoxHelper(Context context, IActionListener listener) * * @return True/False */ - public boolean IsLinked() - { + public boolean IsLinked() { return dropboxApi.getSession().isLinked(); } - public boolean FinishAuthorization() - { + public boolean FinishAuthorization() { AndroidAuthSession session = dropboxApi.getSession(); - if (!session.isLinked() && session.authenticationSuccessful()) - { + if (!session.isLinked() && session.authenticationSuccessful()) { // Mandatory call to complete the auth session.finishAuthentication(); @@ -91,8 +86,7 @@ public boolean FinishAuthorization() * @param key The Access Key * @param secret The Access Secret */ - private void storeKeys(String key, String secret) - { + private void storeKeys(String key, String secret) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ctx); @@ -102,8 +96,7 @@ private void storeKeys(String key, String secret) edit.commit(); } - private void clearKeys() - { + private void clearKeys() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ctx); SharedPreferences.Editor edit = prefs.edit(); @@ -113,21 +106,17 @@ private void clearKeys() } - private AndroidAuthSession buildSession() - { + private AndroidAuthSession buildSession() { int dropboxAppKey = ctx.getResources().getIdentifier("dropbox_appkey", "string", ctx.getPackageName()); int dropboxAppSecret = ctx.getResources().getIdentifier("dropbox_appsecret", "string", ctx.getPackageName()); AppKeyPair appKeyPair = new AppKeyPair(ctx.getString(dropboxAppKey), ctx.getString(dropboxAppSecret)); AndroidAuthSession session; String[] stored = getKeys(); - if (stored != null) - { + if (stored != null) { AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]); session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken); - } - else - { + } else { session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE); } @@ -141,32 +130,26 @@ private AndroidAuthSession buildSession() * * @return Array of [access_key, access_secret], or null if none stored */ - private String[] getKeys() - { + private String[] getKeys() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String key = prefs.getString(ACCESS_KEY_NAME, null); String secret = prefs.getString(ACCESS_SECRET_NAME, null); - if (key != null && secret != null) - { + if (key != null && secret != null) { String[] ret = new String[2]; ret[0] = key; ret[1] = secret; return ret; - } - else - { + } else { return null; } } - public void StartAuthentication(DropBoxAuthorizationActivity dropBoxAuthorizationActivity) - { + public void StartAuthentication(DropBoxAuthorizationActivity dropBoxAuthorizationActivity) { // Start the remote authentication dropboxApi.getSession().startAuthentication(dropBoxAuthorizationActivity); } - public void UnLink() - { + public void UnLink() { // Remove credentials from the session dropboxApi.getSession().unlink(); @@ -175,8 +158,7 @@ public void UnLink() } @Override - public void UploadFile(List files) - { + public void UploadFile(List files) { //If there's a zip file, upload just that //Else upload everything in files. @@ -184,68 +166,54 @@ public void UploadFile(List files) File zipFile = null; - for (File f : files) - { - if (f.getName().contains(".zip")) - { + for (File f : files) { + if (f.getName().contains(".zip")) { zipFile = f; break; } } - if (zipFile != null) - { + if (zipFile != null) { UploadFile(zipFile.getName()); - } - else - { - for (File f : files) - { + } else { + for (File f : files) { UploadFile(f.getName()); } } } - public void UploadFile(String fileName) - { + public void UploadFile(String fileName) { Thread t = new Thread(new DropBoxUploadHandler(fileName, dropboxApi, this)); t.start(); } - public void OnComplete() - { + public void OnComplete() { callback.OnComplete(); } - public void OnFailure() - { + public void OnFailure() { } @Override - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return true; } - public class DropBoxUploadHandler implements Runnable - { + public class DropBoxUploadHandler implements Runnable { DropboxAPI api; String fileName; IActionListener helper; - public DropBoxUploadHandler(String file, DropboxAPI dbApi, IActionListener dbHelper) - { + public DropBoxUploadHandler(String file, DropboxAPI dbApi, IActionListener dbHelper) { fileName = file; api = dbApi; helper = dbHelper; } - public void run() - { - try - { + public void run() { + try { File gpsDir = new File(AppSettings.getGpsLoggerFolder()); File gpxFile = new File(gpsDir, fileName); @@ -253,9 +221,7 @@ public void run() DropboxAPI.Entry upEntry = api.putFileOverwrite(gpxFile.getName(), fis, gpxFile.length(), null); tracer.info("DropBox uploaded file rev is: " + upEntry.rev); helper.OnComplete(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("DropBoxHelper.UploadFile", e); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailActivity.java index 4991bdc79..bd2d0ef76 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailActivity.java @@ -40,16 +40,14 @@ public class AutoEmailActivity extends PreferenceActivity implements OnPreferenceChangeListener, IMessageBoxCallback, IActionListener, - OnPreferenceClickListener -{ + OnPreferenceClickListener { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(AutoEmailActivity.class.getSimpleName()); private final Handler handler = new Handler(); @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); @@ -88,12 +86,9 @@ public boolean onOptionsItemSelected(MenuItem item) { } + public boolean onPreferenceClick(Preference preference) { - public boolean onPreferenceClick(Preference preference) - { - - if (!IsFormValid()) - { + if (!IsFormValid()) { Utilities.MsgBox(getString(R.string.autoemail_invalid_form), getString(R.string.autoemail_invalid_form_message), AutoEmailActivity.this); @@ -121,8 +116,7 @@ public boolean onPreferenceClick(Preference preference) return true; } - private boolean IsFormValid() - { + private boolean IsFormValid() { CheckBoxPreference chkEnabled = (CheckBoxPreference) findPreference("autoemail_enabled"); EditTextPreference txtSmtpServer = (EditTextPreference) findPreference("smtp_server"); @@ -140,45 +134,34 @@ private boolean IsFormValid() } - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { - if (!IsFormValid()) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (!IsFormValid()) { CheckBoxPreference chkEnabled = (CheckBoxPreference) findPreference("autoemail_enabled"); chkEnabled.setChecked(false); Utilities.MsgBox(getString(R.string.autoemail_invalid_form), getString(R.string.autoemail_invalid_form_message), this); return false; - } - else - { + } else { return super.onKeyDown(keyCode, event); } - } - else - { + } else { return super.onKeyDown(keyCode, event); } } - public void MessageBoxResult(int which) - { + public void MessageBoxResult(int which) { finish(); } - public boolean onPreferenceChange(Preference preference, Object newValue) - { + public boolean onPreferenceChange(Preference preference, Object newValue) { - if (preference.getKey().equals("autoemail_preset")) - { + if (preference.getKey().equals("autoemail_preset")) { int newPreset = Integer.valueOf(newValue.toString()); - switch (newPreset) - { + switch (newPreset) { case 0: // Gmail SetSmtpValues("smtp.gmail.com", "465", true); @@ -201,8 +184,7 @@ public boolean onPreferenceChange(Preference preference, Object newValue) return true; } - private void SetSmtpValues(String server, String port, boolean useSsl) - { + private void SetSmtpValues(String server, String port, boolean useSsl) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); @@ -224,43 +206,35 @@ private void SetSmtpValues(String server, String port, boolean useSsl) } - private final Runnable successfullySent = new Runnable() - { - public void run() - { + private final Runnable successfullySent = new Runnable() { + public void run() { SuccessfulSending(); } }; - private final Runnable failedSend = new Runnable() - { + private final Runnable failedSend = new Runnable() { - public void run() - { + public void run() { FailureSending(); } }; - private void FailureSending() - { + private void FailureSending() { Utilities.HideProgress(); Utilities.MsgBox(getString(R.string.sorry), getString(R.string.error_connection), this); } - private void SuccessfulSending() - { + private void SuccessfulSending() { Utilities.HideProgress(); Utilities.MsgBox(getString(R.string.success), getString(R.string.autoemail_testresult_success), this); } - public void OnComplete() - { + public void OnComplete() { handler.post(successfullySent); } - public void OnFailure() - { + public void OnFailure() { handler.post(failedSend); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailHelper.java index f4f9f8840..a6ff805c8 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/AutoEmailHelper.java @@ -28,30 +28,25 @@ import java.util.Date; import java.util.List; -public class AutoEmailHelper implements IActionListener, IFileSender -{ +public class AutoEmailHelper implements IActionListener, IFileSender { IActionListener callback; private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(AutoEmailHelper.class.getSimpleName()); - public AutoEmailHelper(IActionListener callback) - { + public AutoEmailHelper(IActionListener callback) { this.callback = callback; } @Override - public void UploadFile(List files) - { + public void UploadFile(List files) { ArrayList filesToSend = new ArrayList(); //If a zip file exists, remove others - for (File f : files) - { + for (File f : files) { filesToSend.add(f); - if (f.getName().contains(".zip")) - { + if (f.getName().contains(".zip")) { filesToSend.clear(); filesToSend.add(f); break; @@ -66,8 +61,7 @@ public void UploadFile(List files) void SendTestEmail(String smtpServer, String smtpPort, String smtpUsername, String smtpPassword, boolean smtpUseSsl, - String emailTarget, String fromAddress, IActionListener helper) - { + String emailTarget, String fromAddress, IActionListener helper) { Thread t = new Thread(new TestEmailHandler(helper, smtpServer, smtpPort, smtpUsername, smtpPassword, smtpUseSsl, emailTarget, fromAddress)); @@ -75,44 +69,37 @@ void SendTestEmail(String smtpServer, String smtpPort, } - public void OnComplete() - { + public void OnComplete() { // This was a success tracer.info("Email sent"); callback.OnComplete(); } - public void OnFailure() - { + public void OnFailure() { callback.OnFailure(); } @Override - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return true; } } -class AutoSendHandler implements Runnable -{ +class AutoSendHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(AutoSendHandler.class.getSimpleName()); File[] files; private final IActionListener helper; - public AutoSendHandler(File[] files, IActionListener helper) - { + public AutoSendHandler(File[] files, IActionListener helper) { this.files = files; this.helper = helper; } - public void run() - { - try - { + public void run() { + try { Mail m = new Mail(AppSettings.getSmtpUsername(), AppSettings.getSmtpPassword()); @@ -131,24 +118,18 @@ public void run() m.setSmtpHost(AppSettings.getSmtpServer()); m.setSsl(AppSettings.isSmtpSsl()); - for (File f : files) - { + for (File f : files) { m.addAttachment(f.getName(), f.getAbsolutePath()); } tracer.info("Sending email..."); - if (m.send()) - { + if (m.send()) { helper.OnComplete(); - } - else - { + } else { helper.OnFailure(); } - } - catch (Exception e) - { + } catch (Exception e) { helper.OnFailure(); tracer.error("AutoSendHandler.run", e); } @@ -157,8 +138,7 @@ public void run() } -class TestEmailHandler implements Runnable -{ +class TestEmailHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(TestEmailHandler.class.getSimpleName()); String smtpServer; String smtpPort; @@ -171,8 +151,7 @@ class TestEmailHandler implements Runnable public TestEmailHandler(IActionListener helper, String smtpServer, String smtpPort, String smtpUsername, String smtpPassword, - boolean smtpUseSsl, String csvEmailTargets, String fromAddress) - { + boolean smtpUseSsl, String csvEmailTargets, String fromAddress) { this.smtpServer = smtpServer; this.smtpPort = smtpPort; this.smtpPassword = smtpPassword; @@ -183,22 +162,17 @@ public TestEmailHandler(IActionListener helper, String smtpServer, this.fromAddress = fromAddress; } - public void run() - { - try - { + public void run() { + try { Mail m = new Mail(smtpUsername, smtpPassword); String[] toArr = csvEmailTargets.split(","); m.setTo(toArr); - if (fromAddress != null && fromAddress.length() > 0) - { + if (fromAddress != null && fromAddress.length() > 0) { m.setFrom(fromAddress); - } - else - { + } else { m.setFrom(smtpUsername); } @@ -215,17 +189,12 @@ public void run() m.setDebuggable(true); tracer.info("Sending email..."); - if (m.send()) - { + if (m.send()) { helper.OnComplete(); - } - else - { + } else { helper.OnFailure(); } - } - catch (Exception e) - { + } catch (Exception e) { helper.OnFailure(); tracer.error("AutoSendHandler.run", e); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/Mail.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/Mail.java index 262f0121c..a707ddc37 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/Mail.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/email/Mail.java @@ -22,8 +22,16 @@ * JARs: http://code.google.com/p/javamail-android/downloads/list */ -import javax.activation.*; -import javax.mail.*; +import javax.activation.CommandMap; +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.activation.MailcapCommandMap; +import javax.mail.BodyPart; +import javax.mail.Multipart; +import javax.mail.PasswordAuthentication; +import javax.mail.Session; +import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; @@ -31,8 +39,7 @@ import java.util.Date; import java.util.Properties; -class Mail extends javax.mail.Authenticator -{ +class Mail extends javax.mail.Authenticator { private String _user; private String _pass; @@ -54,8 +61,7 @@ class Mail extends javax.mail.Authenticator private Multipart _multipart; - public Mail() - { + public Mail() { _user = ""; // username _pass = ""; // password _from = ""; // email sent from @@ -79,22 +85,19 @@ public Mail() CommandMap.setDefaultCommandMap(mc); } - Mail(String user, String pass) - { + Mail(String user, String pass) { this(); _user = user; _pass = pass; } - boolean send() throws Exception - { + boolean send() throws Exception { Properties props = _setProperties(); if (!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") - && !_body.equals("")) - { + && !_body.equals("")) { Session session = Session.getInstance(props, this); MimeMessage msg = new MimeMessage(session); @@ -102,8 +105,7 @@ boolean send() throws Exception msg.setFrom(new InternetAddress(_from)); InternetAddress[] addressTo = new InternetAddress[_to.length]; - for (int i = 0; i < _to.length; i++) - { + for (int i = 0; i < _to.length; i++) { addressTo[i] = new InternetAddress(_to[i]); } msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); @@ -123,15 +125,12 @@ boolean send() throws Exception Transport.send(msg); return true; - } - else - { + } else { return false; } } - void addAttachment(String fileName, String filePath) throws Exception - { + void addAttachment(String fileName, String filePath) throws Exception { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); messageBodyPart.setDataHandler(new DataHandler(source)); @@ -141,24 +140,20 @@ void addAttachment(String fileName, String filePath) throws Exception } @Override - public PasswordAuthentication getPasswordAuthentication() - { + public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(_user, _pass); } - private Properties _setProperties() - { + private Properties _setProperties() { Properties props = new Properties(); props.put("mail.smtp.host", _host); - if (_debuggable) - { + if (_debuggable) { props.put("mail.debug", "true"); } - if (_auth) - { + if (_auth) { props.put("mail.smtp.auth", "true"); } @@ -167,8 +162,7 @@ private Properties _setProperties() props.put("mail.smtp.starttls.enable", "true"); - if (_ssl) - { + if (_ssl) { props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } @@ -178,48 +172,39 @@ private Properties _setProperties() return props; } - public void setBody(String _body) - { + public void setBody(String _body) { this._body = _body; } - public void setTo(String[] toArr) - { + public void setTo(String[] toArr) { this._to = toArr; } - public void setFrom(String string) - { + public void setFrom(String string) { this._from = string; } - public void setSubject(String string) - { + public void setSubject(String string) { this._subject = string; } - public void setSsl(boolean ssl) - { + public void setSsl(boolean ssl) { this._ssl = ssl; } - public void setPort(String port) - { + public void setPort(String port) { this._port = port; } - public void setSecurePort(String securePort) - { + public void setSecurePort(String securePort) { this._sport = securePort; } - public void setSmtpHost(String host) - { + public void setSmtpHost(String host) { this._host = host; } - public void setDebuggable(boolean debug) - { + public void setDebuggable(boolean debug) { this._debuggable = debug; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/AutoFtpActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/AutoFtpActivity.java index 521deb75c..59e94c02c 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/AutoFtpActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/AutoFtpActivity.java @@ -33,14 +33,12 @@ import com.mendhak.gpslogger.common.Utilities; import org.slf4j.LoggerFactory; -public class AutoFtpActivity extends PreferenceActivity implements IActionListener, Preference.OnPreferenceClickListener -{ +public class AutoFtpActivity extends PreferenceActivity implements IActionListener, Preference.OnPreferenceClickListener { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(AutoFtpActivity.class.getSimpleName()); private final Handler handler = new Handler(); - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); @@ -66,8 +64,7 @@ public boolean onOptionsItemSelected(MenuItem item) { } - private boolean IsFormValid() - { + private boolean IsFormValid() { CheckBoxPreference chkEnabled = (CheckBoxPreference) findPreference("autoftp_enabled"); EditTextPreference txtServer = (EditTextPreference) findPreference("autoftp_server"); @@ -75,101 +72,83 @@ private boolean IsFormValid() EditTextPreference txtPort = (EditTextPreference) findPreference("autoftp_port"); - return !chkEnabled.isChecked() || txtServer.getText() != null && txtServer.getText().length() > 0 && txtUserName.getText() != null && txtUserName.getText().length() > 0 && txtPort.getText() != null - && txtPort.getText().length() > 0 ; + && txtPort.getText().length() > 0; } - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { - if (!IsFormValid()) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (!IsFormValid()) { CheckBoxPreference chkEnabled = (CheckBoxPreference) findPreference("autoftp_enabled"); chkEnabled.setChecked(false); Utilities.MsgBox(getString(R.string.autoemail_invalid_form), getString(R.string.autoemail_invalid_form_message), this); return false; - } - else - { + } else { return super.onKeyDown(keyCode, event); } - } - else - { + } else { return super.onKeyDown(keyCode, event); } } - private final Runnable successfullySent = new Runnable() - { - public void run() - { + private final Runnable successfullySent = new Runnable() { + public void run() { SuccessfulSending(); } }; - private final Runnable failedSend = new Runnable() - { + private final Runnable failedSend = new Runnable() { - public void run() - { + public void run() { FailureSending(); } }; - private void FailureSending() - { + private void FailureSending() { Utilities.HideProgress(); Utilities.MsgBox(getString(R.string.sorry), "FTP Test Failed", this); } - private void SuccessfulSending() - { + private void SuccessfulSending() { Utilities.HideProgress(); Utilities.MsgBox(getString(R.string.success), "FTP Test Succeeded", this); } @Override - public void OnComplete() - { + public void OnComplete() { Utilities.HideProgress(); handler.post(successfullySent); } @Override - public void OnFailure() - { + public void OnFailure() { Utilities.HideProgress(); handler.post(failedSend); } @Override - public boolean onPreferenceClick(Preference preference) - { + public boolean onPreferenceClick(Preference preference) { FtpHelper helper = new FtpHelper(this); - EditTextPreference servernamePreference = (EditTextPreference)findPreference("autoftp_server"); - EditTextPreference usernamePreference = (EditTextPreference)findPreference("autoftp_username"); - EditTextPreference passwordPreference = (EditTextPreference)findPreference("autoftp_password"); - EditTextPreference portPreference = (EditTextPreference)findPreference("autoftp_port"); - CheckBoxPreference useFtpsPreference = (CheckBoxPreference)findPreference("autoftp_useftps"); - ListPreference sslTlsPreference = (ListPreference)findPreference("autoftp_ssltls"); - CheckBoxPreference implicitPreference = (CheckBoxPreference)findPreference("autoftp_implicit"); - EditTextPreference directoryPreference = (EditTextPreference)findPreference("autoftp_directory"); + EditTextPreference servernamePreference = (EditTextPreference) findPreference("autoftp_server"); + EditTextPreference usernamePreference = (EditTextPreference) findPreference("autoftp_username"); + EditTextPreference passwordPreference = (EditTextPreference) findPreference("autoftp_password"); + EditTextPreference portPreference = (EditTextPreference) findPreference("autoftp_port"); + CheckBoxPreference useFtpsPreference = (CheckBoxPreference) findPreference("autoftp_useftps"); + ListPreference sslTlsPreference = (ListPreference) findPreference("autoftp_ssltls"); + CheckBoxPreference implicitPreference = (CheckBoxPreference) findPreference("autoftp_implicit"); + EditTextPreference directoryPreference = (EditTextPreference) findPreference("autoftp_directory"); - if(!helper.ValidSettings(servernamePreference.getText(), usernamePreference.getText(), passwordPreference.getText(), + if (!helper.ValidSettings(servernamePreference.getText(), usernamePreference.getText(), passwordPreference.getText(), Integer.valueOf(portPreference.getText()), useFtpsPreference.isChecked(), sslTlsPreference.getValue(), - implicitPreference.isChecked())) - { + implicitPreference.isChecked())) { Utilities.MsgBox(getString(R.string.autoftp_invalid_settings), getString(R.string.autoftp_invalid_summary), AutoFtpActivity.this); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/Ftp.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/Ftp.java index c54241008..1adb30963 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/Ftp.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/Ftp.java @@ -29,50 +29,40 @@ import java.io.IOException; import java.io.InputStream; -public class Ftp -{ +public class Ftp { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(Ftp.class.getSimpleName()); public static boolean Upload(String server, String username, String password, String directory, int port, boolean useFtps, String protocol, boolean implicit, - InputStream inputStream, String fileName) - { + InputStream inputStream, String fileName) { FTPClient client = null; - try - { - if (useFtps) - { + try { + if (useFtps) { client = new FTPSClient(protocol, implicit); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(null, null); KeyManager km = kmf.getKeyManagers()[0]; ((FTPSClient) client).setKeyManager(km); - } - else - { + } else { client = new FTPClient(); } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Could not create FTP Client", e); return false; } - try - { + try { tracer.debug("Connecting to FTP"); client.connect(server, port); showServerReply(client); tracer.debug("Logging in to FTP server"); - if (client.login(username, password)) - { + if (client.login(username, password)) { client.enterLocalPassiveMode(); showServerReply(client); @@ -82,8 +72,7 @@ public static boolean Upload(String server, String username, String password, St FTPFile[] existingDirectory = client.listFiles(directory); showServerReply(client); - if(existingDirectory.length <= 0) - { + if (existingDirectory.length <= 0) { tracer.debug("Attempting to create FTP directory " + directory); //client.makeDirectory(directory); ftpCreateDirectoryTree(client, directory); @@ -95,33 +84,23 @@ public static boolean Upload(String server, String username, String password, St boolean result = client.storeFile(fileName, inputStream); inputStream.close(); showServerReply(client); - if (result) - { + if (result) { tracer.debug("Successfully FTPd file " + fileName); - } - else - { + } else { tracer.debug("Failed to FTP file " + fileName); return false; } - } - else - { + } else { tracer.debug("Could not log in to FTP server"); return false; } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Could not connect or upload to FTP server.", e); return false; - } - finally - { - try - { + } finally { + try { tracer.debug("Logging out of FTP server"); client.logout(); showServerReply(client); @@ -129,9 +108,7 @@ public static boolean Upload(String server, String username, String password, St tracer.debug("Disconnecting from FTP server"); client.disconnect(); showServerReply(client); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Could not logout or disconnect", e); return false; } @@ -141,14 +118,14 @@ public static boolean Upload(String server, String username, String password, St } - private static void ftpCreateDirectoryTree( FTPClient client, String dirTree ) throws IOException { + private static void ftpCreateDirectoryTree(FTPClient client, String dirTree) throws IOException { boolean dirExists = true; //tokenize the string and attempt to change into each directory level. If you cannot, then start creating. String[] directories = dirTree.split("/"); - for (String dir : directories ) { - if (dir.length() > 0 ) { + for (String dir : directories) { + if (dir.length() > 0) { if (dirExists) { dirExists = client.changeWorkingDirectory(dir); showServerReply(client); @@ -163,7 +140,7 @@ private static void ftpCreateDirectoryTree( FTPClient client, String dirTree ) t } } - private static void showServerReply(FTPClient client){ + private static void showServerReply(FTPClient client) { String[] replies = client.getReplyStrings(); if (replies != null && replies.length > 0) { for (String aReply : replies) { diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/FtpHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/FtpHelper.java index c7b11255b..f6d6e4b08 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/FtpHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/ftp/FtpHelper.java @@ -31,18 +31,15 @@ import java.util.Date; import java.util.List; -public class FtpHelper implements IFileSender -{ +public class FtpHelper implements IFileSender { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(FtpHelper.class.getSimpleName()); IActionListener callback; - public FtpHelper(IActionListener callback) - { + public FtpHelper(IActionListener callback) { this.callback = callback; } - void TestFtp(String servername, String username, String password, String directory, int port, boolean useFtps, String protocol, boolean implicit) - { + void TestFtp(String servername, String username, String password, String directory, int port, boolean useFtps, String protocol, boolean implicit) { String data = "GPSLogger for Android, test file. Generated at " + (new Date()).toLocaleString() + "\r\n"; ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes()); @@ -52,73 +49,58 @@ void TestFtp(String servername, String username, String password, String directo } @Override - public void UploadFile(List files) - { + public void UploadFile(List files) { if (!ValidSettings(AppSettings.getFtpServerName(), AppSettings.getFtpUsername(), AppSettings.getFtpPassword(), - AppSettings.getFtpPort(), AppSettings.FtpUseFtps(), AppSettings.getFtpProtocol(), AppSettings.FtpImplicit())) - { + AppSettings.getFtpPort(), AppSettings.FtpUseFtps(), AppSettings.getFtpProtocol(), AppSettings.FtpImplicit())) { callback.OnFailure(); } File zipFile = null; //Only upload a zip file if it's present - for (File f : files) - { - if (f.getName().contains(".zip")) - { + for (File f : files) { + if (f.getName().contains(".zip")) { zipFile = f; break; } } - if (zipFile != null) - { + if (zipFile != null) { UploadFile(zipFile); - } - else - { - for (File f : files) - { + } else { + for (File f : files) { UploadFile(f); } } } - public void UploadFile(File f) - { - try - { + public void UploadFile(File f) { + try { FileInputStream fis = new FileInputStream(f); Thread t = new Thread(new FtpUploadHandler(callback, AppSettings.getFtpServerName(), AppSettings.getFtpPort(), AppSettings.getFtpUsername(), AppSettings.getFtpPassword(), AppSettings.getFtpDirectory(), AppSettings.FtpUseFtps(), AppSettings.getFtpProtocol(), AppSettings.FtpImplicit(), fis, f.getName())); t.start(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("Could not prepare file for upload.", e); } } @Override - public boolean accept(File file, String s) - { + public boolean accept(File file, String s) { return true; } public boolean ValidSettings(String servername, String username, String password, Integer port, boolean useFtps, - String sslTls, boolean implicit) - { + String sslTls, boolean implicit) { boolean retVal = servername != null && servername.length() > 0 && port != null && port > 0; - if (useFtps && (sslTls == null || sslTls.length() <= 0)) - { + if (useFtps && (sslTls == null || sslTls.length() <= 0)) { retVal = false; } @@ -126,8 +108,7 @@ public boolean ValidSettings(String servername, String username, String password } } -class FtpUploadHandler implements Runnable -{ +class FtpUploadHandler implements Runnable { IActionListener helper; String server; @@ -143,8 +124,7 @@ class FtpUploadHandler implements Runnable public FtpUploadHandler(IActionListener helper, String server, int port, String username, String password, String directory, boolean useFtps, String protocol, boolean implicit, - InputStream inputStream, String fileName) - { + InputStream inputStream, String fileName) { this.helper = helper; this.server = server; this.port = port; @@ -159,14 +139,10 @@ public FtpUploadHandler(IActionListener helper, String server, int port, String } @Override - public void run() - { - if (Ftp.Upload(server, username, password, directory, port, useFtps, protocol, implicit, inputStream, fileName)) - { + public void run() { + if (Ftp.Upload(server, username, password, directory, port, useFtps, protocol, implicit, inputStream, fileName)) { helper.OnComplete(); - } - else - { + } else { helper.OnFailure(); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsHelper.java index e6a4aeea0..16c6e3aef 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsHelper.java @@ -40,8 +40,7 @@ import java.util.List; -public class GDocsHelper implements IActionListener, IFileSender -{ +public class GDocsHelper implements IActionListener, IFileSender { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(GDocsHelper.class.getSimpleName()); Context ctx; @@ -57,23 +56,20 @@ public class GDocsHelper implements IActionListener, IFileSender ./adb -e shell 'sqlite3 /data/system/accounts.db "delete from grants;"' */ - public GDocsHelper(Context applicationContext, IActionListener callback) - { + public GDocsHelper(Context applicationContext, IActionListener callback) { this.ctx = applicationContext; this.callback = callback; } - public static String GetOauth2Scope() - { + public static String GetOauth2Scope() { return "oauth2:https://www.googleapis.com/auth/drive.file"; } /** * Gets the stored authToken, which may be expired */ - public static String GetAuthToken(Context applicationContext) - { + public static String GetAuthToken(Context applicationContext) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext); return prefs.getString("GDRIVE_AUTH_TOKEN", ""); } @@ -81,14 +77,12 @@ public static String GetAuthToken(Context applicationContext) /** * Gets the stored account name */ - public static String GetAccountName(Context applicationContext) - { + public static String GetAccountName(Context applicationContext) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext); return prefs.getString("GDRIVE_ACCOUNT_NAME", ""); } - public static void SetAccountName(Context applicationContext, String accountName) - { + public static void SetAccountName(Context applicationContext, String accountName) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext); SharedPreferences.Editor editor = prefs.edit(); @@ -99,19 +93,15 @@ public static void SetAccountName(Context applicationContext, String accountName /** * Saves the authToken and account name into shared preferences */ - public static void SaveAuthToken(Context applicationContext, String authToken) - { - try - { + public static void SaveAuthToken(Context applicationContext, String authToken) { + try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext); SharedPreferences.Editor editor = prefs.edit(); tracer.debug("Saving GDocs authToken: " + authToken); editor.putString("GDRIVE_AUTH_TOKEN", authToken); editor.commit(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("GDocsHelper.SaveAuthToken", e); } @@ -121,8 +111,7 @@ public static void SaveAuthToken(Context applicationContext, String authToken) /** * Removes the authToken and account name from storage */ - public static void ClearAuthToken(Context applicationContext) - { + public static void ClearAuthToken(Context applicationContext) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext); SharedPreferences.Editor editor = prefs.edit(); @@ -138,8 +127,7 @@ public static void ClearAuthToken(Context applicationContext) * @param applicationContext * @return */ - public static boolean IsLinked(Context applicationContext) - { + public static boolean IsLinked(Context applicationContext) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext); String gdocsAuthToken = prefs.getString("GDRIVE_AUTH_TOKEN", ""); String gdocsAccount = prefs.getString("GDRIVE_ACCOUNT_NAME", ""); @@ -148,44 +136,34 @@ public static boolean IsLinked(Context applicationContext) @Override - public void UploadFile(List files) - { + public void UploadFile(List files) { File zipFile = null; - for (File f : files) - { - if (f.getName().contains(".zip")) - { + for (File f : files) { + if (f.getName().contains(".zip")) { zipFile = f; break; } } - if (zipFile != null) - { + if (zipFile != null) { UploadFile(zipFile.getName()); - } - else - { - for (File f : files) - { + } else { + for (File f : files) { UploadFile(f.getName()); } } } - public void UploadFile(final String fileName) - { + public void UploadFile(final String fileName) { - if (!IsLinked(ctx)) - { + if (!IsLinked(ctx)) { callback.OnFailure(); return; } - try - { + try { File gpsDir = new File(AppSettings.getGpsLoggerFolder()); File gpxFile = new File(gpsDir, fileName); @@ -196,24 +174,20 @@ public void UploadFile(final String fileName) t.start(); - } - catch (Exception e) - { + } catch (Exception e) { callback.OnFailure(); tracer.error("GDocsHelper.UploadFile", e); } } - private class GDocsUploadHandler implements Runnable - { + private class GDocsUploadHandler implements Runnable { String fileName; InputStream inputStream; IActionListener callback; GDocsUploadHandler(InputStream inputStream, String fileName, - IActionListener callback) - { + IActionListener callback) { this.inputStream = inputStream; this.fileName = fileName; @@ -221,10 +195,8 @@ private class GDocsUploadHandler implements Runnable } @Override - public void run() - { - try - { + public void run() { + try { String token = GoogleAuthUtil.getTokenWithNotification(ctx, GetAccountName(ctx), GetOauth2Scope(), new Bundle()); GDocsHelper.SaveAuthToken(ctx, token); @@ -232,13 +204,11 @@ public void run() String gpsLoggerFolderId = GetFileIdFromFileName(token, "GPSLogger For Android"); - if(Utilities.IsNullOrEmpty(gpsLoggerFolderId)) - { + if (Utilities.IsNullOrEmpty(gpsLoggerFolderId)) { //Couldn't find folder, must create it gpsLoggerFolderId = CreateEmptyFile(token, "GPSLogger For Android", "application/vnd.google-apps.folder", "root"); - if(Utilities.IsNullOrEmpty(gpsLoggerFolderId)) - { + if (Utilities.IsNullOrEmpty(gpsLoggerFolderId)) { callback.OnFailure(); return; } @@ -246,31 +216,26 @@ public void run() //Now search for the file - String gpxFileId = GetFileIdFromFileName(token,fileName); + String gpxFileId = GetFileIdFromFileName(token, fileName); - if(Utilities.IsNullOrEmpty(gpxFileId)) - { + if (Utilities.IsNullOrEmpty(gpxFileId)) { //Create empty file first gpxFileId = CreateEmptyFile(token, fileName, GetMimeTypeFromFileName(fileName), gpsLoggerFolderId); - if(Utilities.IsNullOrEmpty(gpxFileId)) - { + if (Utilities.IsNullOrEmpty(gpxFileId)) { callback.OnFailure(); return; } } - if(!Utilities.IsNullOrEmpty(gpxFileId)) - { + if (!Utilities.IsNullOrEmpty(gpxFileId)) { //Set file's contents UpdateFileContents(token, gpxFileId, Utilities.GetByteArrayFromInputStream(inputStream), fileName); } callback.OnComplete(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("GDocsUploadHandler", e); callback.OnFailure(); } @@ -279,19 +244,16 @@ public void run() } } - private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) - { + private String UpdateFileContents(String authToken, String gpxFileId, byte[] fileContents, String fileName) { HttpURLConnection conn = null; String fileId = null; - String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/"+ gpxFileId + "?uploadType=media"; + String fileUpdateUrl = "https://www.googleapis.com/upload/drive/v2/files/" + gpxFileId + "?uploadType=media"; - try - { + try { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) - { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); @@ -322,15 +284,10 @@ private String UpdateFileContents(String authToken, String gpxFileId, byte[] fil fileId = fileMetadataJson.getString("id"); tracer.debug("File updated : " + fileId); - } - catch (Exception e) - { + } catch (Exception e) { System.out.println(e.getMessage()); - } - finally - { - if (conn != null) - { + } finally { + if (conn != null) { conn.disconnect(); } @@ -340,8 +297,7 @@ private String UpdateFileContents(String authToken, String gpxFileId, byte[] fil } - private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) - { + private String CreateEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) { String fileId = null; HttpURLConnection conn = null; @@ -358,11 +314,9 @@ private String CreateEmptyFile(String authToken, String fileName, String mimeTyp " ]\n" + " }"; - try - { + try { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) - { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); @@ -394,17 +348,12 @@ private String CreateEmptyFile(String authToken, String fileName, String mimeTyp fileId = fileMetadataJson.getString("id"); tracer.debug("File created with ID " + fileId + " of type " + mimeType); - } - catch (Exception e) - { + } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getMessage()); - } - finally - { - if (conn != null) - { + } finally { + if (conn != null) { conn.disconnect(); } @@ -414,21 +363,18 @@ private String CreateEmptyFile(String authToken, String fileName, String mimeTyp } - private String GetFileIdFromFileName(String authToken, String fileName) - { + private String GetFileIdFromFileName(String authToken, String fileName) { HttpURLConnection conn = null; String fileId = ""; - try - { + try { fileName = URLEncoder.encode(fileName, "UTF-8"); String searchUrl = "https://www.googleapis.com/drive/v2/files?q=title%20%3D%20%27" + fileName + "%27%20and%20trashed%20%3D%20false"; - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) - { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { //Due to a pre-froyo bug //http://android-developers.blogspot.com/2011/09/androids-http-clients.html System.setProperty("http.keepAlive", "false"); @@ -445,21 +391,15 @@ private String GetFileIdFromFileName(String authToken, String fileName) JSONObject fileMetadataJson = new JSONObject(fileMetadata); - if(fileMetadataJson.getJSONArray("items") != null && fileMetadataJson.getJSONArray("items").length() > 0) - { + if (fileMetadataJson.getJSONArray("items") != null && fileMetadataJson.getJSONArray("items").length() > 0) { fileId = fileMetadataJson.getJSONArray("items").getJSONObject(0).get("id").toString(); tracer.debug("Found file with ID " + fileId); } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("SearchForGPSLoggerFile", e); - } - finally - { - if (conn != null) - { + } finally { + if (conn != null) { conn.disconnect(); } } @@ -467,24 +407,24 @@ private String GetFileIdFromFileName(String authToken, String fileName) return fileId; } - private String GetMimeTypeFromFileName(String fileName){ - if(fileName.endsWith("kml")){ + private String GetMimeTypeFromFileName(String fileName) { + if (fileName.endsWith("kml")) { return "application/vnd.google-earth.kml+xml"; } - if(fileName.endsWith("gpx")){ + if (fileName.endsWith("gpx")) { return "application/gpx+xml"; } - if(fileName.endsWith("zip")){ + if (fileName.endsWith("zip")) { return "application/zip"; } - if(fileName.endsWith("xml")){ + if (fileName.endsWith("xml")) { return "application/xml"; } - if(fileName.endsWith("nmea")){ + if (fileName.endsWith("nmea")) { return "application/x-nmea"; } @@ -492,23 +432,18 @@ private String GetMimeTypeFromFileName(String fileName){ } - - @Override - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return true; } @Override - public void OnComplete() - { + public void OnComplete() { callback.OnComplete(); } @Override - public void OnFailure() - { + public void OnFailure() { callback.OnFailure(); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsSettingsActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsSettingsActivity.java index a111dc1c0..58944e874 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsSettingsActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/gdocs/GDocsSettingsActivity.java @@ -48,8 +48,7 @@ public class GDocsSettingsActivity extends PreferenceActivity - implements Preference.OnPreferenceClickListener, IActionListener -{ + implements Preference.OnPreferenceClickListener, IActionListener { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(GDocsSettingsActivity.class.getSimpleName()); private final Handler handler = new Handler(); @@ -59,11 +58,10 @@ public class GDocsSettingsActivity extends PreferenceActivity static final int REQUEST_CODE_MISSING_GPSF = 1; static final int REQUEST_CODE_ACCOUNT_PICKER = 2; - static final int REQUEST_CODE_RECOVERED=3; + static final int REQUEST_CODE_RECOVERED = 3; - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); @@ -89,35 +87,27 @@ public boolean onOptionsItemSelected(MenuItem item) { } - private void VerifyGooglePlayServices() - { + private void VerifyGooglePlayServices() { Preference resetPref = findPreference("gdocs_resetauth"); Preference testPref = findPreference("gdocs_test"); int availability = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); - if (availability != ConnectionResult.SUCCESS) - { + if (availability != ConnectionResult.SUCCESS) { resetPref.setEnabled(false); testPref.setEnabled(false); - if (!messageShown) - { + if (!messageShown) { Dialog d = GooglePlayServicesUtil.getErrorDialog(availability, this, REQUEST_CODE_MISSING_GPSF); - if (d != null) - { + if (d != null) { d.show(); - } - else - { + } else { Utilities.MsgBox(getString(R.string.gpsf_missing), getString(R.string.gpsf_missing_description), this); } messageShown = true; } - } - else - { + } else { ResetPreferenceAppearance(resetPref, testPref); testPref.setOnPreferenceClickListener(this); @@ -127,47 +117,35 @@ private void VerifyGooglePlayServices() } - public void onResume() - { + public void onResume() { super.onResume(); VerifyGooglePlayServices(); } - private void ResetPreferenceAppearance(Preference resetPref, Preference testPref) - { - if (GDocsHelper.IsLinked(getApplicationContext())) - { + private void ResetPreferenceAppearance(Preference resetPref, Preference testPref) { + if (GDocsHelper.IsLinked(getApplicationContext())) { resetPref.setTitle(R.string.gdocs_clearauthorization); resetPref.setSummary(R.string.gdocs_clearauthorization_summary); testPref.setEnabled(true); - } - else - { + } else { testPref.setEnabled(false); } } @Override - public boolean onPreferenceClick(Preference preference) - { - if (preference.getKey().equalsIgnoreCase("gdocs_test")) - { + public boolean onPreferenceClick(Preference preference) { + if (preference.getKey().equalsIgnoreCase("gdocs_test")) { UploadTestFileToGoogleDocs(); - } - else - { - if (GDocsHelper.IsLinked(getApplicationContext())) - { + } else { + if (GDocsHelper.IsLinked(getApplicationContext())) { //Clear authorization GoogleAuthUtil.invalidateToken(getApplicationContext(), GDocsHelper.GetAuthToken(getApplicationContext())); GDocsHelper.ClearAuthToken(getApplicationContext()); startActivity(new Intent(getApplicationContext(), GpsMainActivity.class)); finish(); - } - else - { + } else { //Re-authorize Authorize(); @@ -177,8 +155,7 @@ public boolean onPreferenceClick(Preference preference) return true; } - private void Authorize() - { + private void Authorize() { Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false, null, null, null, null); @@ -187,25 +164,21 @@ private void Authorize() @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) - { - switch (requestCode) - { + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { case REQUEST_CODE_ACCOUNT_PICKER: - if (resultCode == RESULT_OK) - { + if (resultCode == RESULT_OK) { String accountName = data.getStringExtra( AccountManager.KEY_ACCOUNT_NAME); - GDocsHelper.SetAccountName(getApplicationContext(),accountName); + GDocsHelper.SetAccountName(getApplicationContext(), accountName); tracer.debug(accountName); getAndUseAuthTokenInAsyncTask(); } break; case REQUEST_CODE_RECOVERED: - if(resultCode == RESULT_OK) - { + if (resultCode == RESULT_OK) { getAndUseAuthTokenInAsyncTask(); } break; @@ -215,44 +188,34 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) } // Example of how to use the GoogleAuthUtil in a blocking, non-main thread context - String getAndUseAuthTokenBlocking() - { - try - { + String getAndUseAuthTokenBlocking() { + try { // Retrieve a token for the given account and scope. It will always return either // a non-empty String or throw an exception. final String token = GoogleAuthUtil.getToken(getApplicationContext(), GDocsHelper.GetAccountName(getApplicationContext()), GDocsHelper.GetOauth2Scope()); return token; - } - catch (GooglePlayServicesAvailabilityException playEx) - { + } catch (GooglePlayServicesAvailabilityException playEx) { Dialog alert = GooglePlayServicesUtil.getErrorDialog( playEx.getConnectionStatusCode(), this, REQUEST_CODE_RECOVERED); alert.show(); - } - catch (UserRecoverableAuthException userAuthEx) - { + } catch (UserRecoverableAuthException userAuthEx) { // Start the user recoverable action using the intent returned by // getIntent() startActivityForResult( userAuthEx.getIntent(), REQUEST_CODE_RECOVERED); - } - catch (IOException transientEx) - { + } catch (IOException transientEx) { // network or server error, the call is expected to succeed if you try again later. // Don't attempt to call again immediately - the request is likely to // fail, you'll hit quotas or back-off. - } - catch (GoogleAuthException authEx) - { + } catch (GoogleAuthException authEx) { // Failure. The call is not expected to ever succeed so it should not be // retried. @@ -261,23 +224,18 @@ String getAndUseAuthTokenBlocking() } - void getAndUseAuthTokenInAsyncTask() - { - AsyncTask task = new AsyncTask() - { + void getAndUseAuthTokenInAsyncTask() { + AsyncTask task = new AsyncTask() { @Override - protected String doInBackground(Void... params) - { - return getAndUseAuthTokenBlocking(); + protected String doInBackground(Void... params) { + return getAndUseAuthTokenBlocking(); } @Override - protected void onPostExecute(String authToken) - { - if(authToken != null) - { - GDocsHelper.SaveAuthToken(getApplicationContext(),authToken); + protected void onPostExecute(String authToken) { + if (authToken != null) { + GDocsHelper.SaveAuthToken(getApplicationContext(), authToken); tracer.debug(authToken); VerifyGooglePlayServices(); } @@ -288,23 +246,19 @@ protected void onPostExecute(String authToken) } - private void UploadTestFileToGoogleDocs() - { + private void UploadTestFileToGoogleDocs() { Utilities.ShowProgress(GDocsSettingsActivity.this, getString(R.string.please_wait), getString(R.string.please_wait)); File gpxFolder = new File(AppSettings.getGpsLoggerFolder()); - if (!gpxFolder.exists()) - { + if (!gpxFolder.exists()) { gpxFolder.mkdirs(); } tracer.debug("Creating gpslogger_test.xml"); File testFile = new File(gpxFolder.getPath(), "gpslogger_test.xml"); - try - { - if(!testFile.exists()) - { + try { + if (!testFile.exists()) { testFile.createNewFile(); FileOutputStream initialWriter = new FileOutputStream(testFile, true); @@ -317,9 +271,7 @@ private void UploadTestFileToGoogleDocs() initialOutput.close(); } - } - catch(Exception ex) - { + } catch (Exception ex) { OnFailure(); } @@ -334,45 +286,37 @@ private void UploadTestFileToGoogleDocs() } @Override - public void OnComplete() - { + public void OnComplete() { Utilities.HideProgress(); handler.post(successUpload); } @Override - public void OnFailure() - { + public void OnFailure() { Utilities.HideProgress(); handler.post(failedUpload); } - private final Runnable failedUpload = new Runnable() - { - public void run() - { + private final Runnable failedUpload = new Runnable() { + public void run() { FailureUploading(); } }; - private final Runnable successUpload = new Runnable() - { - public void run() - { + private final Runnable successUpload = new Runnable() { + public void run() { SuccessUploading(); } }; - private void FailureUploading() - { + private void FailureUploading() { Utilities.MsgBox(getString(R.string.sorry), getString(R.string.gdocs_testupload_error), this); } - private void SuccessUploading() - { + private void SuccessUploading() { Utilities.MsgBox(getString(R.string.success), getString(R.string.gdocs_testupload_success), this); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/GpxReader.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/GpxReader.java index beef8583f..fe4a1c2b0 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/GpxReader.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/GpxReader.java @@ -18,7 +18,11 @@ package com.mendhak.gpslogger.senders.opengts; import android.location.Location; -import org.w3c.dom.*; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -36,13 +40,11 @@ * * @author Droid_Interceptor @ http://stackoverflow.com */ -public class GpxReader -{ +public class GpxReader { private static final SimpleDateFormat gpxDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - public static List getPoints(File gpxFile) throws Exception - { + public static List getPoints(File gpxFile) throws Exception { List points; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -55,8 +57,7 @@ public static List getPoints(File gpxFile) throws Exception points = new ArrayList(); - for (int j = 0; j < items.getLength(); j++) - { + for (int j = 0; j < items.getLength(); j++) { Node item = items.item(j); NamedNodeMap attrs = item.getAttributes(); NodeList props = item.getChildNodes(); @@ -66,40 +67,32 @@ public static List getPoints(File gpxFile) throws Exception pt.setLatitude(Double.parseDouble(attrs.getNamedItem("lat").getNodeValue())); pt.setLongitude(Double.parseDouble(attrs.getNamedItem("lon").getNodeValue())); - for (int k = 0; k < props.getLength(); k++) - { + for (int k = 0; k < props.getLength(); k++) { Node item2 = props.item(k); String name = item2.getNodeName(); - if (name.equalsIgnoreCase("ele")) - { + if (name.equalsIgnoreCase("ele")) { pt.setAltitude(Double.parseDouble(item2.getFirstChild().getNodeValue())); } - if (name.equalsIgnoreCase("course")) - { + if (name.equalsIgnoreCase("course")) { pt.setBearing(Float.parseFloat(item2.getFirstChild().getNodeValue())); } - if (name.equalsIgnoreCase("speed")) - { + if (name.equalsIgnoreCase("speed")) { pt.setSpeed(Float.parseFloat(item2.getFirstChild().getNodeValue())); } - if (name.equalsIgnoreCase("hdop")) - { + if (name.equalsIgnoreCase("hdop")) { pt.setAccuracy(Float.parseFloat(item2.getFirstChild().getNodeValue()) * 5); } - if (name.equalsIgnoreCase("time")) - { + if (name.equalsIgnoreCase("time")) { pt.setTime((getDateFormatter().parse(item2.getFirstChild().getNodeValue())).getTime()); } } - for (int y = 0; y < props.getLength(); y++) - { + for (int y = 0; y < props.getLength(); y++) { Node item3 = props.item(y); String name = item3.getNodeName(); - if (!name.equalsIgnoreCase("ele")) - { + if (!name.equalsIgnoreCase("ele")) { continue; } pt.setAltitude(Double.parseDouble(item3.getFirstChild().getNodeValue())); @@ -114,8 +107,7 @@ public static List getPoints(File gpxFile) throws Exception return points; } - public static SimpleDateFormat getDateFormatter() - { + public static SimpleDateFormat getDateFormatter() { SimpleDateFormat sdf = (SimpleDateFormat) gpxDate.clone(); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSActivity.java index 5f00abfe3..d699729bb 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSActivity.java @@ -36,14 +36,12 @@ public class OpenGTSActivity extends PreferenceActivity implements OnPreferenceChangeListener, - OnPreferenceClickListener -{ + OnPreferenceClickListener { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(OpenGTSActivity.class.getSimpleName()); @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); @@ -80,11 +78,8 @@ public boolean onOptionsItemSelected(MenuItem item) { } - - public boolean onPreferenceClick(Preference preference) - { - if (!IsFormValid()) - { + public boolean onPreferenceClick(Preference preference) { + if (!IsFormValid()) { Utilities.MsgBox(getString(R.string.autoopengts_invalid_form), getString(R.string.autoopengts_invalid_form_message), OpenGTSActivity.this); @@ -93,8 +88,7 @@ public boolean onPreferenceClick(Preference preference) return true; } - private boolean IsFormValid() - { + private boolean IsFormValid() { CheckBoxPreference chkEnabled = (CheckBoxPreference) findPreference("opengts_enabled"); EditTextPreference txtOpenGTSServer = (EditTextPreference) findPreference("opengts_server"); EditTextPreference txtOpenGTSServerPort = (EditTextPreference) findPreference("opengts_server_port"); @@ -111,43 +105,32 @@ private boolean IsFormValid() } - private static boolean isNumeric(String str) - { - for (char c : str.toCharArray()) - { - if (!Character.isDigit(c)) - { + private static boolean isNumeric(String str) { + for (char c : str.toCharArray()) { + if (!Character.isDigit(c)) { return false; } } return true; } - public boolean onKeyDown(int keyCode, KeyEvent event) - { - if (keyCode == KeyEvent.KEYCODE_BACK) - { - if (!IsFormValid()) - { + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (!IsFormValid()) { Utilities.MsgBox(getString(R.string.autoopengts_invalid_form), getString(R.string.autoopengts_invalid_form_message), this); return false; - } - else - { + } else { return super.onKeyDown(keyCode, event); } - } - else - { + } else { return super.onKeyDown(keyCode, event); } } - public boolean onPreferenceChange(Preference preference, Object newValue) - { + public boolean onPreferenceChange(Preference preference, Object newValue) { return true; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSHelper.java index ec30e200d..7080e8f64 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/opengts/OpenGTSHelper.java @@ -29,51 +29,42 @@ import java.util.Collections; import java.util.List; -public class OpenGTSHelper implements IActionListener, IFileSender -{ +public class OpenGTSHelper implements IActionListener, IFileSender { Context applicationContext; private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(OpenGTSHelper.class.getSimpleName()); IActionListener callback; - public OpenGTSHelper(Context applicationContext, IActionListener callback) - { + public OpenGTSHelper(Context applicationContext, IActionListener callback) { this.applicationContext = applicationContext; this.callback = callback; } @Override - public void UploadFile(List files) - { + public void UploadFile(List files) { // Use only gpx - for (File f : files) - { - if (f.getName().endsWith(".gpx")) - { + for (File f : files) { + if (f.getName().endsWith(".gpx")) { Thread t = new Thread(new OpenGTSHandler(applicationContext, f, this)); t.start(); } } } - public void OnComplete() - { + public void OnComplete() { callback.OnComplete(); } - public void OnFailure() - { + public void OnFailure() { callback.OnFailure(); } @Override - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return name.toLowerCase().contains(".gpx"); } } -class OpenGTSHandler implements Runnable -{ +class OpenGTSHandler implements Runnable { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(OpenGTSHandler.class.getSimpleName()); List locations; @@ -81,23 +72,19 @@ class OpenGTSHandler implements Runnable File file; final IActionListener helper; - public OpenGTSHandler(Context applicationContext, File file, IActionListener helper) - { + public OpenGTSHandler(Context applicationContext, File file, IActionListener helper) { this.applicationContext = applicationContext; this.file = file; this.helper = helper; } - public void run() - { - try - { + public void run() { + try { locations = getLocationsFromGPX(file); tracer.info(locations.size() + " points where read from " + file.getName()); - if (locations.size() > 0) - { + if (locations.size() > 0) { String server = AppSettings.getOpenGTSServer(); int port = Integer.parseInt(AppSettings.getOpenGTSServerPort()); @@ -107,30 +94,22 @@ public void run() OpenGTSClient openGTSClient = new OpenGTSClient(server, port, path, helper, applicationContext); openGTSClient.sendHTTP(deviceId, locations.toArray(new Location[0])); - } - else - { + } else { helper.OnFailure(); } - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("OpenGTSHandler.run", e); helper.OnFailure(); } } - private List getLocationsFromGPX(File f) - { + private List getLocationsFromGPX(File f) { List locations = Collections.emptyList(); - try - { + try { locations = GpxReader.getPoints(f); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("OpenGTSHelper.getLocationsFromGPX", e); } return locations; diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMAuthorizationActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMAuthorizationActivity.java index 8be95451b..254bfaf47 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMAuthorizationActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMAuthorizationActivity.java @@ -34,16 +34,14 @@ import oauth.signpost.OAuthProvider; import org.slf4j.LoggerFactory; -public class OSMAuthorizationActivity extends PreferenceActivity -{ +public class OSMAuthorizationActivity extends PreferenceActivity { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(OSMAuthorizationActivity.class.getSimpleName()); private static OAuthProvider provider; private static OAuthConsumer consumer; @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); @@ -53,22 +51,18 @@ public void onCreate(Bundle savedInstanceState) final Uri myURI = intent.getData(); if (myURI != null && myURI.getQuery() != null - && myURI.getQuery().length() > 0) - { + && myURI.getQuery().length() > 0) { //User has returned! Read the verifier info from querystring String oAuthVerifier = myURI.getQueryParameter("oauth_verifier"); - try - { + try { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - if (provider == null) - { + if (provider == null) { provider = OSMHelper.GetOSMAuthProvider(getApplicationContext()); } - if (consumer == null) - { + if (consumer == null) { //In case consumer is null, re-initialize from stored values. consumer = OSMHelper.GetOSMAuthConsumer(getApplicationContext()); } @@ -89,9 +83,7 @@ public void onCreate(Bundle savedInstanceState) startActivity(new Intent(getApplicationContext(), GpsMainActivity.class)); finish(); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("OSMAuthorizationActivity.onCreate - user has returned", e); Utilities.MsgBox(getString(R.string.sorry), getString(R.string.osm_auth_error), this); } @@ -103,16 +95,13 @@ public void onCreate(Bundle savedInstanceState) Preference tagsPref = findPreference("osm_tags"); Preference resetPref = findPreference("osm_resetauth"); - if (!OSMHelper.IsOsmAuthorized(getApplicationContext())) - { + if (!OSMHelper.IsOsmAuthorized(getApplicationContext())) { resetPref.setTitle(R.string.osm_lbl_authorize); resetPref.setSummary(R.string.osm_lbl_authorize_description); visibilityPref.setEnabled(false); descriptionPref.setEnabled(false); tagsPref.setEnabled(false); - } - else - { + } else { visibilityPref.setEnabled(true); descriptionPref.setEnabled(true); tagsPref.setEnabled(true); @@ -120,14 +109,11 @@ public void onCreate(Bundle savedInstanceState) } - resetPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() - { + resetPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) - { + public boolean onPreferenceClick(Preference preference) { - if (OSMHelper.IsOsmAuthorized(getApplicationContext())) - { + if (OSMHelper.IsOsmAuthorized(getApplicationContext())) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.remove("osm_accesstoken"); @@ -138,11 +124,8 @@ public boolean onPreferenceClick(Preference preference) startActivity(new Intent(getApplicationContext(), GpsMainActivity.class)); finish(); - } - else - { - try - { + } else { + try { StrictMode.enableDefaults(); //User clicks. Set the consumer and provider up. @@ -166,9 +149,7 @@ public boolean onPreferenceClick(Preference preference) Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); - } - catch (Exception e) - { + } catch (Exception e) { tracer.error("OSMAuthorizationActivity.onClick", e); Utilities.MsgBox(getString(R.string.sorry), getString(R.string.osm_auth_error), OSMAuthorizationActivity.this); @@ -201,5 +182,4 @@ public boolean onOptionsItemSelected(MenuItem item) { } - } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMHelper.java b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMHelper.java index 19924efc0..dc093a07d 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMHelper.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/senders/osm/OSMHelper.java @@ -42,22 +42,19 @@ import java.io.File; import java.util.List; -public class OSMHelper implements IActionListener, IFileSender -{ +public class OSMHelper implements IActionListener, IFileSender { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(OSMHelper.class.getSimpleName()); IActionListener callback; Context ctx; - public OSMHelper(Context ctx, IActionListener callback) - { + public OSMHelper(Context ctx, IActionListener callback) { this.ctx = ctx; this.callback = callback; } - public static OAuthProvider GetOSMAuthProvider(Context ctx) - { + public static OAuthProvider GetOSMAuthProvider(Context ctx) { return new CommonsHttpOAuthProvider( ctx.getString(R.string.osm_requesttoken_url), ctx.getString(R.string.osm_accesstoken_url), @@ -65,8 +62,7 @@ public static OAuthProvider GetOSMAuthProvider(Context ctx) } - public static boolean IsOsmAuthorized(Context ctx) - { + public static boolean IsOsmAuthorized(Context ctx) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ctx); String oAuthAccessToken = prefs.getString("osm_accesstoken", ""); @@ -74,8 +70,7 @@ public static boolean IsOsmAuthorized(Context ctx) return (oAuthAccessToken != null && oAuthAccessToken.length() > 0); } - public static Intent GetOsmSettingsIntent(Context ctx) - { + public static Intent GetOsmSettingsIntent(Context ctx) { Intent intentOsm; intentOsm = new Intent(ctx.getPackageName() + ".OSM_AUTHORIZE"); @@ -85,13 +80,11 @@ public static Intent GetOsmSettingsIntent(Context ctx) } - public static OAuthConsumer GetOSMAuthConsumer(Context ctx) - { + public static OAuthConsumer GetOSMAuthConsumer(Context ctx) { OAuthConsumer consumer = null; - try - { + try { int osmConsumerKey = ctx.getResources().getIdentifier( "osm_consumerkey", "string", ctx.getPackageName()); int osmConsumerSecret = ctx.getResources().getIdentifier( @@ -108,40 +101,32 @@ public static OAuthConsumer GetOSMAuthConsumer(Context ctx) if (osmAccessToken != null && osmAccessToken.length() > 0 && osmAccessTokenSecret != null - && osmAccessTokenSecret.length() > 0) - { + && osmAccessTokenSecret.length() > 0) { consumer.setTokenWithSecret(osmAccessToken, osmAccessTokenSecret); } - } - catch (Exception e) - { + } catch (Exception e) { //Swallow the exception } return consumer; } - public void OnComplete() - { + public void OnComplete() { callback.OnComplete(); } - public void OnFailure() - { + public void OnFailure() { callback.OnFailure(); } @Override - public void UploadFile(List files) - { + public void UploadFile(List files) { //Upload only GPX - for (File f : files) - { - if (f.getName().contains(".gpx")) - { + for (File f : files) { + if (f.getName().contains(".gpx")) { UploadFile(f.getName()); } @@ -150,8 +135,7 @@ public void UploadFile(List files) } - public void UploadFile(String fileName) - { + public void UploadFile(String fileName) { File gpxFolder = new File(AppSettings.getGpsLoggerFolder()); File chosenFile = new File(gpxFolder, fileName); OAuthConsumer consumer = GetOSMAuthConsumer(ctx); @@ -167,14 +151,12 @@ public void UploadFile(String fileName) } @Override - public boolean accept(File dir, String name) - { + public boolean accept(File dir, String name) { return name.toLowerCase().contains(".gpx"); } - private class OsmUploadHandler implements Runnable - { + private class OsmUploadHandler implements Runnable { OAuthConsumer consumer; String gpsTraceUrl; File chosenFile; @@ -183,8 +165,7 @@ private class OsmUploadHandler implements Runnable String visibility; IActionListener helper; - public OsmUploadHandler(IActionListener helper, OAuthConsumer consumer, String gpsTraceUrl, File chosenFile, String description, String tags, String visibility) - { + public OsmUploadHandler(IActionListener helper, OAuthConsumer consumer, String gpsTraceUrl, File chosenFile, String description, String tags, String visibility) { this.consumer = consumer; this.gpsTraceUrl = gpsTraceUrl; this.chosenFile = chosenFile; @@ -194,10 +175,8 @@ public OsmUploadHandler(IActionListener helper, OAuthConsumer consumer, String g this.helper = helper; } - public void run() - { - try - { + public void run() { + try { HttpPost request = new HttpPost(gpsTraceUrl); consumer.sign(request); @@ -207,8 +186,7 @@ public void run() FileBody gpxBody = new FileBody(chosenFile); entity.addPart("file", gpxBody); - if (description == null || description.length() <= 0) - { + if (description == null || description.length() <= 0) { description = "GPSLogger for Android"; } @@ -224,9 +202,7 @@ public void run() tracer.debug("OSM Upload - " + String.valueOf(statusCode)); helper.OnComplete(); - } - catch (Exception e) - { + } catch (Exception e) { helper.OnFailure(); tracer.error("OsmUploadHelper.run", e); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/settings/LoggingSettingsActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/settings/LoggingSettingsActivity.java index b723138d1..a4229958d 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/settings/LoggingSettingsActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/settings/LoggingSettingsActivity.java @@ -42,12 +42,12 @@ protected void onCreate(Bundle savedInstanceState) { getActionBar().setDisplayHomeAsUpEnabled(true); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - if(prefs.getString("new_file_creation","onceaday").equals("static")) { + if (prefs.getString("new_file_creation", "onceaday").equals("static")) { SharedPreferences.Editor editor = prefs.edit(); editor.putString("new_file_creation", "custom"); editor.commit(); - ListPreference newFileCreation = (ListPreference)findPreference("new_file_creation"); + ListPreference newFileCreation = (ListPreference) findPreference("new_file_creation"); newFileCreation.setValue("custom"); } } @@ -174,14 +174,14 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { return false; } - private void setPreferencesEnabledDisabled(){ + private void setPreferencesEnabledDisabled() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Preference prefFileStaticName = (Preference) findPreference("new_file_custom_name"); Preference prefSerialPrefix = (Preference) findPreference("new_file_prefix_serial"); - prefFileStaticName.setEnabled(prefs.getString("new_file_creation","onceaday").equals("custom")); - prefSerialPrefix.setEnabled(!prefs.getString("new_file_creation","onceaday").equals("custom")); + prefFileStaticName.setEnabled(prefs.getString("new_file_creation", "onceaday").equals("custom")); + prefSerialPrefix.setEnabled(!prefs.getString("new_file_creation", "onceaday").equals("custom")); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/settings/UploadSettingsActivity.java b/gpslogger/src/main/java/com/mendhak/gpslogger/settings/UploadSettingsActivity.java index 1e62a4c37..59293f2a2 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/settings/UploadSettingsActivity.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/settings/UploadSettingsActivity.java @@ -14,7 +14,7 @@ * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. - *

+ *

* See * Android Design: Settings for design guidelines and the Settings @@ -59,7 +59,7 @@ protected void onPostCreate(Bundle savedInstanceState) { @Override public boolean onPreferenceClick(Preference preference) { - if(preference.getKey().equals("osm_setup")){ + if (preference.getKey().equals("osm_setup")) { startActivity(OSMHelper.GetOsmSettingsIntent(getApplicationContext())); return true; } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutCreate.java b/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutCreate.java index 36be40c1a..82f68c265 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutCreate.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutCreate.java @@ -24,10 +24,8 @@ import android.os.Bundle; import com.mendhak.gpslogger.R; -public class ShortcutCreate extends Activity -{ - public void onCreate(Bundle savedInstanceState) - { +public class ShortcutCreate extends Activity { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -36,20 +34,15 @@ public void onCreate(Bundle savedInstanceState) AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.shortcut_pickaction); - builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int item) - { + builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { Intent shortcutIntent; String shortcutLabel; - if (item == 0) - { + if (item == 0) { shortcutIntent = new Intent(getApplicationContext(), ShortcutStart.class); shortcutLabel = getString(R.string.shortcut_start); - } - else - { + } else { shortcutIntent = new Intent(getApplicationContext(), ShortcutStop.class); shortcutLabel = getString(R.string.shortcut_stop); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStart.java b/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStart.java index 29f31d93c..3b1edcff7 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStart.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStart.java @@ -23,12 +23,10 @@ import com.mendhak.gpslogger.GpsLoggingService; import org.slf4j.LoggerFactory; -public class ShortcutStart extends Activity -{ +public class ShortcutStart extends Activity { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(ShortcutStart.class.getSimpleName()); - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tracer.info("Shortcut - start logging"); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStop.java b/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStop.java index b3109a142..0deb996ba 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStop.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/shortcuts/ShortcutStop.java @@ -23,13 +23,11 @@ import com.mendhak.gpslogger.GpsLoggingService; import org.slf4j.LoggerFactory; -public class ShortcutStop extends Activity -{ +public class ShortcutStop extends Activity { private static final org.slf4j.Logger tracer = LoggerFactory.getLogger(ShortcutStop.class.getSimpleName()); - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GenericViewFragment.java b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GenericViewFragment.java index 4cda4bf98..0b45451f8 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GenericViewFragment.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GenericViewFragment.java @@ -14,12 +14,19 @@ public abstract class GenericViewFragment extends Fragment { protected IGpsViewCallback gpsCallback; public abstract void SetLocation(Location locationInfo); + public abstract void SetSatelliteCount(int count); + public abstract void SetLoggingStarted(); + public abstract void SetLoggingStopped(); + public abstract void SetStatusMessage(String message); + public abstract void SetFatalMessage(String message); + public abstract void OnFileNameChange(String newFileName); + public abstract void OnNmeaSentence(long timestamp, String nmeaSentence); protected void requestStartLogging() { @@ -59,8 +66,6 @@ public void onDetach() { } - - /** * Interface used by the different fragments to communicate with the parent activity * which should implement this interface. @@ -68,7 +73,9 @@ public void onDetach() { */ public static interface IGpsViewCallback { public void onRequestStartLogging(); + public void onRequestStopLogging(); + public void onRequestToggleLogging(); } } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsBigViewFragment.java b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsBigViewFragment.java index 8725be552..6083f0385 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsBigViewFragment.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsBigViewFragment.java @@ -35,15 +35,15 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, rootView = inflater.inflate(R.layout.fragment_big_view, container, false); - TextView txtLat = (TextView)rootView.findViewById(R.id.bigview_text_lat); + TextView txtLat = (TextView) rootView.findViewById(R.id.bigview_text_lat); txtLat.setOnTouchListener(this); - TextView txtLong = (TextView)rootView.findViewById(R.id.bigview_text_long); + TextView txtLong = (TextView) rootView.findViewById(R.id.bigview_text_long); txtLong.setOnTouchListener(this); SetLocation(Session.getCurrentLocationInfo()); - if(Session.isStarted()){ + if (Session.isStarted()) { Toast.makeText(getActivity().getApplicationContext(), R.string.bigview_taptotoggle, Toast.LENGTH_SHORT).show(); } @@ -53,22 +53,19 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, @Override public void SetLocation(Location locationInfo) { - TextView txtLat = (TextView)rootView.findViewById(R.id.bigview_text_lat); - TextView txtLong = (TextView)rootView.findViewById(R.id.bigview_text_long); + TextView txtLat = (TextView) rootView.findViewById(R.id.bigview_text_lat); + TextView txtLong = (TextView) rootView.findViewById(R.id.bigview_text_long); - if(locationInfo != null){ + if (locationInfo != null) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(6); txtLat.setText(String.valueOf(nf.format(locationInfo.getLatitude()))); txtLong.setText(String.valueOf(nf.format(locationInfo.getLongitude()))); - } - else if (Session.isStarted()) - { + } else if (Session.isStarted()) { txtLat.setText("..."); - } - else { + } else { txtLat.setText(R.string.bigview_taptotoggle); } } @@ -80,8 +77,8 @@ public void SetSatelliteCount(int count) { @Override public void SetLoggingStarted() { - TextView txtLat = (TextView)rootView.findViewById(R.id.bigview_text_lat); - TextView txtLong = (TextView)rootView.findViewById(R.id.bigview_text_long); + TextView txtLat = (TextView) rootView.findViewById(R.id.bigview_text_lat); + TextView txtLong = (TextView) rootView.findViewById(R.id.bigview_text_long); txtLat.setText(""); txtLong.setText(""); } @@ -114,8 +111,7 @@ public void OnNmeaSentence(long timestamp, String nmeaSentence) { @Override public boolean onTouch(View view, MotionEvent motionEvent) { - if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) - { + if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { tracer.debug("Big frame - onTouch event"); requestToggleLogging(); return true; diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsDetailedViewFragment.java b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsDetailedViewFragment.java index b3fafab40..9467f621b 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsDetailedViewFragment.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsDetailedViewFragment.java @@ -35,7 +35,7 @@ public static final GpsDetailedViewFragment newInstance() { GpsDetailedViewFragment fragment = new GpsDetailedViewFragment(); Bundle bundle = new Bundle(1); - bundle.putInt("a_number",1); + bundle.putInt("a_number", 1); fragment.setArguments(bundle); return fragment; @@ -93,8 +93,7 @@ public void onResume() { @Override public void SetLocation(Location locationInfo) { - if (locationInfo == null) - { + if (locationInfo == null) { return; } @@ -114,12 +113,9 @@ public void SetLocation(Location locationInfo) { TextView txtTravelled = (TextView) rootView.findViewById(R.id.detailedview_travelled_text); TextView txtTime = (TextView) rootView.findViewById(R.id.detailedview_duration_text); String providerName = locationInfo.getProvider(); - if (providerName.equalsIgnoreCase("gps")) - { + if (providerName.equalsIgnoreCase("gps")) { providerName = getString(R.string.providername_gps); - } - else - { + } else { providerName = getString(R.string.providername_celltower); } @@ -135,69 +131,50 @@ public void SetLocation(Location locationInfo) { nf.setMaximumFractionDigits(3); - if (locationInfo.hasAltitude()) - { + if (locationInfo.hasAltitude()) { double altitude = locationInfo.getAltitude(); - if (AppSettings.shouldUseImperial()) - { - tvAltitude.setText( nf.format(Utilities.MetersToFeet(altitude)) + if (AppSettings.shouldUseImperial()) { + tvAltitude.setText(nf.format(Utilities.MetersToFeet(altitude)) + getString(R.string.feet)); - } - else - { + } else { tvAltitude.setText(nf.format(altitude) + getString(R.string.meters)); } - } - else - { + } else { tvAltitude.setText(R.string.not_applicable); } - if (locationInfo.hasSpeed()) - { + if (locationInfo.hasSpeed()) { float speed = locationInfo.getSpeed(); String unit; - if (AppSettings.shouldUseImperial()) - { - if (speed > 1.47) - { + if (AppSettings.shouldUseImperial()) { + if (speed > 1.47) { speed = speed * 0.6818f; unit = getString(R.string.miles_per_hour); - } - else - { + } else { speed = Utilities.MetersToFeet(speed); unit = getString(R.string.feet_per_second); } - } - else - { - if (speed > 0.277) - { + } else { + if (speed > 0.277) { speed = speed * 3.6f; unit = getString(R.string.kilometers_per_hour); - } - else - { + } else { unit = getString(R.string.meters_per_second); } } txtSpeed.setText(String.valueOf(nf.format(speed)) + unit); - } - else - { + } else { txtSpeed.setText(R.string.not_applicable); } - if (locationInfo.hasBearing()) - { + if (locationInfo.hasBearing()) { float bearingDegrees = locationInfo.getBearing(); String direction; @@ -206,59 +183,45 @@ public void SetLocation(Location locationInfo) { txtDirection.setText(direction + "(" + String.valueOf(Math.round(bearingDegrees)) + getString(R.string.degree_symbol) + ")"); - } - else - { + } else { txtDirection.setText(R.string.not_applicable); } - if (!Session.isUsingGps()) - { + if (!Session.isUsingGps()) { txtSatellites.setText(R.string.not_applicable); } - if (locationInfo.hasAccuracy()) - { + if (locationInfo.hasAccuracy()) { float accuracy = locationInfo.getAccuracy(); - if (AppSettings.shouldUseImperial()) - { + if (AppSettings.shouldUseImperial()) { txtAccuracy.setText(getString(R.string.accuracy_within, nf.format(Utilities.MetersToFeet(accuracy)), getString(R.string.feet))); - } - else - { + } else { txtAccuracy.setText(getString(R.string.accuracy_within, nf.format(accuracy), getString(R.string.meters))); } - } - else - { + } else { txtAccuracy.setText(R.string.not_applicable); } String distanceUnit; double distanceValue = Session.getTotalTravelled(); - if (AppSettings.shouldUseImperial()) - { + if (AppSettings.shouldUseImperial()) { distanceUnit = getString(R.string.feet); distanceValue = Utilities.MetersToFeet(distanceValue); // When it passes more than 1 kilometer, convert to miles. - if (distanceValue > 3281) - { + if (distanceValue > 3281) { distanceUnit = getString(R.string.miles); distanceValue = distanceValue / 5280; } - } - else - { + } else { distanceUnit = getString(R.string.meters); - if (distanceValue > 1000) - { + if (distanceValue > 1000) { distanceUnit = getString(R.string.kilometers); distanceValue = distanceValue / 1000; } @@ -274,27 +237,24 @@ public void SetLocation(Location locationInfo) { DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext()); - txtTime.setText(duration+" (started at "+dateFormat.format(d)+" "+timeFormat.format(d)+")"); + txtTime.setText(duration + " (started at " + dateFormat.format(d) + " " + timeFormat.format(d) + ")"); } - private String getInterval(long startTime, long endTime) - { + private String getInterval(long startTime, long endTime) { StringBuffer sb = new StringBuffer(); long diff = endTime - startTime; long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); - if (diffDays > 0) - { + if (diffDays > 0) { sb.append(diffDays + " days "); } - if (diffHours > 0) - { - sb.append(String.format("%02d", diffHours)+":"); + if (diffHours > 0) { + sb.append(String.format("%02d", diffHours) + ":"); } - sb.append(String.format("%02d", diffMinutes)+":"); + sb.append(String.format("%02d", diffMinutes) + ":"); sb.append(String.format("%02d", diffSeconds)); return sb.toString(); } @@ -304,11 +264,9 @@ private String getInterval(long startTime, long endTime) * Displays a human readable summary of the preferences chosen by the user * on the main form */ - private void showPreferencesSummary() - { + private void showPreferencesSummary() { tracer.debug("GpsDetailedViewFragment.showPreferencesSummary"); - try - { + try { TextView txtLoggingTo = (TextView) rootView.findViewById(R.id.detailedview_loggingto_text); TextView txtFrequency = (TextView) rootView.findViewById(R.id.detailedview_frequency_text); TextView txtDistance = (TextView) rootView.findViewById(R.id.detailedview_distance_text); @@ -316,76 +274,59 @@ private void showPreferencesSummary() List loggers = FileLoggerFactory.GetFileLoggers(getActivity().getApplicationContext()); - if (loggers.size() > 0) - { + if (loggers.size() > 0) { ListIterator li = loggers.listIterator(); String logTo = li.next().getName(); - while (li.hasNext()) - { + while (li.hasNext()) { logTo += ", " + li.next().getName(); } - if(AppSettings.shouldLogToNmea()){ + if (AppSettings.shouldLogToNmea()) { logTo += ", NMEA"; } txtLoggingTo.setText(logTo); - } - else - { + } else { txtLoggingTo.setText(R.string.summary_loggingto_screen); } - if (AppSettings.getMinimumSeconds() > 0) - { + if (AppSettings.getMinimumSeconds() > 0) { String descriptiveTime = Utilities.GetDescriptiveTimeString(AppSettings.getMinimumSeconds(), getActivity().getApplicationContext()); txtFrequency.setText(descriptiveTime); - } - else - { + } else { txtFrequency.setText(R.string.summary_freq_max); } - if (AppSettings.getMinimumDistanceInMeters() > 0) - { - if (AppSettings.shouldUseImperial()) - { + if (AppSettings.getMinimumDistanceInMeters() > 0) { + if (AppSettings.shouldUseImperial()) { int minimumDistanceInFeet = Utilities.MetersToFeet(AppSettings.getMinimumDistanceInMeters()); txtDistance.setText(((minimumDistanceInFeet == 1) ? getString(R.string.foot) : String.valueOf(minimumDistanceInFeet) + getString(R.string.feet))); - } - else - { + } else { txtDistance.setText(((AppSettings.getMinimumDistanceInMeters() == 1) ? getString(R.string.meter) : String.valueOf(AppSettings.getMinimumDistanceInMeters()) + getString(R.string.meters))); } - } - else - { + } else { txtDistance.setText(R.string.summary_dist_regardless); } - if (AppSettings.isAutoSendEnabled()) - { + if (AppSettings.isAutoSendEnabled()) { String autoEmailResx; - if (AppSettings.getAutoSendDelay() == 0) - { + if (AppSettings.getAutoSendDelay() == 0) { autoEmailResx = "autoemail_frequency_whenistop"; - } - else - { + } else { autoEmailResx = "autoemail_frequency_" + String.valueOf(AppSettings.getAutoSendDelay()).replace(".", ""); @@ -401,53 +342,48 @@ private void showPreferencesSummary() StringBuilder sb = new StringBuilder(); - if(Utilities.IsEmailSetup()){ + if (Utilities.IsEmailSetup()) { sb.append("Email\n"); } - if(Utilities.IsFtpSetup()){ + if (Utilities.IsFtpSetup()) { sb.append("FTP\n"); } - if(GDocsHelper.IsLinked(getActivity().getApplicationContext())){ + if (GDocsHelper.IsLinked(getActivity().getApplicationContext())) { sb.append("Google Docs\n"); } - if(OSMHelper.IsOsmAuthorized(getActivity().getApplicationContext())){ + if (OSMHelper.IsOsmAuthorized(getActivity().getApplicationContext())) { sb.append("OpenStreetMap\n"); } - if(Utilities.IsDropBoxSetup(getActivity().getApplicationContext())){ + if (Utilities.IsDropBoxSetup(getActivity().getApplicationContext())) { sb.append("Dropbox\n"); } - if(Utilities.IsOpenGTSSetup()){ + if (Utilities.IsOpenGTSSetup()) { sb.append("OpenGTS\n"); } - TextView txtTargets = (TextView)rootView.findViewById(R.id.detailedview_autosendtargets_text); + TextView txtTargets = (TextView) rootView.findViewById(R.id.detailedview_autosendtargets_text); txtTargets.setText(sb.toString()); - - } - catch (Exception ex) - { + } catch (Exception ex) { tracer.error("showPreferencesSummary", ex); } } - public void showCurrentFileName(String newFileName) - { - if (newFileName == null || newFileName.length() <= 0) - { + public void showCurrentFileName(String newFileName) { + if (newFileName == null || newFileName.length() <= 0) { return; } TextView txtFilename = (TextView) rootView.findViewById(R.id.detailedview_file_text); - txtFilename.setText(Session.getCurrentFileName() + "\n (" + AppSettings.getGpsLoggerFolder() + ")" ); + txtFilename.setText(Session.getCurrentFileName() + "\n (" + AppSettings.getGpsLoggerFolder() + ")"); } @@ -503,7 +439,7 @@ public void SetLoggingStopped() { @Override public void SetStatusMessage(String message) { - TextView txtStatus = (TextView)rootView.findViewById(R.id.detailedview_txtstatus); + TextView txtStatus = (TextView) rootView.findViewById(R.id.detailedview_txtstatus); txtStatus.setText(message); showPreferencesSummary(); @@ -511,7 +447,7 @@ public void SetStatusMessage(String message) { @Override public void SetFatalMessage(String message) { - TextView txtStatus = (TextView)rootView.findViewById(R.id.detailedview_txtstatus); + TextView txtStatus = (TextView) rootView.findViewById(R.id.detailedview_txtstatus); txtStatus.setText(message); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsSimpleViewFragment.java b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsSimpleViewFragment.java index 4b51b22f2..951105d6c 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsSimpleViewFragment.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/views/GpsSimpleViewFragment.java @@ -17,14 +17,10 @@ import com.mendhak.gpslogger.common.AppSettings; import com.mendhak.gpslogger.common.Session; import com.mendhak.gpslogger.common.Utilities; -import com.mendhak.gpslogger.loggers.FileLoggerFactory; -import com.mendhak.gpslogger.loggers.IFileLogger; import com.mendhak.gpslogger.views.component.ToggleComponent; import org.slf4j.LoggerFactory; import java.text.NumberFormat; -import java.util.List; -import java.util.ListIterator; public class GpsSimpleViewFragment extends GenericViewFragment implements View.OnClickListener { @@ -118,35 +114,31 @@ private void showPreferencesSummary() { if (AppSettings.shouldLogToKml()) { imgKml.setVisibility(View.VISIBLE); - } - else{ + } else { imgKml.setVisibility(View.GONE); } - if(AppSettings.shouldLogToNmea()){ + if (AppSettings.shouldLogToNmea()) { imgNmea.setVisibility(View.VISIBLE); - } - else{ + } else { imgNmea.setVisibility(View.GONE); } if (AppSettings.shouldLogToPlainText()) { imgCsv.setVisibility(View.VISIBLE); - } - else{ + } else { imgCsv.setVisibility(View.GONE); } if (AppSettings.shouldLogToCustomUrl()) { imgLink.setVisibility(View.VISIBLE); - } - else{ + } else { imgLink.setVisibility(View.GONE); } - if(!AppSettings.shouldLogToGpx() && !AppSettings.shouldLogToKml() - && !AppSettings.shouldLogToPlainText()){ + if (!AppSettings.shouldLogToGpx() && !AppSettings.shouldLogToKml() + && !AppSettings.shouldLogToPlainText()) { showCurrentFileName(null); } @@ -161,7 +153,7 @@ private void showCurrentFileName(String newFileName) { } txtFilename.setVisibility(View.VISIBLE); - txtFilename.setText(Html.fromHtml("" + AppSettings.getGpsLoggerFolder() + "/" + Session.getCurrentFileName() + "" )); + txtFilename.setText(Html.fromHtml("" + AppSettings.getGpsLoggerFolder() + "/" + Session.getCurrentFileName() + "")); } @@ -190,7 +182,7 @@ private void setImageTooltips() { ImageView imgPoints = (ImageView) rootView.findViewById(R.id.simpleview_points); imgPoints.setOnClickListener(this); - ImageView imgLink = (ImageView)rootView.findViewById(R.id.simpleview_imgLink); + ImageView imgLink = (ImageView) rootView.findViewById(R.id.simpleview_imgLink); imgLink.setOnClickListener(this); } @@ -503,7 +495,7 @@ public void onClick(View view) { toast.show(); } - private Toast getToast(String message){ + private Toast getToast(String message) { return Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT); } diff --git a/gpslogger/src/main/java/com/mendhak/gpslogger/views/component/ToggleComponent.java b/gpslogger/src/main/java/com/mendhak/gpslogger/views/component/ToggleComponent.java index acb111d0b..32d617609 100644 --- a/gpslogger/src/main/java/com/mendhak/gpslogger/views/component/ToggleComponent.java +++ b/gpslogger/src/main/java/com/mendhak/gpslogger/views/component/ToggleComponent.java @@ -13,10 +13,10 @@ public class ToggleComponent { private ToggleHandler handler; private boolean enabled; - ToggleComponent() {} + ToggleComponent() { + } - public void SetEnabled(boolean enabled) - { + public void SetEnabled(boolean enabled) { if (enabled) { on.setVisibility(View.VISIBLE); @@ -27,7 +27,7 @@ public void SetEnabled(boolean enabled) } } - public static ToggleBuilder getBuilder () { + public static ToggleBuilder getBuilder() { return new ToggleBuilder(new ToggleComponent()); } @@ -101,7 +101,7 @@ public void onClick(View v) { } }); - viewOff.setOnClickListener(new View.OnClickListener(){ + viewOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {