code format

This commit is contained in:
Steffen Horlacher
2010-05-23 11:21:27 +02:00
parent 98b67dcc28
commit 2b56acf164
3 changed files with 127 additions and 122 deletions
@@ -950,46 +950,46 @@ public class MyTracks extends TabActivity implements OnTouchListener,
showDialogSafely(DIALOG_IMPORT_PROGRESS); showDialogSafely(DIALOG_IMPORT_PROGRESS);
Thread t = new Thread() { Thread t = new Thread() {
@Override @Override
public void run() { public void run() {
int message = R.string.success; int message = R.string.success;
long[] trackIdsImported = null; long[] trackIdsImported = null;
try { try {
try { try {
InputStream is = new FileInputStream(fileName); InputStream is = new FileInputStream(fileName);
trackIdsImported = GpxSaxImporter.importGPXFile(is, providerUtils); trackIdsImported = GpxSaxImporter.importGPXFile(is, providerUtils);
} catch (SAXException e) { } catch (SAXException e) {
Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e);
message = R.string.error_generic; message = R.string.error_generic;
} catch (ParserConfigurationException e) { } catch (ParserConfigurationException e) {
Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e);
message = R.string.error_generic; message = R.string.error_generic;
} catch (IOException e) { } catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e);
message = R.string.error_unable_to_read_file; message = R.string.error_unable_to_read_file;
} catch (NullPointerException e) { } catch (NullPointerException e) {
Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e);
message = R.string.error_invalid_gpx_format; message = R.string.error_invalid_gpx_format;
} catch (OutOfMemoryError e) { } catch (OutOfMemoryError e) {
Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e);
message = R.string.error_out_of_memory; message = R.string.error_out_of_memory;
} }
if (trackIdsImported != null && trackIdsImported.length > 0) { if (trackIdsImported != null && trackIdsImported.length > 0) {
// select last track from import file // select last track from import file
setSelectedTrack(trackIdsImported[trackIdsImported.length -1]); setSelectedTrack(trackIdsImported[trackIdsImported.length - 1]);
} else { } else {
MyTracks.this.showMessageDialog(message, false/*success*/); MyTracks.this.showMessageDialog(message, false/* success */);
} }
} finally { } finally {
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {
public void run() { public void run() {
dismissDialog(DIALOG_IMPORT_PROGRESS); dismissDialog(DIALOG_IMPORT_PROGRESS);
} }
}); });
} }
} }
}; };
t.start(); t.start();
} }
@@ -112,11 +112,10 @@ public class GpxSaxImporter extends DefaultHandler {
private boolean isCurrentTrackRollbackable; private boolean isCurrentTrackRollbackable;
private MyTracksProviderUtils providerUtils; private MyTracksProviderUtils providerUtils;
/** /**
* flag to indicate if we in a track xml element * flag to indicate if we in a track xml element some sub elements like name
* some sub elements like name may be used in other * may be used in other parts of the gpx file - ignore them
* parts of the gpx file - ignore them
*/ */
private boolean isInTrackElement; private boolean isInTrackElement;
@@ -124,34 +123,42 @@ public class GpxSaxImporter extends DefaultHandler {
* Reads GPS tracks from a GPX file and append tracks and their coordinates to * Reads GPS tracks from a GPX file and append tracks and their coordinates to
* the given list of tracks. * the given list of tracks.
* *
* Callers must execute <pre>rollbackUnfinishedTrack</pre> in case of * Callers must execute
* an exception to avoid inconsistent data *
* <pre>
* rollbackUnfinishedTrack
* </pre>
*
* in case of an exception to avoid inconsistent data
* *
* @param tracks * @param tracks
* a list of tracks * a list of tracks
* @param is * @param is
* a input steam with gpx-xml data * a input steam with gpx-xml data
* @throws SAXException a parsing error * @throws SAXException
* @throws ParserConfigurationException internal error * a parsing error
* @throws IOException a file reading problem * @throws ParserConfigurationException
* internal error
* @throws IOException
* a file reading problem
*/ */
public static long[] importGPXFile( public static long[] importGPXFile(final InputStream is,
final InputStream is,final MyTracksProviderUtils providerUtils) final MyTracksProviderUtils providerUtils)
throws ParserConfigurationException, SAXException, IOException { throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParserFactory factory = SAXParserFactory.newInstance();
GpxSaxImporter handler = new GpxSaxImporter(providerUtils); GpxSaxImporter handler = new GpxSaxImporter(providerUtils);
SAXParser parser = factory.newSAXParser(); SAXParser parser = factory.newSAXParser();
long[] trackIds = null; long[] trackIds = null;
try{ try {
parser.parse(is, handler); parser.parse(is, handler);
trackIds = handler.getImportedTrackIds(); trackIds = handler.getImportedTrackIds();
} finally { } finally {
// delete track if not finished // delete track if not finished
handler.rollbackUnfinishedTracks(); handler.rollbackUnfinishedTracks();
} }
return trackIds; return trackIds;
} }
@@ -163,7 +170,7 @@ public class GpxSaxImporter extends DefaultHandler {
tracksWritten = new ArrayList<Long>(); tracksWritten = new ArrayList<Long>();
content = new StringBuilder(); content = new StringBuilder();
} }
@Override @Override
public void characters(char[] ch, int start, int length) throws SAXException { public void characters(char[] ch, int start, int length) throws SAXException {
content.append(ch, start, length); content.append(ch, start, length);
@@ -176,17 +183,16 @@ public class GpxSaxImporter extends DefaultHandler {
if (localName.equalsIgnoreCase(TAG_TRACK)) { if (localName.equalsIgnoreCase(TAG_TRACK)) {
isInTrackElement = true; isInTrackElement = true;
onTrackElementStart(); onTrackElementStart();
// process this element only as sub-elements of track // process this element only as sub-elements of track
} else if(isInTrackElement) { } else if (isInTrackElement) {
if (localName.equalsIgnoreCase(TAG_TRACK_POINT)) { if (localName.equalsIgnoreCase(TAG_TRACK_POINT)) {
onTrackPointElementStart(attributes); onTrackPointElementStart(attributes);
} }
} }
} }
@Override @Override
public void endElement(String uri, String localName, String name) public void endElement(String uri, String localName, String name)
throws SAXException { throws SAXException {
@@ -194,10 +200,10 @@ public class GpxSaxImporter extends DefaultHandler {
if (localName.equalsIgnoreCase(TAG_TRACK)) { if (localName.equalsIgnoreCase(TAG_TRACK)) {
onTrackElementEnd(); onTrackElementEnd();
isInTrackElement = false; isInTrackElement = false;
// process these elements only as sub-elements of track // process these elements only as sub-elements of track
} else if(isInTrackElement) { } else if (isInTrackElement) {
if (localName.equalsIgnoreCase(TAG_TRACK_POINT)) { if (localName.equalsIgnoreCase(TAG_TRACK_POINT)) {
onTrackPointElementEnd(); onTrackPointElementEnd();
} else if (localName.equalsIgnoreCase(TAG_ALTITUDE)) { } else if (localName.equalsIgnoreCase(TAG_ALTITUDE)) {
@@ -259,7 +265,6 @@ public class GpxSaxImporter extends DefaultHandler {
return loc; return loc;
} }
private void onDescriptionElementEnd() { private void onDescriptionElementEnd() {
track.setDescription(content.toString().trim()); track.setDescription(content.toString().trim());
} }
@@ -272,25 +277,26 @@ public class GpxSaxImporter extends DefaultHandler {
* Track point finished, write in database * Track point finished, write in database
*/ */
private void onTrackPointElementEnd() { private void onTrackPointElementEnd() {
if (MyTracksUtils.isValidLocation(location)) { if (MyTracksUtils.isValidLocation(location)) {
stats.addLocation(location, location.getTime()); stats.addLocation(location, location.getTime());
// insert in db // insert in db
Uri trackPointIdUri = providerUtils.insertTrackPoint(location, track.getId()); Uri trackPointIdUri = providerUtils.insertTrackPoint(location, track
.getId());
// set start and stop id for track // set start and stop id for track
long trackPointId = Long.parseLong(trackPointIdUri.getLastPathSegment()); long trackPointId = Long.parseLong(trackPointIdUri.getLastPathSegment());
// first track point? // first track point?
if(lastLocation == null) { if (lastLocation == null) {
track.setStartId(trackPointId); track.setStartId(trackPointId);
} }
// location has no setId method // location has no setId method
// updating stop id on track every time... // updating stop id on track every time...
track.setStopId(trackPointId); track.setStopId(trackPointId);
lastLocation = location; lastLocation = location;
numberOfLocations++; numberOfLocations++;
} }
@@ -300,9 +306,9 @@ public class GpxSaxImporter extends DefaultHandler {
* Track finished - update in database * Track finished - update in database
*/ */
private void onTrackElementEnd() { private void onTrackElementEnd() {
if (lastLocation != null) { if (lastLocation != null) {
// Calculate statistics for the imported track and update // Calculate statistics for the imported track and update
stats.pauseAt(lastLocation.getTime()); stats.pauseAt(lastLocation.getTime());
track.setStopTime(lastLocation.getTime()); track.setStopTime(lastLocation.getTime());
@@ -310,9 +316,9 @@ public class GpxSaxImporter extends DefaultHandler {
stats.fillStatisticsForTrack(track); stats.fillStatisticsForTrack(track);
providerUtils.updateTrack(track); providerUtils.updateTrack(track);
tracksWritten.add(new Long(track.getId())); tracksWritten.add(new Long(track.getId()));
} else { } else {
// track contains no track points makes not really // track contains no track points makes not really
// sense to import it as we have no location // sense to import it as we have no location
// information -> roll back // information -> roll back
@@ -321,18 +327,17 @@ public class GpxSaxImporter extends DefaultHandler {
isCurrentTrackRollbackable = false; isCurrentTrackRollbackable = false;
} }
/** /**
* setting time and doing additional calculations * setting time and doing additional calculations as this is the last value
* as this is the last value required. Also sets the * required. Also sets the start time for track and statistics as there is no
* start time for track and statistics as there is * start time in the track root element
* no start time in the track root element
*/ */
private void onTimeElementEnd() { private void onTimeElementEnd() {
long time = parseTimeForAllFormats(content.toString().trim()); long time = parseTimeForAllFormats(content.toString().trim());
if(location != null) { if (location != null) {
location.setTime(time); location.setTime(time);
// initialize start time with time of first track point // initialize start time with time of first track point
if (stats == null) { if (stats == null) {
@@ -355,16 +360,16 @@ public class GpxSaxImporter extends DefaultHandler {
} }
private void onAltitudeElementEnd() { private void onAltitudeElementEnd() {
if(location != null) { if (location != null) {
String altitude = content.toString().trim(); String altitude = content.toString().trim();
// make altitude optional // make altitude optional
if(altitude != null){ if (altitude != null) {
location.setAltitude(Double.parseDouble(altitude)); location.setAltitude(Double.parseDouble(altitude));
} }
} }
} }
/** /**
* If a exception is thrown during the import callers must execute this method * If a exception is thrown during the import callers must execute this method
* in the catch clause to avoid inconsistent data * in the catch clause to avoid inconsistent data
@@ -35,10 +35,10 @@ import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory;
* @author Steffen (steffen.horlacher@gmail.com) * @author Steffen (steffen.horlacher@gmail.com)
*/ */
public class GpxImporterTest extends AndroidTestCase { public class GpxImporterTest extends AndroidTestCase {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd'T'hh:mm:ss'Z'"); "yyyy-MM-dd'T'hh:mm:ss'Z'");
private static final String TRACK_NAME = "blablub"; private static final String TRACK_NAME = "blablub";
private static final String TRACK_DESC = "s'Laebe isch koi Schlotzer"; private static final String TRACK_DESC = "s'Laebe isch koi Schlotzer";
@@ -54,22 +54,25 @@ public class GpxImporterTest extends AndroidTestCase {
private static final String TRACK_TIME_2 = "2010-04-22T18:21:50Z"; private static final String TRACK_TIME_2 = "2010-04-22T18:21:50Z";
// TODO use real files from different sources with more track points // TODO use real files from different sources with more track points
private static final String VALID_TEST_GPX = private static final String VALID_TEST_GPX = "<gpx><trk><name><![CDATA["
"<gpx><trk><name><![CDATA[" + TRACK_NAME + "]]></name><desc><![CDATA[" + TRACK_DESC + "]]></desc><trkseg>" + + TRACK_NAME + "]]></name><desc><![CDATA[" + TRACK_DESC
"<trkpt lat=\"" + TRACK_LAT_1 + "\" lon=\"" + TRACK_LON_1 + "\"><ele>" + TRACK_ELE_1 + "</ele><time>" + TRACK_TIME_1 + "</time></trkpt> +" + + "]]></desc><trkseg>" + "<trkpt lat=\"" + TRACK_LAT_1 + "\" lon=\""
"<trkpt lat=\"" + TRACK_LAT_2 + "\" lon=\"" + TRACK_LON_2 + "\"><ele>" + TRACK_ELE_2 + "</ele><time>" + TRACK_TIME_2 + "</time></trkpt>" + + TRACK_LON_1 + "\"><ele>" + TRACK_ELE_1 + "</ele><time>" + TRACK_TIME_1
"</trkseg></trk></gpx>"; + "</time></trkpt> +" + "<trkpt lat=\"" + TRACK_LAT_2 + "\" lon=\""
+ TRACK_LON_2 + "\"><ele>" + TRACK_ELE_2 + "</ele><time>" + TRACK_TIME_2
+ "</time></trkpt>" + "</trkseg></trk></gpx>";
// invalid xml // invalid xml
private static final String INVALID_TEST_GPX = VALID_TEST_GPX.substring(0,VALID_TEST_GPX.length() - 50); private static final String INVALID_TEST_GPX = VALID_TEST_GPX.substring(0,
VALID_TEST_GPX.length() - 50);
private static final long TRACK_ID = 1; private static final long TRACK_ID = 1;
private static final long TRACK_POINT_ID = 1; private static final long TRACK_POINT_ID = 1;
private static final Uri TRACK_ID_URI = private static final Uri TRACK_ID_URI = ContentUris.appendId(
ContentUris.appendId( TracksColumns.CONTENT_URI.buildUpon(), TRACK_ID).build(); TracksColumns.CONTENT_URI.buildUpon(), TRACK_ID).build();
private static final Uri TRACK_POINT_ID_URI = private static final Uri TRACK_POINT_ID_URI = ContentUris.appendId(
ContentUris.appendId( TrackPointsColumns.CONTENT_URI.buildUpon(), TRACK_POINT_ID).build(); TrackPointsColumns.CONTENT_URI.buildUpon(), TRACK_POINT_ID).build();
private MyTracksProviderUtils providerUtils; private MyTracksProviderUtils providerUtils;
@@ -98,17 +101,15 @@ public class GpxImporterTest extends AndroidTestCase {
Capture<Location> locParam = new Capture<Location>(); Capture<Location> locParam = new Capture<Location>();
Capture<Long> idParam = new Capture<Long>(); Capture<Long> idParam = new Capture<Long>();
expect( expect(providerUtils.insertTrack(capture(trackParam))).andReturn(
providerUtils.insertTrack(capture(trackParam))) TRACK_ID_URI);
.andReturn(TRACK_ID_URI);
expect(providerUtils.insertTrackPoint(capture(locParam), capture(idParam)))
expect( .andReturn(TRACK_POINT_ID_URI);
providerUtils.insertTrackPoint(capture(locParam),capture(idParam)))
.andReturn(TRACK_POINT_ID_URI);
expectLastCall().times(2); expectLastCall().times(2);
providerUtils.updateTrack(capture(trackParam)); providerUtils.updateTrack(capture(trackParam));
replay(providerUtils); replay(providerUtils);
InputStream is = new ByteArrayInputStream(VALID_TEST_GPX.getBytes()); InputStream is = new ByteArrayInputStream(VALID_TEST_GPX.getBytes());
@@ -120,40 +121,39 @@ public class GpxImporterTest extends AndroidTestCase {
Track track = trackParam.getValue(); Track track = trackParam.getValue();
assertEquals(TRACK_NAME, track.getName()); assertEquals(TRACK_NAME, track.getName());
assertEquals(TRACK_DESC, track.getDescription()); assertEquals(TRACK_DESC, track.getDescription());
assertEquals(DATE_FORMAT.parse(TRACK_TIME_1).getTime(), track.getStartTime()); assertEquals(DATE_FORMAT.parse(TRACK_TIME_1).getTime(), track
.getStartTime());
assertNotSame(-1, track.getStartId()); assertNotSame(-1, track.getStartId());
assertNotSame(-1, track.getStopId()); assertNotSame(-1, track.getStopId());
// verify last location parameter // verify last location parameter
Location loc = locParam.getValue(); Location loc = locParam.getValue();
assertEquals(Double.parseDouble(TRACK_LAT_2),loc.getLatitude()); assertEquals(Double.parseDouble(TRACK_LAT_2), loc.getLatitude());
assertEquals(Double.parseDouble(TRACK_LON_2),loc.getLongitude()); assertEquals(Double.parseDouble(TRACK_LON_2), loc.getLongitude());
assertEquals(Double.parseDouble(TRACK_ELE_2),loc.getAltitude()); assertEquals(Double.parseDouble(TRACK_ELE_2), loc.getAltitude());
assertEquals(DATE_FORMAT.parse(TRACK_TIME_2).getTime(), loc.getTime()); assertEquals(DATE_FORMAT.parse(TRACK_TIME_2).getTime(), loc.getTime());
} }
/** /**
* Test if created track will be deleted on * Test if created track will be deleted on parsing errors
* parsing errors
*/ */
public void testImportFailure() throws ParserConfigurationException, public void testImportFailure() throws ParserConfigurationException,
SAXException, IOException { SAXException, IOException {
expect(providerUtils.insertTrack((Track) EasyMock.anyObject())).andReturn(
TRACK_ID_URI);
expect( expect(
providerUtils.insertTrack((Track) EasyMock.anyObject())).andReturn(TRACK_ID_URI); providerUtils.insertTrackPoint((Location) EasyMock.anyObject(),
expect(
providerUtils.insertTrackPoint(
(Location) EasyMock.anyObject(),
EasyMock.anyLong())).andReturn(TRACK_POINT_ID_URI); EasyMock.anyLong())).andReturn(TRACK_POINT_ID_URI);
expectLastCall().anyTimes(); expectLastCall().anyTimes();
providerUtils.deleteTrack(TRACK_ID); providerUtils.deleteTrack(TRACK_ID);
replay(providerUtils); replay(providerUtils);
InputStream is = new ByteArrayInputStream(INVALID_TEST_GPX.getBytes()); InputStream is = new ByteArrayInputStream(INVALID_TEST_GPX.getBytes());
try { try {
GpxSaxImporter.importGPXFile(is, providerUtils); GpxSaxImporter.importGPXFile(is, providerUtils);
} catch (SAXException e) { } catch (SAXException e) {