aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBananeweizen <bananeweizen@gmx.de>2011-11-01 19:25:40 +0100
committerBananeweizen <bananeweizen@gmx.de>2011-11-01 19:25:40 +0100
commit6a8f40ccb8c7761e75e4041cb7e53c4df4064573 (patch)
treea890ed1a7a2f3d77cb3babe929e3316666333797
parenta5571fe16d358c91b60be1f45085d54f16df800b (diff)
parent96fbeff00e6793eed966c15f5829e3d18e16b326 (diff)
downloadcgeo-6a8f40ccb8c7761e75e4041cb7e53c4df4064573.zip
cgeo-6a8f40ccb8c7761e75e4041cb7e53c4df4064573.tar.gz
cgeo-6a8f40ccb8c7761e75e4041cb7e53c4df4064573.tar.bz2
Merge remote branch 'stephanme/importwpt'
Conflicts: main/src/cgeo/geocaching/files/GPXParser.java main/src/cgeo/geocaching/files/LocParser.java tests/src/cgeo/geocaching/files/LocParserTest.java
-rw-r--r--main/res/values-de/strings.xml14
-rw-r--r--main/res/values/strings.xml13
-rw-r--r--main/src/cgeo/geocaching/cgeogpxes.java228
-rw-r--r--main/src/cgeo/geocaching/files/FileParser.java61
-rw-r--r--main/src/cgeo/geocaching/files/GPXParser.java126
-rw-r--r--main/src/cgeo/geocaching/files/LocParser.java64
-rw-r--r--main/src/cgeo/geocaching/files/ParserException.java24
-rw-r--r--tests/res/raw/gc31j2h_err.gpx17
-rw-r--r--tests/src/cgeo/geocaching/cgeogpxesTest.java194
-rw-r--r--tests/src/cgeo/geocaching/files/GPXParserTest.java36
-rw-r--r--tests/src/cgeo/geocaching/files/LocParserTest.java75
11 files changed, 542 insertions, 310 deletions
diff --git a/main/res/values-de/strings.xml b/main/res/values-de/strings.xml
index ea0ab0c..28b6e9b 100644
--- a/main/res/values-de/strings.xml
+++ b/main/res/values-de/strings.xml
@@ -544,17 +544,19 @@
<string name="file_title_searching">Suche</string>
<!-- gpx -->
- <string name="gpx_import_loading_caches">Lade Caches aus GPX-Datei\nGelesen:</string>
- <string name="gpx_import_loading_waypoints">Lade Wegpunkte aus GPX-Datei\nGelesen:</string>
- <string name="gpx_import_storing">Schreibe Caches in Datenbank\nGespeichert:</string>
- <string name="gpx_import_loading_stored">Lade Caches aus GPX-Datei\nGespeichert:</string>
+ <string name="gpx_import_loading_caches">Lade Caches aus GPX-Datei</string>
+ <string name="gpx_import_loading_waypoints">Lade Wegpunkte aus GPX-Datei</string>
+ <string name="gpx_import_storing">Schreibe Caches in Datenbank</string>
<string name="gpx_import_caches_imported">Caches importiert.</string>
- <string name="gpx_import_loading">Lade Caches aus GPX-Datei</string>
<string name="gpx_import_title">Importiere GPX-Datei</string>
<string name="gpx_import_title_reading_file">Lese Datei</string>
<string name="gpx_import_title_caches_imported">Ergebnis</string>
+ <string name="gpx_import_title_caches_import_failed">Import-Fehler</string>
+ <string name="gpx_import_error_io">Fehler beim Lesen der Datei</string>
+ <string name="gpx_import_error_parser">Dateiformat nicht ok</string>
+ <string name="gpx_import_error_unexpected">Unerwarteter Fehler</string>
<string name="gpx_import_confirm">Soll die GPX-Datei importiert werden?</string>
-
+
<!-- map file select -->
<string name="map_file_select_title">Wähle eine Kartendatei</string>
diff --git a/main/res/values/strings.xml b/main/res/values/strings.xml
index 007825b..f5f01e8 100644
--- a/main/res/values/strings.xml
+++ b/main/res/values/strings.xml
@@ -565,16 +565,19 @@
<string name="file_title_searching">Searching</string>
<!-- gpx -->
- <string name="gpx_import_loading_caches">Loading caches from .gpx file\nRead:</string>
- <string name="gpx_import_loading_waypoints">Loading waypoints from .gpx file\nRead:</string>
- <string name="gpx_import_storing">Writing caches to database\nStored:</string>
- <string name="gpx_import_loading_stored">Loading caches from .gpx file\nStored:</string>
+ <string name="gpx_import_loading_caches">Loading caches from .gpx file</string>
+ <string name="gpx_import_loading_waypoints">Loading waypoints file</string>
+ <string name="gpx_import_storing">Writing caches to database</string>
<string name="gpx_import_caches_imported">caches imported</string>
- <string name="gpx_import_loading">Loading caches from .gpx file</string>
<string name="gpx_import_title">Import GPX</string>
<string name="gpx_import_title_reading_file">Reading file</string>
<string name="gpx_import_title_caches_imported">Result</string>
+ <string name="gpx_import_title_caches_import_failed">Import failed</string>
+ <string name="gpx_import_error_io">Can\'t read file</string>
+ <string name="gpx_import_error_parser">File format not ok</string>
+ <string name="gpx_import_error_unexpected">Unexpected error</string>
<string name="gpx_import_confirm">Do you want to import the GPX file into c:geo?</string>
+ <string name="gpx_import_loading">Loading caches from .gpx file</string>
<!-- map file select -->
<string name="map_file_select_title">Select map file</string>
diff --git a/main/src/cgeo/geocaching/cgeogpxes.java b/main/src/cgeo/geocaching/cgeogpxes.java
index 865b9e7..0669f54 100644
--- a/main/src/cgeo/geocaching/cgeogpxes.java
+++ b/main/src/cgeo/geocaching/cgeogpxes.java
@@ -1,30 +1,45 @@
package cgeo.geocaching;
import cgeo.geocaching.files.FileList;
+import cgeo.geocaching.files.GPX10Parser;
+import cgeo.geocaching.files.GPX11Parser;
import cgeo.geocaching.files.GPXParser;
import cgeo.geocaching.files.LocParser;
+import cgeo.geocaching.files.ParserException;
import org.apache.commons.lang3.StringUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
+import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
+import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
+import android.util.Log;
import java.io.File;
-import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.InputStream;
+import java.util.Collection;
import java.util.List;
public class cgeogpxes extends FileList<cgGPXListAdapter> {
+ public static final String GPX_FILE_EXTENSION = ".gpx";
+ public static final String WAYPOINTS_FILE_SUFFIX_AND_EXTENSION = "-wpts.gpx";
private static final String EXTRAS_LIST_ID = "list";
+ static final int IMPORT_STEP_READ_FILE = 1;
+ static final int IMPORT_STEP_READ_WPT_FILE = 2;
+ static final int IMPORT_STEP_STORE_CACHES = 3;
+ static final int IMPORT_STEP_FINISHED = 4;
+ static final int IMPORT_STEP_FINISHED_WITH_ERROR = 5;
+
public cgeogpxes() {
super(new String[] { "gpx", "loc" });
}
@@ -32,28 +47,35 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> {
private ProgressDialog parseDialog = null;
private int listId = 1;
- final private Handler changeParseDialogHandler = new Handler() {
-
+ final private Handler progressHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
- if (parseDialog != null) {
- parseDialog.setMessage(res.getString(msg.arg1) + " " + msg.arg2);
- if (msg.obj != null) {
- final int progress = (Integer) msg.obj;
- parseDialog.setProgress(progress);
- }
- }
+ parseDialog.setProgress(msg.arg1);
}
};
- final private Handler loadCachesHandler = new Handler() {
+ final private Handler importStepHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
- if (parseDialog != null) {
- parseDialog.dismiss();
+ switch (msg.what) {
+ case IMPORT_STEP_READ_FILE:
+ case IMPORT_STEP_READ_WPT_FILE:
+ case IMPORT_STEP_STORE_CACHES:
+ parseDialog.setMessage(res.getString(msg.arg1));
+ parseDialog.setMax(msg.arg2);
+ parseDialog.setProgress(0);
+ break;
+
+ case IMPORT_STEP_FINISHED:
+ parseDialog.dismiss();
+ helpDialog(res.getString(R.string.gpx_import_title_caches_imported), msg.arg1 + " " + res.getString(R.string.gpx_import_caches_imported));
+ break;
+
+ case IMPORT_STEP_FINISHED_WITH_ERROR:
+ parseDialog.dismiss();
+ helpDialog(res.getString(R.string.gpx_import_title_caches_import_failed), res.getString(msg.arg1) + "\n\n" + msg.obj);
+ break;
}
-
- helpDialog(res.getString(R.string.gpx_import_title_caches_imported), msg.arg1 + " " + res.getString(R.string.gpx_import_caches_imported));
}
};
@@ -86,13 +108,7 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> {
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
- try {
- final InputStream attachment = getContentResolver().openInputStream(getIntent().getData());
- importGPX(attachment);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ importGPX((Uri) getIntent().getData(), getContentResolver());
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
@@ -111,64 +127,167 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> {
}
public void importGPX(final File file) {
- createProgressDialog((int) file.length());
- new ImportFileThread(file).start();
+ createProgressDialog();
+ if (StringUtils.endsWithIgnoreCase(file.getName(), GPX_FILE_EXTENSION)) {
+ new ImportGpxFileThread(file, listId, importStepHandler, progressHandler).start();
+ } else {
+ new ImportLocFileThread(file, listId, importStepHandler, progressHandler).start();
+ }
}
- public void importGPX(final InputStream stream) {
- createProgressDialog(-1);
- new ImportStreamThread(stream).start();
+ public void importGPX(final Uri uri, ContentResolver contentResolver) {
+ createProgressDialog();
+ new ImportAttachmentThread(uri, contentResolver, listId, importStepHandler, progressHandler).start();
}
- private void createProgressDialog(int maxBytes) {
+ private void createProgressDialog() {
parseDialog = new ProgressDialog(this);
parseDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
parseDialog.setTitle(res.getString(R.string.gpx_import_title_reading_file));
parseDialog.setMessage(res.getString(R.string.gpx_import_loading));
parseDialog.setCancelable(false);
- parseDialog.setMax(maxBytes);
+ parseDialog.setMax(-1);
parseDialog.show();
}
- private abstract class ImportThread extends Thread {
+ static abstract class ImportThread extends Thread {
+ final int listId;
+ final Handler importStepHandler;
+ final Handler progressHandler;
+
+ public ImportThread(int listId, Handler importStepHandler, Handler progressHandler) {
+ this.listId = listId;
+ this.importStepHandler = importStepHandler;
+ this.progressHandler = progressHandler;
+ }
@Override
public void run() {
- final cgSearch search = doImport();
- loadCachesHandler.sendMessage(loadCachesHandler.obtainMessage(0, cgeoapplication.getCount(search), 0));
+ final Collection<cgCache> caches;
+ try {
+ caches = doImport();
+
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_STORE_CACHES, R.string.gpx_import_storing, caches.size()));
+ cgSearch search = storeParsedCaches(caches);
+ Log.i(Settings.tag, "Imported successfully " + caches.size() + " caches.");
+
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_FINISHED, cgeoapplication.getCount(search), 0, search));
+ } catch (IOException e) {
+ Log.i(Settings.tag, "Importing caches failed - error reading data: " + e.getMessage());
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_FINISHED_WITH_ERROR, R.string.gpx_import_error_io, 0, e.getLocalizedMessage()));
+ } catch (ParserException e) {
+ Log.i(Settings.tag, "Importing caches failed - data format error" + e.getMessage());
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_FINISHED_WITH_ERROR, R.string.gpx_import_error_parser, 0, e.getLocalizedMessage()));
+ } catch (Exception e) {
+ Log.e(Settings.tag, "Importing caches failed - unknown error: ", e);
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_FINISHED_WITH_ERROR, R.string.gpx_import_error_unexpected, 0, e.getLocalizedMessage()));
+ }
}
- protected abstract cgSearch doImport();
+ protected abstract Collection<cgCache> doImport() throws IOException, ParserException;
+
+ private cgSearch storeParsedCaches(Collection<cgCache> caches) {
+ final cgSearch search = new cgSearch();
+ final cgeoapplication app = cgeoapplication.getInstance();
+ int storedCaches = 0;
+ for (cgCache cache : caches) {
+ // remove from cache because a cache might be re-imported
+ app.removeCacheFromCache(cache.getGeocode());
+ app.addCacheToSearch(search, cache);
+ progressHandler.sendMessage(progressHandler.obtainMessage(0, ++storedCaches, 0));
+ }
+ return search;
+ }
}
- private class ImportFileThread extends ImportThread {
- private final File file;
+ static class ImportGpxFileThread extends ImportThread {
+ private final File cacheFile;
- public ImportFileThread(final File file) {
- this.file = file;
+ public ImportGpxFileThread(final File file, int listId, Handler importStepHandler, Handler progressHandler) {
+ super(listId, importStepHandler, progressHandler);
+ this.cacheFile = file;
}
@Override
- protected cgSearch doImport() {
- if (StringUtils.endsWithIgnoreCase(file.getName(), GPXParser.GPX_FILE_EXTENSION)) {
- return GPXParser.importGPX(file, listId, changeParseDialogHandler);
+ protected Collection<cgCache> doImport() throws IOException, ParserException {
+ Log.i(Settings.tag, "Import GPX file: " + cacheFile.getAbsolutePath());
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, (int) cacheFile.length()));
+ Collection<cgCache> caches;
+ GPXParser parser;
+ try {
+ // try to parse cache file as GPX 10
+ parser = new GPX10Parser(listId);
+ caches = parser.parse(cacheFile, progressHandler);
+ } catch (ParserException pe) {
+ // didn't work -> lets try GPX11
+ parser = new GPX11Parser(listId);
+ caches = parser.parse(cacheFile, progressHandler);
}
- else {
- return LocParser.parseLoc(file, listId, changeParseDialogHandler);
+
+ final File wptsFile = getWaypointsFileForGpx(cacheFile);
+ if (wptsFile != null && wptsFile.canRead()) {
+ Log.i(Settings.tag, "Import GPX waypoint file: " + wptsFile.getAbsolutePath());
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_READ_WPT_FILE, R.string.gpx_import_loading_waypoints, (int) wptsFile.length()));
+ caches = parser.parse(wptsFile, progressHandler);
}
+
+ return caches;
+ }
+ }
+
+ static class ImportLocFileThread extends ImportThread {
+ private final File file;
+
+ public ImportLocFileThread(final File file, int listId, Handler importStepHandler, Handler progressHandler) {
+ super(listId, importStepHandler, progressHandler);
+ this.file = file;
+ }
+
+ @Override
+ protected Collection<cgCache> doImport() throws IOException, ParserException {
+ Log.i(Settings.tag, "Import LOC file: " + file.getAbsolutePath());
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, (int) file.length()));
+ LocParser parser = new LocParser(listId);
+ return parser.parse(file, progressHandler);
}
}
- private class ImportStreamThread extends ImportThread {
- private final InputStream stream;
+ static class ImportAttachmentThread extends ImportThread {
+ private final Uri uri;
+ private ContentResolver contentResolver;
- public ImportStreamThread(InputStream stream) {
- this.stream = stream;
+ public ImportAttachmentThread(Uri uri, ContentResolver contentResolver, int listId, Handler importStepHandler, Handler progressHandler) {
+ super(listId, importStepHandler, progressHandler);
+ this.uri = uri;
+ this.contentResolver = contentResolver;
}
@Override
- protected cgSearch doImport() {
- return GPXParser.importGPX(stream, listId, changeParseDialogHandler);
+ protected Collection<cgCache> doImport() throws IOException, ParserException {
+ Log.i(Settings.tag, "Import GPX from uri: " + uri);
+ importStepHandler.sendMessage(importStepHandler.obtainMessage(IMPORT_STEP_READ_FILE, R.string.gpx_import_loading_caches, -1));
+
+ Collection<cgCache> caches;
+ GPXParser parser;
+ try {
+ // try to parse cache file as GPX 10
+ parser = new GPX10Parser(listId);
+ caches = parseAttachement(parser);
+ } catch (ParserException pe) {
+ // didn't work -> lets try GPX11
+ parser = new GPX11Parser(listId);
+ caches = parseAttachement(parser);
+ }
+ return caches;
+ }
+
+ private Collection<cgCache> parseAttachement(GPXParser parser) throws IOException, ParserException {
+ InputStream is = contentResolver.openInputStream(uri);
+ try {
+ return parser.parse(is, progressHandler);
+ } finally {
+ is.close();
+ }
}
}
@@ -182,8 +301,19 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> {
protected boolean filenameBelongsToList(final String filename) {
if (super.filenameBelongsToList(filename)) {
// filter out waypoint files
- return !StringUtils.endsWithIgnoreCase(filename, GPXParser.WAYPOINTS_FILE_SUFFIX_AND_EXTENSION);
+ return !StringUtils.endsWithIgnoreCase(filename, WAYPOINTS_FILE_SUFFIX_AND_EXTENSION);
}
return false;
}
+
+ // 1234567.gpx -> 1234567-wpts.gpx
+ static File getWaypointsFileForGpx(File file) {
+ final String name = file.getName();
+ if (StringUtils.endsWithIgnoreCase(name, GPX_FILE_EXTENSION) && (StringUtils.length(name) > GPX_FILE_EXTENSION.length())) {
+ final String wptsName = StringUtils.substringBeforeLast(name, ".") + WAYPOINTS_FILE_SUFFIX_AND_EXTENSION;
+ return new File(file.getParentFile(), wptsName);
+ } else {
+ return null;
+ }
+ }
}
diff --git a/main/src/cgeo/geocaching/files/FileParser.java b/main/src/cgeo/geocaching/files/FileParser.java
index 1083c65..a803c2b 100644
--- a/main/src/cgeo/geocaching/files/FileParser.java
+++ b/main/src/cgeo/geocaching/files/FileParser.java
@@ -6,36 +6,66 @@ import android.os.Handler;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
+import java.io.FileInputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Collection;
import java.util.Date;
public abstract class FileParser {
- protected static StringBuilder readFile(File file)
- throws FileNotFoundException, IOException {
+ /**
+ * Parses caches from input stream.
+ *
+ * @param stream
+ * @param progressHandler
+ * for reporting parsing progress (in bytes read from input stream)
+ * @return collection of parsed caches
+ * @throws IOException
+ * if the input stream can't be read
+ * @throws ParserException
+ * if the input stream contains data not matching the file format of the parser
+ */
+ public abstract Collection<cgCache> parse(final InputStream stream, final Handler progressHandler) throws IOException, ParserException;
+
+ /**
+ * Convenience method for parsing a file.
+ *
+ * @param file
+ * @param progressHandler
+ * @return
+ * @throws IOException
+ * @throws ParserException
+ */
+ public Collection<cgCache> parse(final File file, final Handler progressHandler) throws IOException, ParserException {
+ FileInputStream fis = new FileInputStream(file);
+ try {
+ return parse(fis, progressHandler);
+ } finally {
+ fis.close();
+ }
+ }
+
+ protected static StringBuilder readStream(InputStream is, Handler progressHandler) throws IOException {
final StringBuilder buffer = new StringBuilder();
- final BufferedReader input = new BufferedReader(new FileReader(file));
+ ProgressInputStream progressInputStream = new ProgressInputStream(is);
+ final BufferedReader input = new BufferedReader(new InputStreamReader(progressInputStream));
+
try {
String line = null;
while ((line = input.readLine()) != null) {
buffer.append(line);
+ showProgressMessage(progressHandler, progressInputStream.getProgress());
}
+ return buffer;
} finally {
input.close();
}
- return buffer;
}
- protected static void showCountMessage(final Handler handler, final int msgId, final int count) {
- if (handler != null && (count <= 1 || count % 10 == 0)) {
- handler.sendMessage(handler.obtainMessage(0, msgId, count));
- }
- }
-
- protected static void showCountMessage(final Handler handler, final int msgId, final int count, final int bytesRead) {
- if (handler != null && (count <= 1 || count % 10 == 0)) {
- handler.sendMessage(handler.obtainMessage(0, msgId, count, bytesRead));
+ protected static void showProgressMessage(final Handler handler, final int bytesRead) {
+ if (handler != null) {
+ handler.sendMessage(handler.obtainMessage(0, bytesRead, 0));
}
}
@@ -49,5 +79,4 @@ public abstract class FileParser {
cache.setUpdated(time);
cache.setDetailedUpdate(time);
}
-
}
diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java
index 900c83b..01929c6 100644
--- a/main/src/cgeo/geocaching/files/GPXParser.java
+++ b/main/src/cgeo/geocaching/files/GPXParser.java
@@ -5,7 +5,6 @@ import cgeo.geocaching.Settings;
import cgeo.geocaching.cgBase;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgLog;
-import cgeo.geocaching.cgSearch;
import cgeo.geocaching.cgTrackable;
import cgeo.geocaching.cgWaypoint;
import cgeo.geocaching.cgeoapplication;
@@ -28,9 +27,6 @@ import android.sax.StartElementListener;
import android.util.Log;
import android.util.Xml;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
@@ -66,15 +62,11 @@ public abstract class GPXParser extends FileParser {
*/
private static final String GSAK_NS = "http://www.gsak.net/xmlv1/5";
- public static final String GPX_FILE_EXTENSION = ".gpx";
- public static final String WAYPOINTS_FILE_SUFFIX_AND_EXTENSION = "-wpts.gpx";
private static final Pattern PATTERN_MILLISECONDS = Pattern.compile("\\.\\d{3}");
private int listId = 1;
final protected String namespace;
final private String version;
- private Handler handler = null;
- private int importedRecords;
private cgCache cache = new cgCache();
private cgTrackable trackable = new cgTrackable();
@@ -243,10 +235,7 @@ public abstract class GPXParser extends FileParser {
return formatSimple.parse(input);
}
- boolean parse(final InputStream stream, Handler handlerIn) {
- importedRecords = 0;
- handler = handlerIn;
-
+ public Collection<cgCache> parse(final InputStream stream, final Handler progressHandler) throws IOException, ParserException {
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
@@ -290,7 +279,7 @@ public abstract class GPXParser extends FileParser {
createNoteFromGSAKUserdata();
result.put(cache.getGeocode(), cache);
- showCountMessage(handler, R.string.gpx_import_loading_caches, ++importedRecords, progressStream.getProgress());
+ showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& cache.getCoords() != null
&& StringUtils.contains(type, "waypoint")) {
@@ -325,7 +314,7 @@ public abstract class GPXParser extends FileParser {
}
cgWaypoint.mergeWayPoints(cacheForWaypoint.getWaypoints(), Collections.singletonList(waypoint));
result.put(cacheGeocodeForWaypoint, cacheForWaypoint);
- showCountMessage(handler, R.string.gpx_import_loading_waypoints, ++importedRecords, progressStream.getProgress());
+ showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
@@ -740,41 +729,11 @@ public abstract class GPXParser extends FileParser {
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
- return true;
- } catch (IOException e) {
- Log.e(Settings.tag, "Cannot parse .gpx file as GPX " + version + ": could not read file!");
+ return result.values();
} catch (SAXException e) {
Log.e(Settings.tag, "Cannot parse .gpx file as GPX " + version + ": could not parse XML - " + e.toString());
+ throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
- return false;
- }
-
- private boolean parse(final File file, final Handler handlerIn) {
- if (file == null) {
- return false;
- }
-
- FileInputStream fis = null;
- boolean parsed = false;
- try {
- fis = new FileInputStream(file);
- parsed = parse(fis, handlerIn);
- } catch (FileNotFoundException e) {
- Log.e(Settings.tag, "Cannot parse .gpx file " + file.getAbsolutePath() + " as GPX " + version + ": file not found!");
- } finally {
- try {
- if (fis != null) {
- fis.close();
- }
- } catch (IOException e) {
- Log.e(Settings.tag, "Error after parsing .gpx file " + file.getAbsolutePath() + " as GPX " + version + ": could not close file!");
- }
- }
- return parsed;
- }
-
- public Collection<cgCache> getParsedCaches() {
- return result.values();
}
/**
@@ -855,79 +814,4 @@ public abstract class GPXParser extends FileParser {
}
}
}
-
- public static cgSearch importGPX(File file, int listId, Handler handler) {
- try {
- // parse cache file
- GPXParser parser = new GPX10Parser(listId);
- boolean parsed = parser.parse(file, handler);
- if (!parsed) {
- parser = new GPX11Parser(listId);
- parsed = parser.parse(file, handler);
- }
-
- // parse waypoint file if exists
- if (parsed) {
- final File wptsFile = getWaypointsFileForGpx(file);
- if (wptsFile != null && wptsFile.canRead()) {
- parser.parse(wptsFile, handler);
- }
- }
-
- if (parsed) {
- return storeParsedCaches(handler, parser);
- }
-
- } catch (Exception e) {
- Log.e(Settings.tag, "GPXParser.importGPX: " + e.toString());
- }
-
- return null;
- }
-
- public static cgSearch importGPX(InputStream stream, int listId, Handler handler) {
- try {
- // parse cache file
- GPXParser parser = new GPX10Parser(listId);
- boolean parsed = parser.parse(stream, handler);
- if (!parsed) {
- parser = new GPX11Parser(listId);
- parsed = parser.parse(stream, handler);
- }
-
- if (parsed) {
- return storeParsedCaches(handler, parser);
- }
-
- } catch (Exception e) {
- Log.e(Settings.tag, "GPXParser.importGPX: " + e.toString());
- }
-
- return null;
- }
-
- private static cgSearch storeParsedCaches(Handler handler, GPXParser parser) {
- final cgSearch search = new cgSearch();
- final cgeoapplication app = cgeoapplication.getInstance();
- int storedCaches = 0;
- for (cgCache cache : parser.getParsedCaches()) {
- // remove from cache, cache can be re-imported
- app.removeCacheFromCache(cache.getGeocode());
- app.addCacheToSearch(search, cache);
- showCountMessage(handler, R.string.gpx_import_storing, ++storedCaches);
- }
- Log.i(Settings.tag, "Caches found in .gpx file: " + parser.getParsedCaches().size());
- return search;
- }
-
- // 1234567.gpx -> 1234567-wpts.gpx
- static File getWaypointsFileForGpx(File file) {
- final String name = file.getName();
- if (StringUtils.endsWithIgnoreCase(name, GPX_FILE_EXTENSION) && (StringUtils.length(name) > GPX_FILE_EXTENSION.length())) {
- final String wptsName = StringUtils.substringBeforeLast(name, ".") + WAYPOINTS_FILE_SUFFIX_AND_EXTENSION;
- return new File(file.getParentFile(), wptsName);
- } else {
- return null;
- }
- }
}
diff --git a/main/src/cgeo/geocaching/files/LocParser.java b/main/src/cgeo/geocaching/files/LocParser.java
index 5baaeac..e21b2c2 100644
--- a/main/src/cgeo/geocaching/files/LocParser.java
+++ b/main/src/cgeo/geocaching/files/LocParser.java
@@ -1,12 +1,9 @@
package cgeo.geocaching.files;
-import cgeo.geocaching.R;
import cgeo.geocaching.Settings;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgCacheWrap;
import cgeo.geocaching.cgCoord;
-import cgeo.geocaching.cgSearch;
-import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.geopoint.GeopointParser;
@@ -16,8 +13,12 @@ import org.apache.commons.lang3.StringUtils;
import android.os.Handler;
import android.util.Log;
-import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
@@ -39,6 +40,8 @@ public final class LocParser extends FileParser {
.compile("<container>([^<]+)</container>");
private static final Pattern patternName = Pattern.compile("CDATA\\[([^\\]]+)\\]");
+ private int listId;
+
public static void parseLoc(final cgCacheWrap caches,
final String fileContent) {
final Map<String, cgCoord> cidCoords = parseCoordinates(fileContent);
@@ -64,7 +67,7 @@ public final class LocParser extends FileParser {
}
}
- public static Map<String, cgCoord> parseCoordinates(
+ static Map<String, cgCoord> parseCoordinates(
final String fileContent) {
final Map<String, cgCoord> coords = new HashMap<String, cgCoord>();
if (StringUtils.isBlank(fileContent)) {
@@ -137,36 +140,31 @@ public final class LocParser extends FileParser {
return coords;
}
- public static cgSearch parseLoc(File file, int listId,
- Handler handler) {
- final cgSearch search = new cgSearch();
-
- try {
- final Map<String, cgCoord> coords = parseCoordinates(readFile(file).toString());
- final cgCacheWrap caches = new cgCacheWrap();
- for (Entry<String, cgCoord> entry : coords.entrySet()) {
- cgCoord coord = entry.getValue();
- if (StringUtils.isBlank(coord.getGeocode()) || StringUtils.isBlank(coord.getName())) {
- continue;
- }
- cgCache cache = new cgCache();
- copyCoordToCache(coord, cache);
- caches.cacheList.add(cache);
-
- fixCache(cache);
- cache.setCacheType(CacheType.UNKNOWN); // type is not given in the LOC file
- cache.setReason(listId);
- cache.setDetailed(true);
+ public LocParser(int listId) {
+ this.listId = listId;
+ }
- cgeoapplication.getInstance().addCacheToSearch(search, cache);
+ @Override
+ public Collection<cgCache> parse(InputStream stream, Handler progressHandler) throws IOException, ParserException {
+ // TODO: progress reporting happens during reading stream only, not during parsing
+ String streamContent = readStream(stream, progressHandler).toString();
+ final Map<String, cgCoord> coords = parseCoordinates(streamContent);
+ final List<cgCache> caches = new ArrayList<cgCache>();
+ for (Entry<String, cgCoord> entry : coords.entrySet()) {
+ cgCoord coord = entry.getValue();
+ if (StringUtils.isBlank(coord.getGeocode()) || StringUtils.isBlank(coord.getName())) {
+ continue;
}
- caches.totalCnt = caches.cacheList.size();
- showCountMessage(handler, R.string.gpx_import_loading_stored, search.getCount());
- Log.i(Settings.tag, "Caches found in .loc file: " + caches.totalCnt);
- } catch (Exception e) {
- Log.e(Settings.tag, "LocParser.parseLoc: " + e.toString());
+ cgCache cache = new cgCache();
+ copyCoordToCache(coord, cache);
+ caches.add(cache);
+
+ fixCache(cache);
+ cache.setCacheType(CacheType.UNKNOWN); // type is not given in the LOC file
+ cache.setReason(listId);
+ cache.setDetailed(true);
}
-
- return search;
+ Log.i(Settings.tag, "Caches found in .loc file: " + caches.size());
+ return caches;
}
}
diff --git a/main/src/cgeo/geocaching/files/ParserException.java b/main/src/cgeo/geocaching/files/ParserException.java
new file mode 100644
index 0000000..5aa152c
--- /dev/null
+++ b/main/src/cgeo/geocaching/files/ParserException.java
@@ -0,0 +1,24 @@
+package cgeo.geocaching.files;
+
+/**
+ * Exception indicating that a FileParser (GPX or LOC) could not parse the file due to bad file format.
+ */
+public class ParserException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ public ParserException() {
+ }
+
+ public ParserException(String detailMessage) {
+ super(detailMessage);
+ }
+
+ public ParserException(Throwable throwable) {
+ super(throwable);
+ }
+
+ public ParserException(String detailMessage, Throwable throwable) {
+ super(detailMessage, throwable);
+ }
+
+}
diff --git a/tests/res/raw/gc31j2h_err.gpx b/tests/res/raw/gc31j2h_err.gpx
new file mode 100644
index 0000000..2c41bb2
--- /dev/null
+++ b/tests/res/raw/gc31j2h_err.gpx
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<gpx xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" creator="Groundspeak Pocket Query" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0 http://www.groundspeak.com/cache/1/0/cache.xsd" xmlns="http://www.topografix.com/GPX/1/0">
+ <name>Testdata</name>
+ <desc>Geocache file generated by Groundspeak</desc>
+ <author>Groundspeak</author>
+ <email>contact@groundspeak.com</email>
+ <time>2011-09-16T21:13:25.1723847Z</time>
+ <keywords>cache, geocache, groundspeak</keywords>
+ <bounds minlat="49.3187" minlon="8.54565" maxlat="49.3187" maxlon="8.54565" />
+ <wpt lat="49.3187" lon="8.54565">
+ <time>2011-08-05T07:00:00Z</time>
+ <name>GC31J2H</name>
+ <desc>Hockenheimer City-Brunnen by vptsz, Multi-cache (2/1)</desc>
+ <url>http://www.geocaching.com/seek/cache_details.aspx?guid=0eba627b-bc4c-4e37-9bae-80dad5b97815</url>
+ <urlname>Hockenheimer City-Brunnen</urlname>
+ <sym>Geocache Found</sym>
+ <type>Geocache|Multi-cache</type>
diff --git a/tests/src/cgeo/geocaching/cgeogpxesTest.java b/tests/src/cgeo/geocaching/cgeogpxesTest.java
index de2cc29..90ce201 100644
--- a/tests/src/cgeo/geocaching/cgeogpxesTest.java
+++ b/tests/src/cgeo/geocaching/cgeogpxesTest.java
@@ -1,25 +1,189 @@
package cgeo.geocaching;
-import cgeo.geocaching.cgeogpxes;
+import cgeo.geocaching.test.R;
-import android.test.AndroidTestCase;
+import android.os.Handler;
+import android.os.Message;
+import android.test.ActivityInstrumentationTestCase2;
-public class cgeogpxesTest extends AndroidTestCase {
- private cgeogpxes cgeogpxes = new cgeogpxes();
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class cgeogpxesTest extends ActivityInstrumentationTestCase2<cgeogpxes> {
+ private int listId;
+ private cgeogpxes importGpxActivity = new cgeogpxes();
+ private File tempDir;
+ private TestHandler importStepHandler = new TestHandler();
+ private TestHandler progressHandler = new TestHandler();
+
+ public cgeogpxesTest() {
+ super("cgeo.geocaching", cgeogpxes.class);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ tempDir = new File(System.getProperty("java.io.tmpdir"), "cgeogpxesTest");
+ tempDir.mkdir();
+
+ // workaround to get storage initialized
+ cgeoapplication.getInstance().getAllHistoricCachesCount();
+ listId = cgeoapplication.getInstance().createList("cgeogpxesTest");
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ cgeoapplication.getInstance().dropStored(listId);
+ cgeoapplication.getInstance().removeList(listId);
+ deleteDirectory(tempDir);
+ super.tearDown();
+ }
+
+
+ private void copyResourceToFile(int resourceId, File file) throws IOException {
+ final InputStream is = getInstrumentation().getContext().getResources().openRawResource(resourceId);
+ final FileOutputStream os = new FileOutputStream(file);
+
+ try {
+ byte[] buffer = new byte[4096];
+ int byteCount;
+ while ((byteCount = is.read(buffer)) >= 0) {
+ os.write(buffer, 0, byteCount);
+ }
+ } finally {
+ os.close();
+ is.close();
+ }
+ }
+
+ private void deleteDirectory(File dir) {
+ for (File f : dir.listFiles()) {
+ if (f.isFile()) {
+ f.delete();
+ } else if (f.isDirectory()) {
+ deleteDirectory(f);
+ }
+ }
+ dir.delete();
+ }
+
+ static class TestHandler extends Handler {
+ List<Message> messages = new ArrayList<Message>();
+
+ @Override
+ public void handleMessage(Message msg) {
+ Message msg1 = new Message();
+ msg1.copyFrom(msg);
+ messages.add(msg1);
+ }
+ }
public void testFileNameMatches() {
- assertTrue(cgeogpxes.filenameBelongsToList("1234567.gpx"));
- assertTrue(cgeogpxes.filenameBelongsToList("1234567.GPX"));
- assertTrue(cgeogpxes.filenameBelongsToList(".gpx"));
- assertTrue(cgeogpxes.filenameBelongsToList("1234567.loc"));
- assertTrue(cgeogpxes.filenameBelongsToList("1234567.LOC"));
+ assertTrue(importGpxActivity.filenameBelongsToList("1234567.gpx"));
+ assertTrue(importGpxActivity.filenameBelongsToList("1234567.GPX"));
+ assertTrue(importGpxActivity.filenameBelongsToList(".gpx"));
+ assertTrue(importGpxActivity.filenameBelongsToList("1234567.loc"));
+ assertTrue(importGpxActivity.filenameBelongsToList("1234567.LOC"));
- assertFalse(cgeogpxes.filenameBelongsToList("1234567.gpy"));
- assertFalse(cgeogpxes.filenameBelongsToList("1234567.agpx"));
- assertFalse(cgeogpxes.filenameBelongsToList("1234567"));
- assertFalse(cgeogpxes.filenameBelongsToList(""));
- assertFalse(cgeogpxes.filenameBelongsToList("gpx"));
+ assertFalse(importGpxActivity.filenameBelongsToList("1234567.gpy"));
+ assertFalse(importGpxActivity.filenameBelongsToList("1234567.agpx"));
+ assertFalse(importGpxActivity.filenameBelongsToList("1234567"));
+ assertFalse(importGpxActivity.filenameBelongsToList(""));
+ assertFalse(importGpxActivity.filenameBelongsToList("gpx"));
- assertFalse(cgeogpxes.filenameBelongsToList("1234567-wpts.gpx"));
+ assertFalse(importGpxActivity.filenameBelongsToList("1234567-wpts.gpx"));
}
+
+ public void testGetWaypointsFileForGpx() {
+ assertEquals(new File("1234567-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("1234567.gpx")));
+ assertEquals(new File("/mnt/sdcard/1234567-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("/mnt/sdcard/1234567.gpx")));
+ assertEquals(new File("/mnt/sdcard/1-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("/mnt/sdcard/1.gpx")));
+ assertEquals(new File("/mnt/sd.card/1-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("/mnt/sd.card/1.gpx")));
+ assertEquals(new File("1234567.9-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("1234567.9.gpx")));
+ assertEquals(new File("1234567-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("1234567.GPX")));
+ assertEquals(new File("gpx.gpx-wpts.gpx"), cgeogpxes.getWaypointsFileForGpx(new File("gpx.gpx.gpx")));
+ assertNull(cgeogpxes.getWaypointsFileForGpx(new File("123.gpy")));
+ assertNull(cgeogpxes.getWaypointsFileForGpx(new File("gpx")));
+ assertNull(cgeogpxes.getWaypointsFileForGpx(new File(".gpx")));
+ assertNull(cgeogpxes.getWaypointsFileForGpx(new File("/mnt/sdcard/.gpx")));
+ }
+
+ public void testImportGpx() throws IOException {
+ File gc31j2h = new File(tempDir, "gc31j2h.gpx");
+ copyResourceToFile(R.raw.gc31j2h, gc31j2h);
+
+ cgeogpxes.ImportGpxFileThread importThread = new cgeogpxes.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler);
+ importThread.run();
+
+ assertEquals(3, importStepHandler.messages.size());
+ assertEquals(cgeogpxes.IMPORT_STEP_READ_FILE, importStepHandler.messages.get(0).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_STORE_CACHES, importStepHandler.messages.get(1).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_FINISHED, importStepHandler.messages.get(2).what);
+ cgSearch search = (cgSearch) importStepHandler.messages.get(2).obj;
+ assertEquals(Collections.singletonList("GC31J2H"), search.getGeocodes());
+
+ cgCache cache = cgeoapplication.getInstance().getCacheByGeocode("GC31J2H");
+ assertNotNull(cache);
+
+ // can't assert, for whatever reason the waypoints are remembered in DB
+ // assertNull(cache.waypoints);
+ }
+
+ public void testImportGpxWithWaypoints() throws IOException {
+ File gc31j2h = new File(tempDir, "gc31j2h.gpx");
+ copyResourceToFile(R.raw.gc31j2h, gc31j2h);
+ copyResourceToFile(R.raw.gc31j2h_wpts, new File(tempDir, "gc31j2h-wpts.gpx"));
+
+ cgeogpxes.ImportGpxFileThread importThread = new cgeogpxes.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler);
+ importThread.run();
+
+ assertEquals(4, importStepHandler.messages.size());
+ assertEquals(cgeogpxes.IMPORT_STEP_READ_FILE, importStepHandler.messages.get(0).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_READ_WPT_FILE, importStepHandler.messages.get(1).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_STORE_CACHES, importStepHandler.messages.get(2).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_FINISHED, importStepHandler.messages.get(3).what);
+ cgSearch search = (cgSearch) importStepHandler.messages.get(3).obj;
+ assertEquals(Collections.singletonList("GC31J2H"), search.getGeocodes());
+
+ cgCache cache = cgeoapplication.getInstance().getCacheByGeocode("GC31J2H");
+ assertNotNull(cache);
+ assertEquals(2, cache.getWaypoints().size());
+ }
+
+ public void testImportLoc() throws IOException {
+ File oc5952 = new File(tempDir, "oc5952.loc");
+ copyResourceToFile(R.raw.oc5952_loc, oc5952);
+
+ cgeogpxes.ImportLocFileThread importThread = new cgeogpxes.ImportLocFileThread(oc5952, listId, importStepHandler, progressHandler);
+ importThread.run();
+
+ assertEquals(3, importStepHandler.messages.size());
+ assertEquals(cgeogpxes.IMPORT_STEP_READ_FILE, importStepHandler.messages.get(0).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_STORE_CACHES, importStepHandler.messages.get(1).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_FINISHED, importStepHandler.messages.get(2).what);
+ cgSearch search = (cgSearch) importStepHandler.messages.get(2).obj;
+ assertEquals(Collections.singletonList("OC5952"), search.getGeocodes());
+
+ cgCache cache = cgeoapplication.getInstance().getCacheByGeocode("OC5952");
+ assertNotNull(cache);
+ }
+
+ public void testImportGpxError() throws IOException {
+ File gc31j2h = new File(tempDir, "gc31j2h.gpx");
+ copyResourceToFile(R.raw.gc31j2h_err, gc31j2h);
+
+ cgeogpxes.ImportGpxFileThread importThread = new cgeogpxes.ImportGpxFileThread(gc31j2h, listId, importStepHandler, progressHandler);
+ importThread.run();
+
+ assertEquals(2, importStepHandler.messages.size());
+ assertEquals(cgeogpxes.IMPORT_STEP_READ_FILE, importStepHandler.messages.get(0).what);
+ assertEquals(cgeogpxes.IMPORT_STEP_FINISHED_WITH_ERROR, importStepHandler.messages.get(1).what);
+ }
+
}
diff --git a/tests/src/cgeo/geocaching/files/GPXParserTest.java b/tests/src/cgeo/geocaching/files/GPXParserTest.java
index bc795e2..c3e253a 100644
--- a/tests/src/cgeo/geocaching/files/GPXParserTest.java
+++ b/tests/src/cgeo/geocaching/files/GPXParserTest.java
@@ -14,7 +14,6 @@ import android.content.res.Resources;
import android.os.Handler;
import android.test.InstrumentationTestCase;
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
@@ -30,7 +29,7 @@ public class GPXParserTest extends InstrumentationTestCase {
testGPXVersion(R.raw.gc1bkp3_gpx100);
}
- private cgCache testGPXVersion(final int resourceId) throws IOException {
+ private cgCache testGPXVersion(final int resourceId) throws IOException, ParserException {
final List<cgCache> caches = readGPX(resourceId);
assertNotNull(caches);
assertEquals(1, caches.size());
@@ -51,13 +50,13 @@ public class GPXParserTest extends InstrumentationTestCase {
return cache;
}
- public void testGPXVersion101() throws IOException {
+ public void testGPXVersion101() throws IOException, ParserException {
final cgCache cache = testGPXVersion(R.raw.gc1bkp3_gpx101);
assertNotNull(cache.getAttributes());
assertEquals(10, cache.getAttributes().size());
}
- public void testOC() throws IOException {
+ public void testOC() throws IOException, ParserException {
final List<cgCache> caches = readGPX(R.raw.oc5952_gpx);
final cgCache cache = caches.get(0);
assertEquals("OC5952", cache.getGeocode());
@@ -74,7 +73,7 @@ public class GPXParserTest extends InstrumentationTestCase {
assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(cache.getCoords()));
}
- public void testGc31j2h() throws IOException {
+ public void testGc31j2h() throws IOException, ParserException {
final List<cgCache> caches = readGPX(R.raw.gc31j2h);
assertEquals(1, caches.size());
final cgCache cache = caches.get(0);
@@ -86,7 +85,7 @@ public class GPXParserTest extends InstrumentationTestCase {
assertNull(cache.getWaypoints());
}
- public void testGc31j2hWpts() throws IOException {
+ public void testGc31j2hWpts() throws IOException, ParserException {
List<cgCache> caches = readGPX(R.raw.gc31j2h, R.raw.gc31j2h_wpts);
assertEquals(1, caches.size());
cgCache cache = caches.get(0);
@@ -94,7 +93,7 @@ public class GPXParserTest extends InstrumentationTestCase {
assertGc31j2hWaypoints(cache);
}
- public void testGc31j2hWptsWithoutCache() throws IOException {
+ public void testGc31j2hWptsWithoutCache() throws IOException, ParserException {
final List<cgCache> caches = readGPX(R.raw.gc31j2h_wpts);
assertEquals(0, caches.size());
}
@@ -175,33 +174,20 @@ public class GPXParserTest extends InstrumentationTestCase {
assertEquals(8.545100, wp.getCoords().getLongitude(), 0.000001);
}
- public static void testGetWaypointsFileForGpx() {
- assertEquals(new File("1234567-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("1234567.gpx")));
- assertEquals(new File("/mnt/sdcard/1234567-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("/mnt/sdcard/1234567.gpx")));
- assertEquals(new File("/mnt/sdcard/1-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("/mnt/sdcard/1.gpx")));
- assertEquals(new File("/mnt/sd.card/1-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("/mnt/sd.card/1.gpx")));
- assertEquals(new File("1234567.9-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("1234567.9.gpx")));
- assertEquals(new File("1234567-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("1234567.GPX")));
- assertEquals(new File("gpx.gpx-wpts.gpx"), GPXParser.getWaypointsFileForGpx(new File("gpx.gpx.gpx")));
- assertNull(GPXParser.getWaypointsFileForGpx(new File("123.gpy")));
- assertNull(GPXParser.getWaypointsFileForGpx(new File("gpx")));
- assertNull(GPXParser.getWaypointsFileForGpx(new File(".gpx")));
- assertNull(GPXParser.getWaypointsFileForGpx(new File("/mnt/sdcard/.gpx")));
- }
-
- private List<cgCache> readGPX(int... resourceIds) throws IOException {
+ private List<cgCache> readGPX(int... resourceIds) throws IOException, ParserException {
final GPX10Parser parser = new GPX10Parser(1);
+ Collection<cgCache> caches = null;
for (int resourceId : resourceIds) {
final Resources res = getInstrumentation().getContext().getResources();
final InputStream instream = res.openRawResource(resourceId);
try {
- assertTrue(parser.parse(instream, new Handler()));
+ caches = parser.parse(instream, new Handler());
+ assertNotNull(caches);
} finally {
instream.close();
}
}
- Collection<cgCache> caches = parser.getParsedCaches();
- assertNotNull(caches);
+
List<cgCache> cacheList = new ArrayList<cgCache>(caches);
// TODO: may need to sort by geocode when a test imports more than one cache
return cacheList;
diff --git a/tests/src/cgeo/geocaching/files/LocParserTest.java b/tests/src/cgeo/geocaching/files/LocParserTest.java
index 6e74061..6fa8182 100644
--- a/tests/src/cgeo/geocaching/files/LocParserTest.java
+++ b/tests/src/cgeo/geocaching/files/LocParserTest.java
@@ -1,64 +1,59 @@
package cgeo.geocaching.files;
-import cgeo.geocaching.cgCoord;
+import cgeo.geocaching.cgCache;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.test.R;
import android.content.res.Resources;
+import android.os.Handler;
import android.test.InstrumentationTestCase;
import java.io.IOException;
import java.io.InputStream;
-import java.util.Map;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
public class LocParserTest extends InstrumentationTestCase {
- private Map<String, cgCoord> readLoc(int resourceId) {
- Map<String, cgCoord> caches = null;
+ private List<cgCache> readLoc(int resourceId) throws IOException, ParserException {
+ LocParser parser = new LocParser(1);
+ Collection<cgCache> caches = null;
final Resources res = getInstrumentation().getContext().getResources();
final InputStream instream = res.openRawResource(resourceId);
try {
- final StringBuilder buffer = new StringBuilder();
- int ch;
- while ((ch = instream.read()) != -1) {
- buffer.append((char) ch);
- }
- caches = LocParser.parseCoordinates(buffer.toString());
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ caches = parser.parse(instream, new Handler());
+ assertNotNull(caches);
+ assertTrue(caches.size() > 0);
} finally {
- try {
- instream.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ instream.close();
}
- assertNotNull(caches);
- assertTrue(caches.size() > 0);
- return caches;
- }
- public void testOCLoc() {
- final Map<String, cgCoord> coords = readLoc(R.raw.oc5952_loc);
- final cgCoord coord = coords.get("OC5952");
- assertNotNull(coord);
- assertEquals("OC5952", coord.getGeocode());
- assertEquals("Die Schatzinsel / treasure island", coord.getName());
- assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(coord.getCoords()));
+ List<cgCache> cacheList = new ArrayList<cgCache>(caches);
+ // TODO: may need to sort by geocode when a test imports more than one cache
+ return cacheList;
}
- public void testGCLoc() {
- final Map<String, cgCoord> coords = readLoc(R.raw.gc1bkp3_loc);
- final cgCoord coord = coords.get("GC1BKP3");
- assertNotNull(coord);
- assertEquals("GC1BKP3", coord.getGeocode());
- assertEquals("Die Schatzinsel / treasure island", coord.getName());
- assertTrue(new Geopoint(48.859683, 9.1874).isEqualTo(coord.getCoords()));
- assertEquals(1.0f, coord.getDifficulty().floatValue());
- assertEquals(5.0f, coord.getTerrain().floatValue());
- assertEquals(CacheSize.MICRO, coord.getSize());
+ public void testOCLoc() throws IOException, ParserException {
+ final List<cgCache> caches = readLoc(R.raw.oc5952_loc);
+ assertEquals(1, caches.size());
+ final cgCache cache = caches.get(0);
+ assertNotNull(cache);
+ assertEquals("OC5952", cache.getGeocode());
+ assertEquals("Die Schatzinsel / treasure island", cache.getName());
+ assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(cache.getCoords()));
}
+ public void testGCLoc() throws IOException, ParserException {
+ final List<cgCache> caches = readLoc(R.raw.gc1bkp3_loc);
+ assertEquals(1, caches.size());
+ final cgCache cache = caches.get(0);
+ assertNotNull(cache);
+ assertEquals("GC1BKP3", cache.getGeocode());
+ assertEquals("Die Schatzinsel / treasure island", cache.getName());
+ assertTrue(new Geopoint(48.859683, 9.1874).isEqualTo(cache.getCoords()));
+ assertEquals(1.0f, cache.getDifficulty().floatValue());
+ assertEquals(5.0f, cache.getTerrain().floatValue());
+ assertEquals(CacheSize.MICRO, cache.getSize());
+ }
}