merge heads

This commit is contained in:
Jimmy Shih
2012-03-23 10:44:06 -07:00
11 changed files with 101 additions and 143 deletions
@@ -72,7 +72,7 @@ public class ImportActivity extends Activity {
Intent intent = getIntent(); Intent intent = getIntent();
importAll = intent.getBooleanExtra(EXTRA_IMPORT_ALL, false); importAll = intent.getBooleanExtra(EXTRA_IMPORT_ALL, false);
if (importAll) { if (importAll) {
path = new FileUtils().buildExternalDirectoryPath("gpx"); path = FileUtils.buildExternalDirectoryPath("gpx");
} else { } else {
String action = intent.getAction(); String action = intent.getAction();
if (!(Intent.ACTION_ATTACH_DATA.equals(action) || Intent.ACTION_VIEW.equals(action))) { if (!(Intent.ACTION_ATTACH_DATA.equals(action) || Intent.ACTION_VIEW.equals(action))) {
@@ -121,8 +121,7 @@ public class ImportAsyncTask extends AsyncTask<Void, Integer, Boolean> {
@Override @Override
protected Boolean doInBackground(Void... params) { protected Boolean doInBackground(Void... params) {
try { try {
FileUtils fileUtils = new FileUtils(); if (!FileUtils.isSdCardAvailable()) {
if (!fileUtils.isSdCardAvailable()) {
return false; return false;
} }
@@ -53,7 +53,7 @@ public class BackupAsyncTask extends AsyncTask<Void, Integer, Boolean> {
*/ */
public BackupAsyncTask(BackupActivity backupActivity) { public BackupAsyncTask(BackupActivity backupActivity) {
this.backupActivity = backupActivity; this.backupActivity = backupActivity;
this.externalFileBackup = new ExternalFileBackup(backupActivity, new FileUtils()); this.externalFileBackup = new ExternalFileBackup(backupActivity);
success = false; success = false;
completed = false; completed = false;
messageId = R.string.sd_card_error_write_file; messageId = R.string.sd_card_error_write_file;
@@ -80,9 +80,7 @@ public class BackupAsyncTask extends AsyncTask<Void, Integer, Boolean> {
@Override @Override
protected Boolean doInBackground(Void... params) { protected Boolean doInBackground(Void... params) {
FileUtils fileUtils = new FileUtils(); if (!FileUtils.isSdCardAvailable()) {
if (!fileUtils.isSdCardAvailable()) {
messageId = R.string.sd_card_error_no_storage; messageId = R.string.sd_card_error_no_storage;
return false; return false;
} }
@@ -65,11 +65,9 @@ class ExternalFileBackup {
private static final int COMPRESSION_LEVEL = 8; private static final int COMPRESSION_LEVEL = 8;
private final Context context; private final Context context;
private final FileUtils fileUtils;
public ExternalFileBackup(Context context, FileUtils fileUtils) { public ExternalFileBackup(Context context) {
this.context = context; this.context = context;
this.fileUtils = fileUtils;
} }
/** /**
@@ -87,12 +85,12 @@ class ExternalFileBackup {
* @param create whether to try creating the directory if it doesn't exist * @param create whether to try creating the directory if it doesn't exist
*/ */
private File getBackupsDirectory(boolean create) { private File getBackupsDirectory(boolean create) {
String dirName = fileUtils.buildExternalDirectoryPath(BACKUPS_SUBDIR); String dirName = FileUtils.buildExternalDirectoryPath(BACKUPS_SUBDIR);
final File dir = new File(dirName); final File dir = new File(dirName);
Log.d(Constants.TAG, "Dir: " + dir.getAbsolutePath()); Log.d(Constants.TAG, "Dir: " + dir.getAbsolutePath());
if (create) { if (create) {
// Try to create - if that fails, return null // Try to create - if that fails, return null
return fileUtils.ensureDirectoryExists(dir) ? dir : null; return FileUtils.ensureDirectoryExists(dir) ? dir : null;
} else { } else {
// Return it if it already exists, otherwise return null // Return it if it already exists, otherwise return null
return dir.isDirectory() ? dir : null; return dir.isDirectory() ? dir : null;
@@ -16,7 +16,6 @@
package com.google.android.apps.mytracks.io.backup; package com.google.android.apps.mytracks.io.backup;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.android.maps.mytracks.R; import com.google.android.maps.mytracks.R;
import android.os.AsyncTask; import android.os.AsyncTask;
@@ -57,7 +56,7 @@ public class RestoreAsyncTask extends AsyncTask<Void, Integer, Boolean> {
public RestoreAsyncTask(RestoreActivity restoreActivity, Date date) { public RestoreAsyncTask(RestoreActivity restoreActivity, Date date) {
this.restoreActivity = restoreActivity; this.restoreActivity = restoreActivity;
this.date = date; this.date = date;
this.externalFileBackup = new ExternalFileBackup(restoreActivity, new FileUtils()); this.externalFileBackup = new ExternalFileBackup(restoreActivity);
success = false; success = false;
completed = false; completed = false;
messageId = R.string.sd_card_error_read_file; messageId = R.string.sd_card_error_read_file;
@@ -55,11 +55,10 @@ public class RestoreChooserActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
FileUtils fileUtils = new FileUtils(); ExternalFileBackup externalFileBackup = new ExternalFileBackup(this);
ExternalFileBackup externalFileBackup = new ExternalFileBackup(this, fileUtils);
// Get the list of existing backups // Get the list of existing backups
if (!fileUtils.isSdCardAvailable()) { if (!FileUtils.isSdCardAvailable()) {
Toast.makeText(this, R.string.sd_card_error_no_storage, Toast.LENGTH_LONG).show(); Toast.makeText(this, R.string.sd_card_error_no_storage, Toast.LENGTH_LONG).show();
finish(); finish();
return; return;
@@ -101,7 +101,7 @@ public class SaveActivity extends Activity {
} }
if (shareTrack || playTrack) { if (shareTrack || playTrack) {
// Save to the temp directory // Save to the temp directory
String dirName = new FileUtils().buildExternalDirectoryPath( String dirName = FileUtils.buildExternalDirectoryPath(
trackFileFormat.getExtension(), "tmp"); trackFileFormat.getExtension(), "tmp");
trackWriter.setDirectory(new File(dirName)); trackWriter.setDirectory(new File(dirName));
} }
@@ -52,7 +52,6 @@ class TrackWriterImpl implements TrackWriter {
private final MyTracksProviderUtils providerUtils; private final MyTracksProviderUtils providerUtils;
private final Track track; private final Track track;
private final TrackFormatWriter writer; private final TrackFormatWriter writer;
private final FileUtils fileUtils;
private boolean success = false; private boolean success = false;
private int errorMessage = -1; private int errorMessage = -1;
private File directory = null; private File directory = null;
@@ -66,7 +65,6 @@ class TrackWriterImpl implements TrackWriter {
this.providerUtils = providerUtils; this.providerUtils = providerUtils;
this.track = track; this.track = track;
this.writer = writer; this.writer = writer;
this.fileUtils = new FileUtils();
} }
@Override @Override
@@ -175,7 +173,7 @@ class TrackWriterImpl implements TrackWriter {
} }
// Make sure the file doesn't exist yet (possibly by changing the filename) // Make sure the file doesn't exist yet (possibly by changing the filename)
String fileName = fileUtils.buildUniqueFileName( String fileName = FileUtils.buildUniqueFileName(
directory, track.getName(), writer.getExtension()); directory, track.getName(), writer.getExtension());
if (fileName == null) { if (fileName == null) {
Log.e(Constants.TAG, Log.e(Constants.TAG,
@@ -200,16 +198,16 @@ class TrackWriterImpl implements TrackWriter {
protected boolean canWriteFile() { protected boolean canWriteFile() {
if (directory == null) { if (directory == null) {
String dirName = String dirName =
fileUtils.buildExternalDirectoryPath(writer.getExtension()); FileUtils.buildExternalDirectoryPath(writer.getExtension());
directory = newFile(dirName); directory = newFile(dirName);
} }
if (!fileUtils.isSdCardAvailable()) { if (!FileUtils.isSdCardAvailable()) {
Log.i(Constants.TAG, "Could not find SD card."); Log.i(Constants.TAG, "Could not find SD card.");
errorMessage = R.string.sd_card_error_no_storage; errorMessage = R.string.sd_card_error_no_storage;
return false; return false;
} }
if (!fileUtils.ensureDirectoryExists(directory)) { if (!FileUtils.ensureDirectoryExists(directory)) {
Log.i(Constants.TAG, "Could not create export directory."); Log.i(Constants.TAG, "Could not create export directory.");
errorMessage = R.string.sd_card_error_create_dir; errorMessage = R.string.sd_card_error_create_dir;
return false; return false;
@@ -91,10 +91,7 @@ public class RemoveTempFilesService extends Service {
} }
private void cleanTempDirectory(String name) { private void cleanTempDirectory(String name) {
FileUtils fileUtils = new FileUtils(); cleanTempDirectory(new File(FileUtils.buildExternalDirectoryPath(name, "tmp")));
String dirName = fileUtils.buildExternalDirectoryPath(name, "tmp");
File dir = new File(dirName);
cleanTempDirectory(dir);
} }
/** /**
@@ -29,20 +29,46 @@ import java.io.File;
*/ */
public class FileUtils { public class FileUtils {
private FileUtils() {}
/** /**
* The maximum FAT32 path length. See the FAT32 spec at * The maximum FAT32 path length. See the FAT32 spec at
* http://msdn.microsoft.com/en-us/windows/hardware/gg463080 * http://msdn.microsoft.com/en-us/windows/hardware/gg463080
*/ */
@VisibleForTesting @VisibleForTesting
static final int MAX_FAT32_PATH_LENGTH = 260; static final int MAX_FAT32_PATH_LENGTH = 260;
/**
* Returns whether the SD card is available.
*/
public static boolean isSdCardAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
* Ensures the given directory exists by creating it and its parents if
* necessary.
*
* @return whether the directory exists (either already existed or was
* successfully created)
*/
public static boolean ensureDirectoryExists(File dir) {
if (dir.exists() && dir.isDirectory()) {
return true;
}
if (dir.mkdirs()) {
return true;
}
return false;
}
/** /**
* Builds a path inside the My Tracks directory in the SD card. * Builds a path inside the My Tracks directory in the SD card.
* *
* @param components the path components inside the mytracks directory * @param components the path components inside the mytracks directory
* @return the full path to the destination * @return the full path to the destination
*/ */
public String buildExternalDirectoryPath(String... components) { public static String buildExternalDirectoryPath(String... components) {
StringBuilder dirNameBuilder = new StringBuilder(); StringBuilder dirNameBuilder = new StringBuilder();
dirNameBuilder.append(Environment.getExternalStorageDirectory()); dirNameBuilder.append(Environment.getExternalStorageDirectory());
dirNameBuilder.append(File.separatorChar); dirNameBuilder.append(File.separatorChar);
@@ -54,33 +80,6 @@ public class FileUtils {
return dirNameBuilder.toString(); return dirNameBuilder.toString();
} }
/**
* Returns whether the SD card is available.
*/
public boolean isSdCardAvailable() {
return Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState());
}
/**
* Ensures the given directory exists by creating it and its parents if
* necessary.
*
* @return whether the directory exists (either already existed or was
* successfully created)
*/
public boolean ensureDirectoryExists(File dir) {
if (dir.exists() && dir.isDirectory()) {
return true;
}
if (dir.mkdirs()) {
return true;
}
return false;
}
/** /**
* Builds a filename with the given base name (prefix) and the given * Builds a filename with the given base name (prefix) and the given
* extension, possibly adding a suffix to ensure the file doesn't exist. * extension, possibly adding a suffix to ensure the file doesn't exist.
@@ -90,8 +89,8 @@ public class FileUtils {
* @param extension the file's extension * @param extension the file's extension
* @return the complete file name, without the directory * @return the complete file name, without the directory
*/ */
public synchronized String buildUniqueFileName(File directory, public static synchronized String buildUniqueFileName(
String fileBaseName, String extension) { File directory, String fileBaseName, String extension) {
return buildUniqueFileName(directory, fileBaseName, extension, 0); return buildUniqueFileName(directory, fileBaseName, extension, 0);
} }
@@ -105,7 +104,8 @@ public class FileUtils {
* @param suffix the first numeric suffix to try to use, or 0 for none * @param suffix the first numeric suffix to try to use, or 0 for none
* @return the complete filename, without the directory * @return the complete filename, without the directory
*/ */
private String buildUniqueFileName(File directory, String base, String extension, int suffix) { private static String buildUniqueFileName(
File directory, String base, String extension, int suffix) {
String suffixName = ""; String suffixName = "";
if (suffix > 0) { if (suffix > 0) {
suffixName += "(" + Integer.toString(suffix) + ")"; suffixName += "(" + Integer.toString(suffix) + ")";
@@ -115,8 +115,8 @@ public class FileUtils {
String baseName = sanitizeFileName(base); String baseName = sanitizeFileName(base);
baseName = truncateFileName(directory, baseName, suffixName); baseName = truncateFileName(directory, baseName, suffixName);
String fullName = baseName + suffixName; String fullName = baseName + suffixName;
if (!fileExists(directory, fullName)) { if (!new File(directory, fullName).exists()) {
return fullName; return fullName;
} }
return buildUniqueFileName(directory, base, extension, suffix + 1); return buildUniqueFileName(directory, base, extension, suffix + 1);
@@ -131,7 +131,7 @@ public class FileUtils {
* @param name name * @param name name
*/ */
@VisibleForTesting @VisibleForTesting
String sanitizeFileName(String name) { static String sanitizeFileName(String name) {
StringBuffer buffer = new StringBuffer(name.length()); StringBuffer buffer = new StringBuffer(name.length());
for (int i = 0; i < name.length(); i++) { for (int i = 0; i < name.length(); i++) {
int codePoint = name.codePointAt(i); int codePoint = name.codePointAt(i);
@@ -145,13 +145,13 @@ public class FileUtils {
String result = buffer.toString(); String result = buffer.toString();
return result.replaceAll("_+", "_"); return result.replaceAll("_+", "_");
} }
/** /**
* Returns true if it is a special FAT32 character. * Returns true if it is a special FAT32 character.
* *
* @param character the character * @param character the character
*/ */
private boolean isSpecialFat32(char character) { private static boolean isSpecialFat32(char character) {
switch (character) { switch (character) {
case '$': case '$':
case '%': case '%':
@@ -191,8 +191,8 @@ public class FileUtils {
* @param suffix suffix * @param suffix suffix
*/ */
@VisibleForTesting @VisibleForTesting
String truncateFileName(File directory, String name, String suffix) { static String truncateFileName(File directory, String name, String suffix) {
// 1 at the end accounts for the FAT32 filename trailing NUL character // 1 at the end accounts for the FAT32 filename trailing NUL character
int requiredLength = directory.getPath().length() + suffix.length() + 1; int requiredLength = directory.getPath().length() + suffix.length() + 1;
if (name.length() + requiredLength > MAX_FAT32_PATH_LENGTH) { if (name.length() + requiredLength > MAX_FAT32_PATH_LENGTH) {
int limit = MAX_FAT32_PATH_LENGTH - requiredLength; int limit = MAX_FAT32_PATH_LENGTH - requiredLength;
@@ -201,13 +201,4 @@ public class FileUtils {
return name; return name;
} }
} }
/**
* Checks whether a file with the given name exists in the given directory.
* This is isolated so it can be overridden in tests.
*/
protected boolean fileExists(File directory, String fullName) {
File file = new File(directory, fullName);
return file.exists();
}
} }
@@ -20,8 +20,6 @@ import com.google.android.apps.mytracks.Constants;
import android.os.Environment; import android.os.Environment;
import java.io.File; import java.io.File;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase; import junit.framework.TestCase;
@@ -31,76 +29,81 @@ import junit.framework.TestCase;
* @author Rodrigo Damazio * @author Rodrigo Damazio
*/ */
public class FileUtilsTest extends TestCase { public class FileUtilsTest extends TestCase {
private FileUtils fileUtils;
private Set<String> existingFiles;
@Override
protected void setUp() throws Exception {
super.setUp();
existingFiles = new HashSet<String>();
fileUtils = new FileUtils() {
@Override
protected boolean fileExists(File directory, String fullName) {
return existingFiles.contains(fullName);
}
};
}
/**
* Tests {@link FileUtils#buildExternalDirectoryPath(String...)}.
*/
public void testBuildExternalDirectoryPath() { public void testBuildExternalDirectoryPath() {
String expectedName = Environment.getExternalStorageDirectory() String expectedName = Environment.getExternalStorageDirectory() + File.separator
+ File.separator + Constants.SDCARD_TOP_DIR + File.separator + "a" + File.separator + "b" + File.separator
+ Constants.SDCARD_TOP_DIR
+ File.separator
+ "a"
+ File.separator
+ "b"
+ File.separator
+ "c"; + "c";
String dirName = FileUtils.buildExternalDirectoryPath("a", "b", "c");
String dirName = fileUtils.buildExternalDirectoryPath("a", "b", "c");
assertEquals(expectedName, dirName); assertEquals(expectedName, dirName);
} }
/** /**
* Tests sanitize filename. * Tests {@link FileUtils#buildUniqueFileName(File, String, String)} when the
* file is new.
*/
public void testBuildUniqueFileName_new() {
String filename = FileUtils.buildUniqueFileName(new File("/dir"), "Filename", "ext");
assertEquals("Filename.ext", filename);
}
/**
* Tests {@link FileUtils#buildUniqueFileName(File, String, String)} when the
* file exists already.
*/
public void testBuildUniqueFileName_exist() {
// Expect "/default.prop" to exist on the phone/emulator
String filename = FileUtils.buildUniqueFileName(new File("/"), "default", "prop");
assertEquals("default(1).prop", filename);
}
/**
* Tests {@link FileUtils#sanitizeFileName(String)} with special characters.
* Verifies that they are sanitized.
*/ */
public void testSanitizeFileName() { public void testSanitizeFileName() {
String name = "Swim\10ming-^across:/the/ pacific (ocean)."; String name = "Swim\10ming-^across:/the/ pacific (ocean).";
String expected = "Swim_ming-^across_the_ pacific (ocean)_"; String expected = "Swim_ming-^across_the_ pacific (ocean)_";
assertEquals(expected, fileUtils.sanitizeFileName(name)); assertEquals(expected, FileUtils.sanitizeFileName(name));
} }
/** /**
* Tests characters in other languages, like Chinese and Russian, are allowed. * Tests {@link FileUtils#sanitizeFileName(String)} with i18n characters (in
* Chinese and Russian). Verifies that they are allowed.
*/ */
public void testSanitizeFileName_i18n() { public void testSanitizeFileName_i18n() {
String name = "您好-привет"; String name = "您好-привет";
String expected = "您好-привет"; String expected = "您好-привет";
assertEquals(expected, FileUtils.sanitizeFileName(name));
assertEquals(expected, fileUtils.sanitizeFileName(name));
} }
/** /**
* Tests special FAT32 characters are allowed. * Tests {@link FileUtils#sanitizeFileName(String)} with special FAT32
* characters. Verifies that they are allowed.
*/ */
public void testSanitizeFileName_special_characters() { public void testSanitizeFileName_special_characters() {
String name = "$%'-_@~`!(){}^#&+,;=[] "; String name = "$%'-_@~`!(){}^#&+,;=[] ";
String expected = "$%'-_@~`!(){}^#&+,;=[] "; String expected = "$%'-_@~`!(){}^#&+,;=[] ";
assertEquals(expected, FileUtils.sanitizeFileName(name));
assertEquals(expected, fileUtils.sanitizeFileName(name));
} }
/** /**
* Testing collapsing multiple underscores characters. * Tests {@link FileUtils#sanitizeFileName(String)} with multiple escaped
* characters in a row. Verifies that they are collapsed into one underscore.
*/ */
public void testSanitizeFileName_collapse() { public void testSanitizeFileName_collapse() {
String name = "hello//there"; String name = "hello//there";
String expected = "hello_there"; String expected = "hello_there";
assertEquals(expected, FileUtils.sanitizeFileName(name));
assertEquals(expected, fileUtils.sanitizeFileName(name));
} }
/**
* Tests {@link FileUtils#truncateFileName(File, String, String)}. Verifies
* the a long file name is truncated.
*/
public void testTruncateFileName() { public void testTruncateFileName() {
File directory = new File("/dir1/dir2/"); File directory = new File("/dir1/dir2/");
String suffix = ".gpx"; String suffix = ".gpx";
@@ -109,36 +112,12 @@ public class FileUtilsTest extends TestCase {
name[i] = 'a'; name[i] = 'a';
} }
String nameString = new String(name); String nameString = new String(name);
String truncated = FileUtils.truncateFileName(directory, nameString, suffix);
String truncated = fileUtils.truncateFileName(directory, nameString, suffix);
for (int i = 0; i < truncated.length(); i++) { for (int i = 0; i < truncated.length(); i++) {
assertEquals('a', truncated.charAt(i)); assertEquals('a', truncated.charAt(i));
} }
assertEquals(FileUtils.MAX_FAT32_PATH_LENGTH, assertEquals(FileUtils.MAX_FAT32_PATH_LENGTH,
new File(directory, truncated + suffix).getPath().length()); new File(directory, truncated + suffix).getPath().length());
} }
public void testBuildUniqueFileName_someExist() {
existingFiles = new HashSet<String>();
existingFiles.add("Filename.ext");
existingFiles.add("Filename(1).ext");
existingFiles.add("Filename(2).ext");
existingFiles.add("Filename(3).ext");
existingFiles.add("Filename(4).ext");
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename(5).ext", filename);
}
public void testBuildUniqueFileName_oneExists() {
existingFiles.add("Filename.ext");
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename(1).ext", filename);
}
public void testBuildUniqueFileName_noneExists() {
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename.ext", filename);
}
} }