code
stringlengths
3
1.18M
language
stringclasses
1 value
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.data.Geocache; import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper; public class LocationSaver { private final CacheWriter mCacheWriter; private final Database mDatabase; private final SQLiteWrapper mSQLiteWrapper; public LocationSaver(Database database, SQLiteWrapper sqliteWrapper, CacheWriter cacheWriter) { mDatabase = database; mSQLiteWrapper = sqliteWrapper; mCacheWriter = cacheWriter; } public void saveLocation(Geocache geocache) { mSQLiteWrapper.openWritableDatabase(mDatabase); // TODO: catch errors on open mCacheWriter.startWriting(); mCacheWriter.insertAndUpdateCache(geocache.getId(), geocache.getName(), geocache .getLatitude(), geocache.getLongitude(), geocache.getSourceType(), geocache .getSourceName()); mCacheWriter.stopWriting(); mSQLiteWrapper.close(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.R; import com.google.code.geobeagle.gpx.GpxAndZipFiles; import com.google.code.geobeagle.gpx.IGpxReader; import com.google.code.geobeagle.gpx.GpxAndZipFiles.GpxAndZipFilesIter; import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.ui.ErrorDisplayer; import java.io.FileNotFoundException; import java.io.IOException; public class ImportThreadDelegate { public static class ImportThreadHelper { private final ErrorDisplayer mErrorDisplayer; private final GpxLoader mGpxLoader; private final MessageHandler mMessageHandler; public ImportThreadHelper(GpxLoader gpxLoader, MessageHandler messageHandler, ErrorDisplayer errorDisplayer) { mErrorDisplayer = errorDisplayer; mGpxLoader = gpxLoader; mMessageHandler = messageHandler; } public void cleanup() { mMessageHandler.loadComplete(); } public void end() { mGpxLoader.end(); } public boolean processFile(IGpxReader iGpxFile) { String filename = iGpxFile.getFilename(); try { mGpxLoader.open(filename, iGpxFile.open()); if (!mGpxLoader.load()) return false; return true; } catch (final FileNotFoundException e) { mErrorDisplayer.displayError(R.string.error_opening_file, filename); } catch (Exception e) { mErrorDisplayer.displayErrorAndStack(e); } return false; } public boolean start(boolean hasNext) { if (!hasNext) { mErrorDisplayer.displayError(R.string.error_no_gpx_files); return false; } mGpxLoader.start(); return true; } } private final GpxAndZipFiles mGpxAndZipFiles; private ImportThreadHelper mImportThreadHelper; private ErrorDisplayer mErrorDisplayer; public ImportThreadDelegate(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) { mGpxAndZipFiles = gpxAndZipFiles; mImportThreadHelper = importThreadHelper; mErrorDisplayer = errorDisplayer; } public void run() { try { tryRun(); } catch (Exception e) { mErrorDisplayer.displayErrorAndStack(e); } finally { mImportThreadHelper.cleanup(); } } protected void tryRun() throws IOException { GpxAndZipFilesIter gpxFileIter = mGpxAndZipFiles.iterator(); if (gpxFileIter == null) { mErrorDisplayer.displayError(R.string.error_cant_read_sd); return; } if (!mImportThreadHelper.start(gpxFileIter.hasNext())) return; while (gpxFileIter.hasNext()) { if (!mImportThreadHelper.processFile(gpxFileIter.next())) return; } mImportThreadHelper.end(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class Database { public static interface ISQLiteDatabase { void beginTransaction(); int countResults(String table, String sql, String... args); void endTransaction(); void execSQL(String s, Object... bindArg1); public Cursor query(String table, String[] columns, String selection, String groupBy, String having, String orderBy, String limit, String... selectionArgs); void setTransactionSuccessful(); } public static class OpenHelperDelegate { public void onCreate(ISQLiteDatabase db) { db.execSQL(SQL_CREATE_CACHE_TABLE); db.execSQL(SQL_CREATE_GPX_TABLE); db.execSQL(SQL_CREATE_IDX_LATITUDE); db.execSQL(SQL_CREATE_IDX_LONGITUDE); db.execSQL(SQL_CREATE_IDX_SOURCE); } public void onUpgrade(ISQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 9) { db.execSQL(SQL_DROP_CACHE_TABLE); db.execSQL(SQL_CREATE_CACHE_TABLE); db.execSQL(SQL_CREATE_IDX_LATITUDE); db.execSQL(SQL_CREATE_IDX_LONGITUDE); db.execSQL(SQL_CREATE_IDX_SOURCE); } if (oldVersion == 9) { db.execSQL(SQL_CACHES_ADD_COLUMN); } if (oldVersion < 10) { db.execSQL(SQL_CREATE_GPX_TABLE); } } } public static final String DATABASE_NAME = "GeoBeagle.db"; public static final int DATABASE_VERSION = 10; public static final String[] READER_COLUMNS = new String[] { "Latitude", "Longitude", "Id", "Description", "Source" }; public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1"; public static final String S0_INTENT = "intent"; public static final String SQL_CACHES_ADD_COLUMN = "ALTER TABLE CACHES ADD COLUMN " + S0_COLUMN_DELETE_ME; public static final String SQL_CACHES_DONT_DELETE_ME = "UPDATE CACHES SET DeleteMe = 0 WHERE Source = ?"; public static final String SQL_CLEAR_CACHES = "DELETE FROM CACHES WHERE Source=?"; public static final String SQL_CREATE_CACHE_TABLE = "CREATE TABLE CACHES (" + "Id VARCHAR PRIMARY KEY, Description VARCHAR, " + "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ")"; public static final String SQL_CREATE_GPX_TABLE = "CREATE TABLE GPX (" + "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL)"; public static final String SQL_CREATE_IDX_LATITUDE = "CREATE INDEX IDX_LATITUDE on CACHES (Latitude)"; public static final String SQL_CREATE_IDX_LONGITUDE = "CREATE INDEX IDX_LONGITUDE on CACHES (Longitude)"; public static final String SQL_CREATE_IDX_SOURCE = "CREATE INDEX IDX_SOURCE on CACHES (Source)"; public static final String SQL_DELETE_CACHE = "DELETE FROM CACHES WHERE Id=?"; public static final String SQL_DELETE_OLD_CACHES = "DELETE FROM CACHES WHERE DeleteMe = 1"; public static final String SQL_DELETE_OLD_GPX = "DELETE FROM GPX WHERE DeleteMe = 1"; public static final String SQL_DROP_CACHE_TABLE = "DROP TABLE IF EXISTS CACHES"; public static final String SQL_GPX_DONT_DELETE_ME = "UPDATE GPX SET DeleteMe = 0 WHERE Name = ?"; public static final String SQL_MATCH_NAME_AND_EXPORTED_LATER = "Name = ? AND ExportTime >= ?"; public static final String SQL_REPLACE_CACHE = "REPLACE INTO CACHES " + "(Id, Description, Latitude, Longitude, Source, DeleteMe) VALUES (?, ?, ?, ?, ?, 0)"; public static final String SQL_REPLACE_GPX = "REPLACE INTO GPX (Name, ExportTime, DeleteMe) VALUES (?, ?, 0)"; public static final String SQL_RESET_DELETE_ME_CACHES = "UPDATE CACHES SET DeleteMe = 1 WHERE Source != '" + S0_INTENT + "'"; public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1"; public static final String TBL_CACHES = "CACHES"; public static final String TBL_GPX = "GPX"; private final SQLiteOpenHelper mSqliteOpenHelper; Database(SQLiteOpenHelper sqliteOpenHelper) { mSqliteOpenHelper = sqliteOpenHelper; } public SQLiteDatabase getReadableDatabase() { return mSqliteOpenHelper.getReadableDatabase(); } public SQLiteDatabase getWritableDatabase() { return mSqliteOpenHelper.getWritableDatabase(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.io.GpxToCacheDI.XmlPullParserWrapper; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; public class GpxToCache { @SuppressWarnings("serial") public static class CancelException extends Exception { } private boolean mAbort; private final EventHelper mEventHelper; private final XmlPullParserWrapper mXmlPullParserWrapper; GpxToCache(XmlPullParserWrapper xmlPullParserWrapper, EventHelper eventHelper) { mXmlPullParserWrapper = xmlPullParserWrapper; mEventHelper = eventHelper; } public void abort() { mAbort = true; } public String getSource() { return mXmlPullParserWrapper.getSource(); } /** * @return false if this file has already been loaded. * @throws XmlPullParserException * @throws IOException * @throws CancelException */ public boolean load() throws XmlPullParserException, IOException, CancelException { int eventType; for (eventType = mXmlPullParserWrapper.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = mXmlPullParserWrapper .next()) { if (mAbort) throw new CancelException(); // File already loaded. if (!mEventHelper.handleEvent(eventType)) return true; } // Pick up END_DOCUMENT event as well. mEventHelper.handleEvent(eventType); return false; } public void open(String source, Reader reader) throws XmlPullParserException, IOException { mXmlPullParserWrapper.open(source, reader); mEventHelper.reset(); mAbort = false; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.LocationControl; import com.google.code.geobeagle.data.Geocache; import com.google.code.geobeagle.data.Geocaches; import com.google.code.geobeagle.io.CacheReader.CacheReaderCursor; import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper; import java.util.ArrayList; public class GeocachesSql { private final CacheReader mCacheReader; private final Database mDatabase; private final Geocaches mGeocaches; private final LocationControl mLocationControl; private final SQLiteWrapper mSQLiteWrapper; GeocachesSql(CacheReader cacheReader, Geocaches geocaches, Database database, SQLiteWrapper sqliteWrapper, LocationControl locationControl) { mCacheReader = cacheReader; mGeocaches = geocaches; mDatabase = database; mSQLiteWrapper = sqliteWrapper; mLocationControl = locationControl; } public int getCount() { mSQLiteWrapper.openWritableDatabase(mDatabase); int count = mCacheReader.getTotalCount(); mSQLiteWrapper.close(); return count; } public ArrayList<Geocache> getGeocaches() { return mGeocaches.getAll(); } public void loadNearestCaches() { // TODO: This has to be writable for upgrade to work; we should open one // readable and one writable at the activity level, and then pass it // down. mSQLiteWrapper.openWritableDatabase(mDatabase); CacheReaderCursor cursor = mCacheReader.open(mLocationControl.getLocation()); if (cursor != null) { read(cursor); cursor.close(); } mSQLiteWrapper.close(); } public void read(CacheReaderCursor cursor) { mGeocaches.clear(); do { mGeocaches.add(cursor.getCache()); } while (cursor.moveToNext()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import java.io.IOException; public class GpxEventHandler { public static final String XPATH_GPXNAME = "/gpx/name"; public static final String XPATH_GPXTIME = "/gpx/time"; public static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name"; public static final String XPATH_HINT = "/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints"; public static final String XPATH_LOGDATE = "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date"; public static final String[] XPATH_PLAINLINES = { "/gpx/wpt/desc", "/gpx/wpt/groundspeak:cache/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:container", "/gpx/wpt/groundspeak:cache/groundspeak:short_description", "/gpx/wpt/groundspeak:cache/groundspeak:long_description", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text" }; public static final String XPATH_SYM = "/gpx/wpt/sym"; public static final String XPATH_WPT = "/gpx/wpt"; public static final String XPATH_WPTNAME = "/gpx/wpt/name"; private final CachePersisterFacade mCachePersisterFacade; public GpxEventHandler(CachePersisterFacade cachePersisterFacade) { mCachePersisterFacade = cachePersisterFacade; } public void endTag(String previousFullPath) throws IOException { if (previousFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.endTag(); } } public void startTag(String mFullPath, GpxToCacheDI.XmlPullParserWrapper mXmlPullParser) { if (mFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.wpt(mXmlPullParser); } } public boolean text(String mFullPath, String text) throws IOException { text = text.trim(); if (mFullPath.equals(XPATH_WPTNAME)) { mCachePersisterFacade.wptName(text); } else if (mFullPath.equals(XPATH_GPXNAME)) { mCachePersisterFacade.gpxName(text); } else if (mFullPath.equals(XPATH_GPXTIME)) { return mCachePersisterFacade.gpxTime(text); } else if (mFullPath.equals(XPATH_GROUNDSPEAKNAME)) { mCachePersisterFacade.groundspeakName(text); } else if (mFullPath.equals(XPATH_LOGDATE)) { mCachePersisterFacade.logDate(text); } else if (mFullPath.equals(XPATH_SYM)) { mCachePersisterFacade.symbol(text); } else if (mFullPath.equals(XPATH_HINT)) { if (!text.equals("")) { mCachePersisterFacade.hint(text); } } else { for (String writeLineMatch : XPATH_PLAINLINES) { if (mFullPath.equals(writeLineMatch)) { mCachePersisterFacade.line(text); return true; } } } return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import java.io.IOException; public class CacheDetailsWriter { public static final String GEOBEAGLE_DIR = "/sdcard/GeoBeagle"; private final HtmlWriter mHtmlWriter; private String mLatitude; private String mLongitude; public CacheDetailsWriter(HtmlWriter htmlWriter) { mHtmlWriter = htmlWriter; } void close() throws IOException { mHtmlWriter.writeFooter(); mHtmlWriter.close(); } public void latitudeLongitude(String latitude, String longitude) { mLatitude = latitude; mLongitude = longitude; } public void open(String wpt) throws IOException { mHtmlWriter.open(CacheDetailsWriter.GEOBEAGLE_DIR + "/" + wpt + ".html"); } public void writeHint(String text) throws IOException { mHtmlWriter.write("<br />Hint: <font color=gray>" + text + "</font>"); } void writeLine(String text) throws IOException { mHtmlWriter.write(text); } void writeLogDate(String text) throws IOException { mHtmlWriter.writeSeparator(); mHtmlWriter.write(text); } void writeWptName(String wpt) throws IOException { mHtmlWriter.writeHeader(); mHtmlWriter.write(wpt); mHtmlWriter.write(mLatitude + ", " + mLongitude); mLatitude = mLongitude = null; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.R; import com.google.code.geobeagle.io.GpxToCache.CancelException; import com.google.code.geobeagle.ui.ErrorDisplayer; import org.xmlpull.v1.XmlPullParserException; import android.database.sqlite.SQLiteException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; public class GpxLoader { private final CachePersisterFacade mCachePersisterFacade; private final ErrorDisplayer mErrorDisplayer; private final GpxToCache mGpxToCache; GpxLoader(GpxToCache gpxToCache, CachePersisterFacade cachePersisterFacade, ErrorDisplayer errorDisplayer) { mGpxToCache = gpxToCache; mCachePersisterFacade = cachePersisterFacade; mErrorDisplayer = errorDisplayer; } public void abort() { mGpxToCache.abort(); } public void end() { mCachePersisterFacade.end(); } /** * @return true if we should continue loading more files, false if we should * terminate. */ public boolean load() { boolean markLoadAsComplete = false; boolean continueLoading = false; try { boolean alreadyLoaded = mGpxToCache.load(); markLoadAsComplete = !alreadyLoaded; continueLoading = true; } catch (final SQLiteException e) { mErrorDisplayer.displayError(R.string.error_writing_cache, e.getMessage()); } catch (XmlPullParserException e) { mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage()); } catch (IOException e) { mErrorDisplayer.displayError(R.string.error_reading_file, mGpxToCache.getSource()); } catch (CancelException e) { } mCachePersisterFacade.close(markLoadAsComplete); return continueLoading; } public void open(String path, Reader reader) throws FileNotFoundException, XmlPullParserException, IOException { mGpxToCache.open(path, reader); mCachePersisterFacade.open(path); } public void start() { mCachePersisterFacade.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.io.GpxToCacheDI.XmlPullParserWrapper; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; public class EventHelper { public static class XmlPathBuilder { private String mPath = ""; public void endTag(String currentTag) { mPath = mPath.substring(0, mPath.length() - (currentTag.length() + 1)); } public String getPath() { return mPath; } public void reset() { mPath = ""; } public void startTag(String mCurrentTag) { mPath += "/" + mCurrentTag; } } private final GpxEventHandler mGpxEventHandler; private final XmlPathBuilder mXmlPathBuilder; private final XmlPullParserWrapper mXmlPullParser; public EventHelper(XmlPathBuilder xmlPathBuilder, GpxEventHandler gpxEventHandler, XmlPullParserWrapper xmlPullParser) { mXmlPathBuilder = xmlPathBuilder; mGpxEventHandler = gpxEventHandler; mXmlPullParser = xmlPullParser; } public boolean handleEvent(int eventType) throws IOException { switch (eventType) { case XmlPullParser.START_TAG: mXmlPathBuilder.startTag(mXmlPullParser.getName()); mGpxEventHandler.startTag(mXmlPathBuilder.getPath(), mXmlPullParser); break; case XmlPullParser.END_TAG: mGpxEventHandler.endTag(mXmlPathBuilder.getPath()); mXmlPathBuilder.endTag(mXmlPullParser.getName()); break; case XmlPullParser.TEXT: return mGpxEventHandler.text(mXmlPathBuilder.getPath(), mXmlPullParser.getText()); } return true; } public void reset() { mXmlPathBuilder.reset(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.data.Geocache.Source; import com.google.code.geobeagle.io.Database.ISQLiteDatabase; /** * @author sng */ public class CacheWriter { private final ISQLiteDatabase mSqlite; private final DbToGeocacheAdapter mDbToGeocacheAdapter; public static final String SQLS_CLEAR_EARLIER_LOADS[] = { Database.SQL_DELETE_OLD_CACHES, Database.SQL_DELETE_OLD_GPX, Database.SQL_RESET_DELETE_ME_CACHES, Database.SQL_RESET_DELETE_ME_GPX }; CacheWriter(ISQLiteDatabase sqlite, DbToGeocacheAdapter dbToGeocacheAdapter) { mSqlite = sqlite; mDbToGeocacheAdapter = dbToGeocacheAdapter; } public void clearCaches(String source) { mSqlite.execSQL(Database.SQL_CLEAR_CACHES, source); } /** * Deletes any cache/gpx entries marked delete_me, then marks all remaining * gpx-based caches, and gpx entries with delete_me = 1. */ public void clearEarlierLoads() { for (String sql : CacheWriter.SQLS_CLEAR_EARLIER_LOADS) { mSqlite.execSQL(sql); } } public void deleteCache(CharSequence id) { mSqlite.execSQL(Database.SQL_DELETE_CACHE, id); } public void insertAndUpdateCache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName) { mSqlite.execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude), new Double( longitude), mDbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName)); } public boolean isGpxAlreadyLoaded(String gpxName, String gpxTime) { boolean gpxAlreadyLoaded = mSqlite.countResults(Database.TBL_GPX, Database.SQL_MATCH_NAME_AND_EXPORTED_LATER, gpxName, gpxTime) > 0; if (gpxAlreadyLoaded) { mSqlite.execSQL(Database.SQL_CACHES_DONT_DELETE_ME, gpxName); mSqlite.execSQL(Database.SQL_GPX_DONT_DELETE_ME, gpxName); } return gpxAlreadyLoaded; } public void startWriting() { mSqlite.beginTransaction(); } public void stopWriting() { // TODO: abort if no writes--otherwise sqlite is unhappy. mSqlite.setTransactionSuccessful(); mSqlite.endTransaction(); } public void writeGpx(String gpxName, String pocketQueryExportTime) { mSqlite.execSQL(Database.SQL_REPLACE_GPX, gpxName, pocketQueryExportTime); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.io.CachePersisterFacadeDI.WriterWrapper; import java.io.IOException; public class HtmlWriter { private final WriterWrapper mWriter; public HtmlWriter(WriterWrapper writerWrapper) { mWriter = writerWrapper; } public void close() throws IOException { mWriter.close(); } public void open(String path) throws IOException { mWriter.open(path); } public void write(String text) throws IOException { mWriter.write(text + "<br/>\n"); } public void writeFooter() throws IOException { mWriter.write(" </body>\n"); mWriter.write("</html>\n"); } public void writeHeader() throws IOException { mWriter.write("<html>\n"); mWriter.write(" <body>\n"); } public void writeSeparator() throws IOException { mWriter.write("<hr/>\n"); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.data.Geocache.Source; public class DbToGeocacheAdapter { public Source sourceNameToSourceType(String sourceName) { if (sourceName.equals("intent")) return Source.WEB_URL; else if (sourceName.equals("mylocation")) return Source.MY_LOCATION; return Source.GPX; } public String sourceTypeToSourceName(Source source, String sourceName) { if (source == Source.MY_LOCATION) return "mylocation"; else if (source == Source.WEB_URL) return "intent"; return sourceName; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.io; import com.google.code.geobeagle.io.CachePersisterFacadeDI.FileFactory; import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.io.GpxToCacheDI.XmlPullParserWrapper; import android.os.PowerManager.WakeLock; import java.io.File; import java.io.IOException; public class CachePersisterFacade { public static final int WAKELOCK_DURATION = 5000; private final CacheDetailsWriter mCacheDetailsWriter; private final CacheTagWriter mCacheTagWriter; private final FileFactory mFileFactory; private final MessageHandler mMessageHandler; private final WakeLock mWakeLock; CachePersisterFacade(CacheTagWriter cacheTagWriter, FileFactory fileFactory, CacheDetailsWriter cacheDetailsWriter, MessageHandler messageHandler, WakeLock wakeLock) { mCacheTagWriter = cacheTagWriter; mFileFactory = fileFactory; mCacheDetailsWriter = cacheDetailsWriter; mMessageHandler = messageHandler; mWakeLock = wakeLock; } public void close(boolean success) { mCacheTagWriter.stopWriting(success); } public void end() { mCacheTagWriter.end(); } void endTag() throws IOException { mCacheDetailsWriter.close(); mCacheTagWriter.write(); } public void gpxName(String text) { mCacheTagWriter.gpxName(text); } public boolean gpxTime(String gpxTime) { return mCacheTagWriter.gpxTime(gpxTime); } void groundspeakName(String text) { mMessageHandler.updateName(text); mCacheTagWriter.cacheName(text); } public void hint(String text) throws IOException { mCacheDetailsWriter.writeHint(text); } void line(String text) throws IOException { mCacheDetailsWriter.writeLine(text); } void logDate(String text) throws IOException { mCacheDetailsWriter.writeLogDate(text); } void open(String text) { mMessageHandler.updateSource(text); mCacheTagWriter.startWriting(); mCacheTagWriter.gpxName(text); } void start() { File file = mFileFactory.createFile(CacheDetailsWriter.GEOBEAGLE_DIR); file.mkdirs(); } public void symbol(String text) { mCacheTagWriter.symbol(text); } void wpt(XmlPullParserWrapper mXmlPullParser) { mCacheTagWriter.clear(); String latitude = mXmlPullParser.getAttributeValue(null, "lat"); String longitude = mXmlPullParser.getAttributeValue(null, "lon"); mCacheTagWriter.latitudeLongitude(latitude, longitude); mCacheDetailsWriter.latitudeLongitude(latitude, longitude); } void wptName(String wpt) throws IOException { mCacheDetailsWriter.open(wpt); mCacheDetailsWriter.writeWptName(wpt); mCacheTagWriter.id(wpt); mMessageHandler.updateWaypointId(wpt); mWakeLock.acquire(WAKELOCK_DURATION); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /* * maps.jar doesn't include all its dependencies; fake them out here for testing. */ package android.widget; public class ZoomButtonsController { }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import android.content.ContentValues; import android.database.Cursor; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; class DesktopSQLiteDatabase implements ISQLiteDatabase { DesktopSQLiteDatabase() { File db = new File("GeoBeagle.db"); db.delete(); } @Override public void beginTransaction() { } @Override public void close() { } @Override public int countResults(String table, String sql, String... args) { return 0; } public String dumpSchema() { return DesktopSQLiteDatabase.exec(".schema"); } public String dumpTable(String table) { return DesktopSQLiteDatabase.exec("SELECT * FROM " + table); } @Override public void endTransaction() { } @Override public void execSQL(String s, Object... bindArg1) { if (bindArg1.length > 0) throw new UnsupportedOperationException("bindArgs not yet supported"); System.out.print(DesktopSQLiteDatabase.exec(s)); } @Override public Cursor query(String table, String[] columns, String selection, String groupBy, String having, String orderBy, String limit, String... selectionArgs) { return null; } @Override public Cursor rawQuery(String string, String[] object) { // TODO Auto-generated method stub return null; } @Override public void setTransactionSuccessful() { } @Override public boolean isOpen() { // TODO Auto-generated method stub return false; } @Override public void delete(String table, String where, String bindArg) { exec("DELETE FROM " + table + " WHERE " + where + "='" + bindArg + "'"); } @Override public void insert(String table, String[] columns, Object[] bindArgs) { // Assumes len(bindArgs) > 0. StringBuilder columnsAsString = new StringBuilder(); for (String column : columns) { columnsAsString.append(", "); columnsAsString.append(column); } StringBuilder values = new StringBuilder(); for (Object bindArg : bindArgs) { values.append(", "); values.append("'" + bindArg + "'"); } values.substring(2); exec("REPLACE INTO " + table + "( " + columnsAsString.substring(2) + ") VALUES (" + values.substring(2) + ")"); } @Override public boolean hasValue(String table, String[] columns, String[] selectionArgs) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(" WHERE " + columns[0] + "="); stringBuilder.append("'" + selectionArgs[0] + "'"); for (int ix = 1; ix < columns.length; ix++) { stringBuilder.append(" AND "); stringBuilder.append(columns[ix]); stringBuilder.append("="); stringBuilder.append("'" + selectionArgs[ix] + "'"); } String s = "SELECT COUNT(*) FROM " + table + stringBuilder.toString(); String result = exec(s); return Integer.parseInt(result.trim()) != 0; } /** * <pre> * * version 8 * same as version 7 but rebuilds everything because a released version mistakenly puts * *intent* into imported caches. * * version 9 * fixes bug where INDEX wasn't being created on upgrade. * * version 10 * adds GPX table * * version 11 * adds new CACHES columns: CacheType, Difficulty, Terrain, and Container * * version 12: 4/21/2010 * adds new TAGS table: * </pre> * * @throws IOException */ static String convertStreamToString(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); return sb.toString(); } static String exec(String s) { String output = null; try { ProcessBuilder processBuilder = new ProcessBuilder("sqlite3", "GeoBeagle.db", s); processBuilder.redirectErrorStream(true); InputStream shellIn = null; Process shell = processBuilder.start(); shellIn = shell.getInputStream(); int result = shell.waitFor(); output = DesktopSQLiteDatabase.convertStreamToString(shellIn); if (result != 0) throw (new RuntimeException(output)); } catch (InterruptedException e) { throw (new RuntimeException(e + "\n" + output)); } catch (IOException e) { throw (new RuntimeException(e + "\n" + output)); } return output; } @Override public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { // TODO Auto-generated method stub return null; } @Override public void update(String string, ContentValues contentValues, String whereClause, String[] strings) { // TODO Auto-generated method stub } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass.view; import android.text.Editable; import android.text.InputFilter; class StubEditable implements Editable { private final String mString; public StubEditable(String s) { mString = s; } public Editable append(char arg0) { return null; } public Editable append(CharSequence arg0) { return null; } public Editable append(CharSequence arg0, int arg1, int arg2) { return null; } public char charAt(int index) { return mString.charAt(index); } public void clear() { } public void clearSpans() { } public Editable delete(int arg0, int arg1) { return null; } public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { mString.getChars(srcBegin, srcEnd, dst, dstBegin); } public InputFilter[] getFilters() { return null; } public int getSpanEnd(Object arg0) { return 0; } public int getSpanFlags(Object arg0) { return 0; } public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) { return null; } public int getSpanStart(Object arg0) { return 0; } public Editable insert(int arg0, CharSequence arg1) { return null; } public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) { return null; } public int length() { return mString.length(); } @SuppressWarnings("unchecked") public int nextSpanTransition(int arg0, int arg1, Class arg2) { return 0; } public void removeSpan(Object arg0) { } public Editable replace(int arg0, int arg1, CharSequence arg2) { return null; } public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) { return null; } public void setFilters(InputFilter[] arg0) { } public void setSpan(Object arg0, int arg1, int arg2, int arg3) { } public CharSequence subSequence(int start, int end) { return mString.subSequence(start, end); } @Override public String toString() { return mString; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.MenuItem; import android.view.SubMenu; import android.view.ContextMenu.ContextMenuInfo; public class MenuActionStub implements MenuItem { @Override public char getAlphabeticShortcut() { return 0; } @Override public int getGroupId() { return 0; } @Override public Drawable getIcon() { return null; } @Override public Intent getIntent() { return null; } @Override public int getItemId() { return 7; } @Override public ContextMenuInfo getMenuInfo() { return null; } @Override public char getNumericShortcut() { return 0; } @Override public int getOrder() { return 0; } @Override public SubMenu getSubMenu() { return null; } @Override public CharSequence getTitle() { return null; } @Override public CharSequence getTitleCondensed() { return null; } @Override public boolean hasSubMenu() { return false; } @Override public boolean isCheckable() { return false; } @Override public boolean isChecked() { return false; } @Override public boolean isEnabled() { return false; } @Override public boolean isVisible() { return false; } @Override public MenuItem setAlphabeticShortcut(char alphaChar) { return null; } @Override public MenuItem setCheckable(boolean checkable) { return null; } @Override public MenuItem setChecked(boolean checked) { return null; } @Override public MenuItem setEnabled(boolean enabled) { return null; } @Override public MenuItem setIcon(Drawable icon) { return null; } @Override public MenuItem setIcon(int iconRes) { return null; } @Override public MenuItem setIntent(Intent intent) { return null; } @Override public MenuItem setNumericShortcut(char numericChar) { return null; } @Override public MenuItem setOnMenuItemClickListener( OnMenuItemClickListener menuItemClickListener) { return null; } @Override public MenuItem setShortcut(char numericChar, char alphaChar) { return null; } @Override public MenuItem setTitle(CharSequence title) { return null; } @Override public MenuItem setTitle(int title) { return null; } @Override public MenuItem setTitleCondensed(CharSequence title) { return null; } @Override public MenuItem setVisible(boolean visible) { return null; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.searchonline; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.ActivityRestorer; import com.google.code.geobeagle.activity.MenuActionStub; import android.content.Context; import android.test.ActivityInstrumentationTestCase2; public class SearchOnlineActivityTest extends ActivityInstrumentationTestCase2<SearchOnlineActivity> { public SearchOnlineActivityTest() { super("com.google.code.geobeagle", SearchOnlineActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); } public void testCreate() { final SearchOnlineActivity searchOnlineActivity = getActivity(); assertNotNull(searchOnlineActivity.getDistanceFormatterManager()); assertNotNull(searchOnlineActivity.getGpsWidgetAndUpdater()); assertNotNull(searchOnlineActivity.getCombinedLocationListener()); assertNotNull(searchOnlineActivity.getHelpContentsView()); assertEquals(R.id.help_contents, searchOnlineActivity .getHelpContentsView().getId()); ActivityRestorer activityRestorer = searchOnlineActivity .getActivityRestorer(); assertNotNull(activityRestorer); assertEquals(searchOnlineActivity.getBaseContext() .getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE), activityRestorer.getSharedPreferences()); assertNotNull(searchOnlineActivity.getJsInterface()); final MenuActionStub menuActionStub = new MenuActionStub(); getInstrumentation() .addMonitor(searchOnlineActivity.getClass().getCanonicalName(), null, false); getInstrumentation().runOnMainSync(new Runnable() { public void run() { searchOnlineActivity.onOptionsItemSelected(menuActionStub); } }); getInstrumentation().waitForIdleSync(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import android.app.Instrumentation; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.Smoke; import android.view.KeyEvent; public class GeoBeagleActivityTest extends ActivityInstrumentationTestCase2<GeoBeagle> { private GeoBeagle geoBeagle; private Instrumentation instrumentation; public GeoBeagleActivityTest() { super("com.google.code.geobeagle", GeoBeagle.class); } @Override protected void setUp() throws Exception { super.setUp(); geoBeagle = getActivity(); instrumentation = getInstrumentation(); } @Override protected void tearDown() throws Exception { super.tearDown(); getActivity().finish(); } @Smoke public void testCreate() { assertNotNull(geoBeagle.locationControlBuffered); assertNotNull(geoBeagle.activitySaver); getInstrumentation().waitForIdleSync(); } @Smoke public void testMenuSettings() throws InterruptedException { instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER); Thread.sleep(2000); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } public void testMenuCacheList() throws InterruptedException { instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER); Thread.sleep(2000); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.R; import org.easymock.EasyMock; import android.app.Instrumentation; import android.test.ActivityInstrumentationTestCase2; import android.view.KeyEvent; import android.view.MenuItem; public class CacheListActivityTest extends ActivityInstrumentationTestCase2<CacheListActivity> { private CacheListActivity cacheListActivity; private Instrumentation instrumentation; private MenuItem item; public CacheListActivityTest() { super("com.google.code.geobeagle", CacheListActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); instrumentation = getInstrumentation(); item = EasyMock.createMock(MenuItem.class); cacheListActivity = getActivity(); } public void testAddMyLocation() throws InterruptedException { EasyMock.expect(item.getItemId()).andReturn( R.string.menu_add_my_location); EasyMock.replay(item); cacheListActivity.onOptionsItemSelected(item); EasyMock.verify(item); instrumentation.waitForIdleSync(); Thread.sleep(2000); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } public void testSearchOnline() throws InterruptedException { EasyMock.expect(item.getItemId()) .andReturn(R.string.menu_search_online); EasyMock.replay(item); cacheListActivity.onOptionsItemSelected(item); EasyMock.verify(item); instrumentation.waitForIdleSync(); Thread.sleep(2000); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } public void testShowMap() throws InterruptedException { EasyMock.expect(item.getItemId()).andReturn(R.string.menu_map); EasyMock.replay(item); cacheListActivity.onOptionsItemSelected(item); EasyMock.verify(item); instrumentation.waitForIdleSync(); Thread.sleep(2000); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } public void testShowAllCaches() throws InterruptedException { instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_LEFT); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER); Thread.sleep(2000); } public void testSync() { EasyMock.expect(item.getItemId()).andReturn(R.string.menu_sync); EasyMock.replay(item); cacheListActivity.onOptionsItemSelected(item); EasyMock.verify(item); instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); instrumentation.waitForIdleSync(); } }
Java
package roboguice.util; import roboguice.inject.ContextScope; import android.content.Context; import android.os.Handler; import com.google.inject.Inject; import com.google.inject.Provider; import java.util.concurrent.ThreadFactory; /** * Allows injection to happen for tasks that execute in a background thread. * * @param <ResultT> */ public abstract class RoboAsyncTask<ResultT> extends SafeAsyncTask<ResultT> { @Inject static protected Provider<Context> contextProvider; @Inject static protected Provider<ContextScope> scopeProvider; protected ContextScope scope = scopeProvider.get(); protected Context context = contextProvider.get(); protected RoboAsyncTask() { } protected RoboAsyncTask(Handler handler) { super(handler); } protected RoboAsyncTask(Handler handler, ThreadFactory threadFactory) { super(handler, threadFactory); } protected RoboAsyncTask(ThreadFactory threadFactory) { super(threadFactory); } @Override protected Task<ResultT> newTask() { return new RoboTask<ResultT>(this); } protected class RoboTask<ResultT> extends SafeAsyncTask.Task<ResultT> { public RoboTask(SafeAsyncTask parent) { super(parent); } @Override protected ResultT doCall() throws Exception { try { scope.enter(context); return super.doCall(); } finally { scope.exit(context); } } } }
Java
package roboguice.util; import roboguice.inject.ContextScope; import android.content.Context; import com.google.inject.Inject; import com.google.inject.Provider; /** * An extension to {@link Thread} which propogates the current * Context to the background thread. * * Current limitations: any parameters set in the RoboThread are * ignored other than Runnable. This means that priorities, groups, * names, etc. won't be honored. Yet. */ public class RoboThread extends Thread { @Inject static public Provider<Context> contextProvider; @Inject static protected Provider<ContextScope> scopeProvider; public RoboThread() { } public RoboThread(Runnable runnable) { super(runnable); } @Override public void start() { final ContextScope scope = scopeProvider.get(); final Context context = contextProvider.get(); // BUG any parameters set in the RoboThread are ignored other than Runnable. // This means that priorities, groups, names, etc. won't be honored. Yet. new Thread() { @Override public void run() { try { scope.enter(context); RoboThread.this.run(); } finally { scope.exit(context); } } }.start(); } }
Java
package roboguice.util; import android.os.Handler; import android.util.Log; import java.util.concurrent.*; /** * A class similar but unrelated to android's {@link android.os.AsyncTask}. * * Unlike AsyncTask, this class properly propagates exceptions. * * If you're familiar with AsyncTask and are looking for {@link android.os.AsyncTask#doInBackground(Object[])}, * we've named it {@link #call()} here to conform with java 1.5's {@link java.util.concurrent.Callable} interface. * * Current limitations: does not yet handle progress, although it shouldn't be * hard to add. * * @param <ResultT> */ public abstract class SafeAsyncTask<ResultT> implements Callable<ResultT> { protected Handler handler; protected ThreadFactory threadFactory; protected FutureTask<Void> future = new FutureTask<Void>( newTask() ); public SafeAsyncTask() { this.handler = new Handler(); this.threadFactory = Executors.defaultThreadFactory(); } public SafeAsyncTask( Handler handler ) { this.handler = handler; this.threadFactory = Executors.defaultThreadFactory(); } public SafeAsyncTask( ThreadFactory threadFactory ) { this.handler = new Handler(); this.threadFactory = threadFactory; } public SafeAsyncTask( Handler handler, ThreadFactory threadFactory ) { this.handler = handler; this.threadFactory = threadFactory; } public void execute() { threadFactory.newThread( future ).start(); } public boolean cancel( boolean mayInterruptIfRunning ) { return future != null && future.cancel(mayInterruptIfRunning); } /** * @throws Exception, captured on passed to onException() if present. */ protected void onPreExecute() throws Exception {} /** * @param t the result of {@link #call()} * @throws Exception, captured on passed to onException() if present. */ @SuppressWarnings({"UnusedDeclaration"}) protected void onSuccess( ResultT t ) throws Exception {} /** * Called when the thread has been interrupted, likely because * the task was canceled. * * By default, calls {@link #onException(Exception)}, but this method * may be overridden to handle interruptions differently than other * exceptions. * * @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)} */ protected void onInterrupted( InterruptedException e ) { onException(e); } /** * Logs the exception as an Error by default, but this method may * be overridden by subclasses. * * @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)} * @throws RuntimeException, ignored */ protected void onException( Exception e ) throws RuntimeException { Log.e("roboguice", "Exception caught during background processing", e); } /** * @throws RuntimeException, ignored */ protected void onFinally() throws RuntimeException {} protected Task<ResultT> newTask() { return new Task<ResultT>(this); } protected static class Task<ResultT> implements Callable<Void> { protected SafeAsyncTask<ResultT> parent; public Task(SafeAsyncTask parent) { this.parent = parent; } public Void call() throws Exception { try { doPreExecute(); doSuccess(doCall()); return null; } catch( final Exception e ) { try { doException(e); } catch( Exception f ) { // ignored, throw original instead } throw e; } finally { doFinally(); } } protected void doPreExecute() throws Exception { postToUiThreadAndWait( new Callable<Object>() { public Object call() throws Exception { parent.onPreExecute(); return null; } }); } protected ResultT doCall() throws Exception { return parent.call(); } protected void doSuccess( final ResultT r ) throws Exception { postToUiThreadAndWait( new Callable<Object>() { public Object call() throws Exception { parent.onSuccess(r); return null; } }); } protected void doException( final Exception e ) throws Exception { postToUiThreadAndWait( new Callable<Object>() { public Object call() throws Exception { if( e instanceof InterruptedException ) parent.onInterrupted((InterruptedException)e); else parent.onException(e); return null; } }); } protected void doFinally() throws Exception { postToUiThreadAndWait( new Callable<Object>() { public Object call() throws Exception { parent.onFinally(); return null; } }); } /** * Posts the specified runnable to the UI thread using a handler, * and waits for operation to finish. If there's an exception, * it captures it and rethrows it. * @param c the callable to post * @throws Exception on error */ protected void postToUiThreadAndWait( final Callable c ) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final Exception[] exceptions = new Exception[1]; // Execute onSuccess in the UI thread, but wait // for it to complete. // If it throws an exception, capture that exception // and rethrow it later. parent.handler.post( new Runnable() { public void run() { try { c.call(); } catch( Exception e ) { exceptions[0] = e; } finally { latch.countDown(); } } }); // Wait for onSuccess to finish latch.await(); if( exceptions[0] != null ) throw exceptions[0]; } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.inject.Provider; import com.google.inject.matcher.Matchers; import roboguice.config.RoboGuiceModule; import roboguice.inject.ActivityProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScope; import roboguice.inject.ContextScoped; import roboguice.inject.ExtrasListener; import roboguice.inject.ResourceListener; import roboguice.inject.ResourcesProvider; import roboguice.inject.SharedPreferencesProvider; import roboguice.inject.SystemServiceProvider; import roboguice.inject.ViewListener; import android.app.Activity; import android.app.ActivityManager; import android.app.Application; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.location.LocationManager; import android.os.PowerManager; import android.view.LayoutInflater; public class FasterRoboGuiceModule extends RoboGuiceModule { public FasterRoboGuiceModule(ContextScope contextScope, Provider<Context> throwingContextProvider, Provider<Context> contextProvider, ResourceListener resourceListener, ViewListener viewListener, ExtrasListener extrasListener, Application application) { super(contextScope, throwingContextProvider, contextProvider, resourceListener, viewListener, extrasListener, application); } @SuppressWarnings("unchecked") @Override protected void configure() { // Sundry Android Classes bind(Resources.class).toProvider(ResourcesProvider.class); bind(ContentResolver.class).toProvider(ContentResolverProvider.class); for (Class<? extends Object> c = application.getClass(); c != null && Application.class.isAssignableFrom(c); c = c.getSuperclass()) { bind((Class<Object>)c).toInstance(application); } // System Services bind(LocationManager.class).toProvider( new SystemServiceProvider<LocationManager>(Context.LOCATION_SERVICE)); bind(LayoutInflater.class).toProvider( new SystemServiceProvider<LayoutInflater>(Context.LAYOUT_INFLATER_SERVICE)); bind(ActivityManager.class).toProvider( new SystemServiceProvider<ActivityManager>(Context.ACTIVITY_SERVICE)); bind(PowerManager.class).toProvider( new SystemServiceProvider<PowerManager>(Context.POWER_SERVICE)); // Context Scope bindings bindScope(ContextScoped.class, contextScope); bind(ContextScope.class).toInstance(contextScope); bind(Context.class).toProvider(throwingContextProvider).in(ContextScoped.class); bind(Activity.class).toProvider(ActivityProvider.class); // Android Resources, Views and extras require special handling bindListener(new ClassToTypeLiteralMatcherAdapter(Matchers.subclassesOf(Activity.class)), resourceListener); bindListener(new ClassToTypeLiteralMatcherAdapter(Matchers.subclassesOf(Activity.class)), viewListener); bindListener(new ClassToTypeLiteralMatcherAdapter(Matchers.subclassesOf(Activity.class)), extrasListener); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.code.geobeagle.xmlimport.gpx.gpx.GpxFileOpener; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.IOException; /** * @author sng * * Takes a filename and returns an IGpxReaderIter based on the * extension: * * zip: ZipFileIter * gpx/loc: GpxFileIter */ public class GpxFileIterAndZipFileIterFactory { private final Provider<AbortState> mAborterProvider; private final ZipInputFileTester mZipInputFileTester; private final GeoBeagleEnvironment mGeoBeagleEnvironment; @Inject public GpxFileIterAndZipFileIterFactory(ZipInputFileTester zipInputFileTester, Provider<AbortState> aborterProvider, GeoBeagleEnvironment geoBeagleEnvironment) { mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; mGeoBeagleEnvironment = geoBeagleEnvironment; } public IGpxReaderIter fromFile(String filename) throws IOException { String importFolder = mGeoBeagleEnvironment.getImportFolder(); if (filename.endsWith(".zip")) { return new ZipFileOpener(importFolder + filename, new ZipInputStreamFactory(), mZipInputFileTester, mAborterProvider).iterator(); } return new GpxFileOpener(importFolder + filename, mAborterProvider).iterator(); } public void resetAborter() { mAborterProvider.get().reset(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Provider; import com.google.inject.Singleton; import android.util.Log; import java.util.regex.Pattern; @Singleton public class EmotifierPatternProvider implements Provider<Pattern> { static Pattern createEmotifierPattern(String[] emoticons) { StringBuffer keysBuffer = new StringBuffer(); String escapeChars = "()|?}^"; for (String emoticon : emoticons) { String key = new String(emoticon); for (int i = 0; i < escapeChars.length(); i++) { char c = escapeChars.charAt(i); key = key.replaceAll("\\" + String.valueOf(c), "\\\\" + c); } keysBuffer.append("|" + key); } keysBuffer.deleteCharAt(0); final String keys = "\\[(" + keysBuffer.toString() + ")\\]"; try { return Pattern.compile(keys); } catch (Exception e) { Log.d("GeoBeagle", e.getLocalizedMessage()); } return null; } private Pattern pattern; @Override public Pattern get() { if (pattern != null) return pattern; String emoticons[] = { ":(", ":o)", ":)", ":D", "8D", ":I", ":P", "}:)", ":)", ":D", "8D", ":I", ":P", "}:)", ";)", "B)", "8", ":)", "8)", ":O", ":(!", "xx(", "|)", ":X", "V", "?", "^" }; pattern = createEmotifierPattern(emoticons); return pattern; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.bcaching.communication; import org.json.JSONException; import org.json.JSONObject; class BCachingListFactory { public BCachingList create(String s) throws BCachingException { try { return new BCachingList(new BCachingJSONObject(new JSONObject(s))); } catch (JSONException e) { throw new BCachingException("Error parsing data from bcaching server: " + e.getLocalizedMessage()); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.bcaching; import com.google.code.geobeagle.database.ClearCachesFromSource; import com.google.code.geobeagle.database.ClearCachesFromSourceNull; import com.google.inject.Provides; import roboguice.config.AbstractAndroidModule; import roboguice.util.RoboThread; import android.os.PowerManager; import android.os.PowerManager.WakeLock; public class BCachingModule extends AbstractAndroidModule { public static final String BCACHING_INITIAL_MESSAGE = "Getting cache count..."; @Provides WakeLock wakeLockProvider(PowerManager powerManager) { return powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Importing"); } @Override protected void configure() { bind(ClearCachesFromSource.class).to(ClearCachesFromSourceNull.class); requestStaticInjection(RoboThread.class); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.bcaching; import com.google.code.geobeagle.bcaching.communication.BCachingCommunication; import com.google.code.geobeagle.bcaching.communication.BCachingException; import com.google.inject.Inject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Hashtable; public class BufferedReaderFactory { private final BCachingCommunication bcachingCommunication; @Inject BufferedReaderFactory(BCachingCommunication bcachingCommunication) { this.bcachingCommunication = bcachingCommunication; } public BufferedReader create(Hashtable<String, String> params) throws BCachingException { InputStream inputStream = bcachingCommunication.sendRequest(params); return new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")), 8192); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.code.geobeagle.activity.compass.NullRefresher; import com.google.inject.Provides; import roboguice.config.AbstractAndroidModule; import roboguice.inject.SystemServiceProvider; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.preference.PreferenceManager; // TODO rename to GeoBeagleModule public class GeoBeaglePackageModule extends AbstractAndroidModule { @Provides public SharedPreferences providesDefaultSharedPreferences(Context context) { return PreferenceManager.getDefaultSharedPreferences(context); } @Provides AlertDialog.Builder providesAlertDialogBuilder(Activity activity) { return new AlertDialog.Builder(activity); } @Override protected void configure() { bind(Refresher.class).to(NullRefresher.class); bind(SensorManager.class).toProvider( new SystemServiceProvider<SensorManager>(Context.SENSOR_SERVICE)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import java.util.Hashtable; public class CacheTypeFactory { private final Hashtable<Integer, CacheType> mCacheTypes = new Hashtable<Integer, CacheType>(CacheType.values().length); public CacheTypeFactory() { for (CacheType cacheType : CacheType.values()) mCacheTypes.put(cacheType.toInt(), cacheType); } public CacheType fromInt(int i) { return mCacheTypes.get(i); } public CacheType fromTag(String tag) { String tagLower = tag.toLowerCase(); int longestMatch = 0; CacheType result = CacheType.NULL; for (CacheType cacheType : mCacheTypes.values()) { if (tagLower.contains(cacheType.getTag()) && cacheType.getTag().length() > longestMatch) { result = cacheType; longestMatch = cacheType.getTag().length(); // Necessary to continue the search to find mega-events and // individual waypoint types. } } return result; } public int container(String container) { if (container.equals("Micro")) { return 1; } else if (container.equals("Small")) { return 2; } else if (container.equals("Regular")) { return 3; } else if (container.equals("Large")) { return 4; } else if (container.equals("Other")) { return 5; } return 0; } public int stars(String stars) { try { return Math.round(Float.parseFloat(stars) * 2); } catch (Exception ex) { return 0; } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.location; import com.google.inject.Provides; import android.location.LocationListener; import android.location.LocationManager; import java.util.ArrayList; import roboguice.config.AbstractAndroidModule; public class LocationModule extends AbstractAndroidModule { @Override protected void configure() { } @Provides CombinedLocationManager provideCombinedLocationManager(LocationManager locationManager) { final ArrayList<LocationListener> locationListeners = new ArrayList<LocationListener>(3); return new CombinedLocationManager(locationManager, locationListeners); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.R; import com.google.inject.Provides; import roboguice.config.AbstractAndroidModule; import android.app.Activity; import android.content.Context; import android.view.ViewGroup; import android.widget.LinearLayout; public class GpsStatusWidgetModule extends AbstractAndroidModule { static InflatedGpsStatusWidget inflatedGpsStatusWidgetCacheList; @Override protected void configure() { } @Provides InflatedGpsStatusWidget providesInflatedGpsStatusWidget(Activity activity) { Context context = activity.getApplicationContext(); InflatedGpsStatusWidget searchOnlineWidget = getInflatedGpsStatusWidgetSearchOnline(activity); if (searchOnlineWidget != null) return searchOnlineWidget; return getInflatedGpsStatusWidgetCacheList(context); } InflatedGpsStatusWidget getInflatedGpsStatusWidgetCacheList(Context context) { if (inflatedGpsStatusWidgetCacheList != null) return inflatedGpsStatusWidgetCacheList; inflatedGpsStatusWidgetCacheList = new InflatedGpsStatusWidget(context); LinearLayout inflatedGpsStatusWidgetParent = new LinearLayout(context); inflatedGpsStatusWidgetParent.addView(inflatedGpsStatusWidgetCacheList, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); inflatedGpsStatusWidgetCacheList.setTag(inflatedGpsStatusWidgetParent); return inflatedGpsStatusWidgetCacheList; } InflatedGpsStatusWidget getInflatedGpsStatusWidgetSearchOnline(Activity activity) { return (InflatedGpsStatusWidget)activity.findViewById(R.id.gps_widget_view); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.inject.Provides; import roboguice.config.AbstractAndroidModule; public class DatabaseModule extends AbstractAndroidModule { @Override protected void configure() { } @Provides ISQLiteDatabase sqliteDatabaseProvider(DbFrontend dbFrontend) { return dbFrontend.getDatabase(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpx.zip; import com.google.code.geobeagle.xmlimport.gpx.zip.GpxZipInputStream; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipInputStream; public class ZipInputStreamFactory { public GpxZipInputStream create(String filename) throws IOException { return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream( new FileInputStream(filename)))); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cacheloader; import com.google.code.geobeagle.xmlimport.EventDispatcher; class DetailsXmlToStringFactory { DetailsXmlToString create(EventDispatcher eventDispatcher) { return new DetailsXmlToString(eventDispatcher); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cacheloader; import com.google.code.geobeagle.cachedetails.DetailsDatabaseReader; import com.google.code.geobeagle.xmlimport.CacheXmlTagHandler; import com.google.code.geobeagle.xmlimport.EventDispatcher; import com.google.code.geobeagle.xmlimport.EventDispatcher.EventDispatcherFactory; import com.google.code.geobeagle.xmlimport.EventHandlerGpx; import com.google.inject.Inject; import android.content.res.Resources; public class CacheLoaderFactory { private final DetailsDatabaseReader detailsDatabaseReader; private final DetailsXmlToStringFactory detailsXmlToStringFactory; private final Resources resources; private final EventDispatcherFactory eventDispatcherFactory; @Inject public CacheLoaderFactory(DetailsDatabaseReader detailsDatabaseReader, DetailsXmlToStringFactory detailsXmlToStringFactory, Resources resources, EventDispatcherFactory eventDispatcherFactory) { this.detailsDatabaseReader = detailsDatabaseReader; this.detailsXmlToStringFactory = detailsXmlToStringFactory; this.resources = resources; this.eventDispatcherFactory = eventDispatcherFactory; } public CacheLoader create(CacheXmlTagHandler cacheXmlTagHandler) { EventHandlerGpx eventHandlerGpx = new EventHandlerGpx(cacheXmlTagHandler); EventDispatcher eventDispatcher = eventDispatcherFactory.create(eventHandlerGpx); DetailsXmlToString detailsXmlToString = detailsXmlToStringFactory.create(eventDispatcher); return new CacheLoader(detailsDatabaseReader, detailsXmlToString, resources); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.Geocache.AttributeFormatter; import com.google.code.geobeagle.Geocache.AttributeFormatterImpl; import com.google.code.geobeagle.Geocache.AttributeFormatterNull; import com.google.code.geobeagle.GeocacheFactory.Source.SourceFactory; import com.google.code.geobeagle.activity.compass.GeocacheFromParcelFactory; import android.os.Parcel; import android.os.Parcelable; public class GeocacheFactory { public static class CreateGeocacheFromParcel implements Parcelable.Creator<Geocache> { private final GeocacheFromParcelFactory mGeocacheFromParcelFactory = new GeocacheFromParcelFactory( new GeocacheFactory()); @Override public Geocache createFromParcel(Parcel in) { return mGeocacheFromParcelFactory.create(in); } @Override public Geocache[] newArray(int size) { return new Geocache[size]; } } public static enum Provider { ATLAS_QUEST(0, "LB"), GROUNDSPEAK(1, "GC"), MY_LOCATION(-1, "ML"), OPENCACHING(2, "OC"), GEOCACHING_AU( 3, "GA"), GEOCACHING_WP(4, "TP"); private final int mIx; private final String mPrefix; Provider(int ix, String prefix) { mIx = ix; mPrefix = prefix; } public int toInt() { return mIx; } public String getPrefix() { return mPrefix; } } public static Provider ALL_PROVIDERS[] = { Provider.ATLAS_QUEST, Provider.GROUNDSPEAK, Provider.MY_LOCATION, Provider.OPENCACHING }; public static enum Source { GPX(0), LOC(3), MY_LOCATION(1), WEB_URL(2); public final static int MIN_SOURCE = 0; public final static int MAX_SOURCE = 3; public static class SourceFactory { private final Source mSources[] = new Source[values().length]; public SourceFactory() { for (Source source : values()) mSources[source.toInt()] = source; } public Source fromInt(int i) { return mSources[i]; } } private final int mIx; Source(int ix) { mIx = ix; } public int toInt() { return mIx; } } static class AttributeFormatterFactory { private AttributeFormatterImpl mAttributeFormatterImpl; private AttributeFormatterNull mAttributeFormatterNull; public AttributeFormatterFactory(AttributeFormatterImpl attributeFormatterImpl, AttributeFormatterNull attributeFormatterNull) { mAttributeFormatterImpl = attributeFormatterImpl; mAttributeFormatterNull = attributeFormatterNull; } AttributeFormatter getAttributeFormatter(Source sourceType) { if (sourceType == Source.GPX) return mAttributeFormatterImpl; return mAttributeFormatterNull; } } private static CacheTypeFactory mCacheTypeFactory; private static SourceFactory mSourceFactory; private AttributeFormatterFactory mAttributeFormatterFactory; public GeocacheFactory() { mSourceFactory = new SourceFactory(); mCacheTypeFactory = new CacheTypeFactory(); mAttributeFormatterFactory = new AttributeFormatterFactory(new AttributeFormatterImpl(), new AttributeFormatterNull()); } public CacheType cacheTypeFromInt(int cacheTypeIx) { return mCacheTypeFactory.fromInt(cacheTypeIx); } public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container, boolean available, boolean archived) { if (id.length() < 2) { // ID is missing for waypoints imported from the browser; create a // new id from the time. id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis()); } if (name == null) name = ""; final AttributeFormatter attributeFormatter = mAttributeFormatterFactory .getAttributeFormatter(sourceType); return new Geocache(id, name, latitude, longitude, sourceType, sourceName, cacheType, difficulty, terrain, container, attributeFormatter, available, archived); } public Source sourceFromInt(int sourceIx) { return mSourceFactory.fromInt(sourceIx); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.map.QueryManager.LoaderImpl; import com.google.code.geobeagle.activity.map.click.MapClickIntentFactory; import com.google.inject.Inject; import android.app.Activity; import android.content.res.Resources; import android.util.Log; import java.util.ArrayList; public class CachePinsOverlayFactory { private final CacheItemFactory cacheItemFactory; private CachePinsOverlay cachePinsOverlay; private final Activity activity; private final QueryManager queryManager; private final Resources resources; private final LoaderImpl loaderImpl; private final MapClickIntentFactory mapClickIntentFactory; @Inject public CachePinsOverlayFactory(Activity activity, CacheItemFactory cacheItemFactory, QueryManager queryManager, Resources resources, LoaderImpl loaderImpl, MapClickIntentFactory mapClickIntentFactory) { this.resources = resources; this.activity = activity; this.cacheItemFactory = cacheItemFactory; this.mapClickIntentFactory = mapClickIntentFactory; this.cachePinsOverlay = new CachePinsOverlay(resources, cacheItemFactory, activity, new ArrayList<Geocache>(), mapClickIntentFactory); this.queryManager = queryManager; this.loaderImpl = loaderImpl; } public CachePinsOverlay getCachePinsOverlay() { Log.d("GeoBeagle", "refresh Caches"); Timing timing = new Timing(); GeoMapView geoMapView = (GeoMapView)activity.findViewById(R.id.mapview); Projection projection = geoMapView.getProjection(); GeoPoint newTopLeft = projection.fromPixels(0, 0); GeoPoint newBottomRight = projection.fromPixels(geoMapView.getRight(), geoMapView.getBottom()); timing.start(); if (!queryManager.needsLoading(newTopLeft, newBottomRight)) return cachePinsOverlay; ArrayList<Geocache> cacheList = queryManager.load(newTopLeft, newBottomRight, loaderImpl); timing.lap("Loaded caches"); cachePinsOverlay = new CachePinsOverlay(resources, cacheItemFactory, activity, cacheList, mapClickIntentFactory); return cachePinsOverlay; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter; import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.GraphicsGenerator.MapViewBitmapCopier; import com.google.inject.Inject; import android.content.res.Resources; import android.graphics.drawable.Drawable; class CacheItemFactory { private final IconRenderer mIconRenderer; private final MapViewBitmapCopier mMapViewBitmapCopier; private final IconOverlayFactory mIconOverlayFactory; private final DifficultyAndTerrainPainter mDifficultyAndTerrainPainter; @Inject CacheItemFactory(MapViewBitmapCopier mapViewBitmapCopier, IconOverlayFactory iconOverlayFactory, Resources resources, DifficultyAndTerrainPainter difficultyAndTerrainPainter) { mIconRenderer = new IconRenderer(resources); mMapViewBitmapCopier = mapViewBitmapCopier; mIconOverlayFactory = iconOverlayFactory; mDifficultyAndTerrainPainter = difficultyAndTerrainPainter; } CacheItem createCacheItem(Geocache geocache) { final CacheItem cacheItem = new CacheItem(geocache.getGeoPoint(), (String)geocache.getId(), geocache); final Drawable icon = mIconRenderer.renderIcon(geocache.getDifficulty(), geocache .getTerrain(), geocache.getCacheType().iconMap(), mIconOverlayFactory.create( geocache, false), mMapViewBitmapCopier, mDifficultyAndTerrainPainter); cacheItem.setMarker(icon); return cacheItem; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map.click; import com.google.code.geobeagle.activity.map.click.MapClickIntentFactory; import com.google.code.geobeagle.activity.map.click.MapClickIntentFactoryHoneycomb; import com.google.code.geobeagle.activity.map.click.MapClickIntentFactoryPreHoneycomb; import roboguice.config.AbstractAndroidModule; import android.os.Build; public class MapModule extends AbstractAndroidModule { @Override protected void configure() { int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) { bind(MapClickIntentFactory.class).to(MapClickIntentFactoryHoneycomb.class); } else { bind(MapClickIntentFactory.class).to(MapClickIntentFactoryPreHoneycomb.class); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.intents.GeocacheToGoogleGeo; import com.google.code.geobeagle.activity.compass.intents.IntentStarter; import com.google.code.geobeagle.activity.compass.intents.IntentStarterGeo; import com.google.code.geobeagle.activity.compass.intents.IntentStarterViewUri; import com.google.code.geobeagle.activity.compass.menuactions.NavigateOnClickListener; import com.google.code.geobeagle.activity.compass.view.install_radar.InstallRadarAppDialog; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.res.Resources; public class ChooseNavDialogProvider implements Provider<ChooseNavDialog> { private final ErrorDisplayer errorDisplayer; private final Activity activity; private final Provider<Resources> resourcesProvider; private final Provider<Context> contextProvider; private final Provider<InstallRadarAppDialog> installRadarAppDialogProvider; private final HasGeocache hasGeocache; @Inject public ChooseNavDialogProvider(Injector injector) { errorDisplayer = injector.getInstance(ErrorDisplayer.class); activity = injector.getInstance(Activity.class); resourcesProvider = injector.getProvider(Resources.class); contextProvider = injector.getProvider(Context.class); installRadarAppDialogProvider = injector.getProvider(InstallRadarAppDialog.class); hasGeocache = injector.getInstance(HasGeocache.class); } @Override public ChooseNavDialog get() { GeocacheToGoogleGeo geocacheToGoogleMaps = new GeocacheToGoogleGeo(resourcesProvider, R.string.google_maps_intent); GeocacheToGoogleGeo geocacheToNavigate = new GeocacheToGoogleGeo(resourcesProvider, R.string.navigate_intent); IntentStarterGeo intentStarterRadar = new IntentStarterGeo(activity, new Intent( "com.google.android.radar.SHOW_RADAR"), hasGeocache); IntentStarterViewUri intentStarterGoogleMaps = new IntentStarterViewUri(activity, geocacheToGoogleMaps, errorDisplayer, hasGeocache); IntentStarterViewUri intentStarterNavigate = new IntentStarterViewUri(activity, geocacheToNavigate, errorDisplayer, hasGeocache); IntentStarter[] intentStarters = { intentStarterRadar, intentStarterGoogleMaps, intentStarterNavigate }; OnClickListener onClickListener = new NavigateOnClickListener(intentStarters, installRadarAppDialogProvider.get()); return new ChooseNavDialog(new AlertDialog.Builder(contextProvider.get()) .setItems(R.array.select_nav_choices, onClickListener) .setTitle(R.string.select_nav_choices_title).create()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.compass.Util; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.LocationSaver; import com.google.inject.Inject; import com.google.inject.Provider; import android.content.Intent; import android.net.UrlQuerySanitizer; import android.os.Bundle; import android.util.Log; public class GeocacheFromIntentFactory { static final String GEO_BEAGLE_SAVED_IN_DATABASE = "com.google.code.geobeagle.SavedInDatabase"; private final GeocacheFactory mGeocacheFactory; private final Provider<DbFrontend> mDbFrontendProvider; @Inject GeocacheFromIntentFactory(GeocacheFactory geocacheFactory, Provider<DbFrontend> dbFrontendProvider) { mGeocacheFactory = geocacheFactory; mDbFrontendProvider = dbFrontendProvider; } Geocache viewCacheFromMapsIntent(Intent intent, LocationSaver locationSaver, Geocache defaultGeocache) { Log.d("GeoBeagle", "viewCacheFromMapsIntent: " + intent); final String query = intent.getData().getQuery(); CharSequence sanitizedQuery = Util.parseHttpUri(query, new UrlQuerySanitizer(), UrlQuerySanitizer.getAllButNulAndAngleBracketsLegal()); if (sanitizedQuery == null) return defaultGeocache; final CharSequence[] latlon = Util .splitLatLonDescription(sanitizedQuery); CharSequence cacheId = latlon[2]; Bundle extras = intent.getExtras(); if (extras != null && extras.getBoolean(GEO_BEAGLE_SAVED_IN_DATABASE)) { Log.d("GeoBeagle", "Loading from database: " + cacheId); return mDbFrontendProvider.get().getCache(cacheId); } final Geocache geocache = mGeocacheFactory.create(cacheId, latlon[3], Util.parseCoordinate(latlon[0]), Util .parseCoordinate(latlon[1]), Source.WEB_URL, null, CacheType.NULL, 0, 0, 0, true, false); locationSaver.saveLocation(geocache); intent.putExtra("com.google.code.geobeagle.SavedInDatabase", true); return geocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.inject.Inject; import android.content.SharedPreferences; public class GeocacheFromPreferencesFactory { private final GeocacheFactory mGeocacheFactory; @Inject public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) { mGeocacheFactory = geocacheFactory; } public Geocache create(SharedPreferences preferences) { final int iSource = preferences.getInt(Geocache.SOURCE_TYPE, -1); final Source source = mGeocacheFactory.sourceFromInt(Math.max(Source.MIN_SOURCE, Math.min( iSource, Source.MAX_SOURCE))); final int iCacheType = preferences.getInt(Geocache.CACHE_TYPE, 0); final CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(iCacheType); return mGeocacheFactory.create(preferences.getString(Geocache.ID, "GCMEY7"), preferences .getString(Geocache.NAME, "Google Falls"), preferences.getFloat(Geocache.LATITUDE, 0), preferences.getFloat(Geocache.LONGITUDE, 0), source, preferences.getString( Geocache.SOURCE_NAME, ""), cacheType, preferences.getInt( Geocache.DIFFICULTY, 0), preferences.getInt(Geocache.TERRAIN, 0), preferences.getInt(Geocache.CONTAINER, 0), preferences.getBoolean(Geocache.AVAILABLE, true), preferences.getBoolean(Geocache.ARCHIVED, false)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.inject.Inject; import android.os.Bundle; import android.os.Parcel; public class GeocacheFromParcelFactory { private final GeocacheFactory mGeocacheFactory; @Inject public GeocacheFromParcelFactory(GeocacheFactory geocacheFactory) { mGeocacheFactory = geocacheFactory; } public Geocache create(Parcel in) { return createFromBundle(in.readBundle()); } public Geocache createFromBundle(Bundle bundle) { return mGeocacheFactory.create(bundle.getCharSequence(Geocache.ID), bundle .getCharSequence(Geocache.NAME), bundle.getDouble(Geocache.LATITUDE), bundle .getDouble(Geocache.LONGITUDE), mGeocacheFactory.sourceFromInt(bundle .getInt(Geocache.SOURCE_TYPE)), bundle.getString(Geocache.SOURCE_NAME), mGeocacheFactory.cacheTypeFromInt(bundle.getInt(Geocache.CACHE_TYPE)), bundle .getInt(Geocache.DIFFICULTY), bundle.getInt(Geocache.TERRAIN), bundle .getInt(Geocache.CONTAINER), bundle.getBoolean(Geocache.AVAILABLE), bundle .getBoolean(Geocache.ARCHIVED)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.GraphicsGenerator.RatingsArray; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.ActivityWithGeocache; import com.google.code.geobeagle.activity.compass.fieldnotes.FragmentWithGeocache; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.AttributeViewer; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.LabelledAttributeViewer; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.UnlabelledAttributeViewer; import com.google.inject.Provides; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import roboguice.config.AbstractAndroidModule; import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Build; import android.widget.ImageView; import android.widget.TextView; public class CompassActivityModule extends AbstractAndroidModule { @Override protected void configure() { bind(ChooseNavDialog.class).toProvider(ChooseNavDialogProvider.class); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) { bind(CompassFragtivityOnCreateHandler.class).to(CompassFragmentOnCreateHandler.class); bind(HasGeocache.class).to(FragmentWithGeocache.class); } else { bind(CompassFragtivityOnCreateHandler.class).to(CompassActivityOnCreateHandler.class); bind(HasGeocache.class).to(ActivityWithGeocache.class); } } private static UnlabelledAttributeViewer getImagesOnDifficulty(final Drawable[] pawDrawables, ImageView imageView, RatingsArray ratingsArray) { return new UnlabelledAttributeViewer(imageView, ratingsArray.getRatings(pawDrawables, 10)); } @Provides RadarView providesRadarView(Activity activity) { RadarView radarView = (RadarView)activity.findViewById(R.id.radarview); radarView.setUseImperial(false); radarView.setDistanceView((TextView)activity.findViewById(R.id.radar_distance), (TextView)activity.findViewById(R.id.radar_bearing), (TextView)activity .findViewById(R.id.radar_accuracy)); return radarView; } @Provides XmlPullParser providesXmlPullParser() throws XmlPullParserException { return XmlPullParserFactory.newInstance().newPullParser(); } static AttributeViewer getLabelledAttributeViewer(HasViewById activity, Resources resources, RatingsArray ratingsArray, int[] resourceIds, int difficultyId, int labelId) { final ImageView imageViewTerrain = (ImageView)activity.findViewById(difficultyId); final Drawable[] pawDrawables = { resources.getDrawable(resourceIds[0]), resources.getDrawable(resourceIds[1]), resources.getDrawable(resourceIds[2]), }; final AttributeViewer pawImages = getImagesOnDifficulty(pawDrawables, imageViewTerrain, ratingsArray); final AttributeViewer gcTerrain = new LabelledAttributeViewer((TextView)activity .findViewById(labelId), pawImages); return gcTerrain; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger.OnClickOk; import com.google.inject.Inject; import android.app.Activity; import android.widget.EditText; public class OnClickOkFactory { private final CacheLogger cacheLogger; private final Activity activity; private final HasGeocache hasGeocache; @Inject public OnClickOkFactory(Activity activity, CacheLogger cacheLogger, HasGeocache hasGeocache) { this.activity = activity; this.cacheLogger = cacheLogger; this.hasGeocache = hasGeocache; } public OnClickOk create(EditText editText, boolean dnf) { return new OnClickOk(hasGeocache.get(activity).getId(), editText, cacheLogger, dnf); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass.fieldnotes; import com.google.inject.Inject; public class DialogHelperSmsFactory { private final FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf; @Inject public DialogHelperSmsFactory(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf) { this.fieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; } public DialogHelperSms create(int geocacheIdLength, boolean dnf) { return new DialogHelperSms(fieldnoteStringsFVsDnf, geocacheIdLength, dnf); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperCommon; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperFile; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperSms; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger; import com.google.inject.Inject; import android.content.SharedPreferences; public class FieldnoteLoggerFactory { private final DialogHelperCommon dialogHelperCommon; private final DialogHelperFile dialogHelperFile; private final SharedPreferences sharedPreferences; @Inject public FieldnoteLoggerFactory(DialogHelperCommon dialogHelperCommon, DialogHelperFile dialogHelperFile, SharedPreferences sharedPreferences) { this.dialogHelperCommon = dialogHelperCommon; this.dialogHelperFile = dialogHelperFile; this.sharedPreferences = sharedPreferences; } public FieldnoteLogger create(DialogHelperSms dialogHelperSms) { return new FieldnoteLogger(dialogHelperCommon, dialogHelperFile, dialogHelperSms, sharedPreferences); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.R; import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter; import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.GraphicsGenerator.MapViewBitmapCopier; import com.google.code.geobeagle.GraphicsGenerator.RatingsArray; import com.google.code.geobeagle.activity.cachelist.view.NameFormatter; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.AttributeViewer; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.NameViewer; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.ResourceImages; import com.google.inject.Inject; import android.app.Activity; import android.content.res.Resources; import android.widget.ImageView; import android.widget.TextView; import java.util.Arrays; public class GeocacheViewerFactory { private final IconOverlayFactory iconOverlayFactory; private final NameFormatter nameFormatter; private final Resources resources; private final RatingsArray ratingsArray; private final MapViewBitmapCopier mapViewBitmapCopier; private final DifficultyAndTerrainPainter difficultyAndTerrainPainter; private final IconRenderer iconRenderer; private final Activity activity; @Inject GeocacheViewerFactory(IconOverlayFactory iconOverlayFactory, NameFormatter nameFormatter, Resources resources, RatingsArray ratingsArray, MapViewBitmapCopier mapViewBitmapCopier, DifficultyAndTerrainPainter difficultyAndTerrainPainter, IconRenderer iconRenderer, Activity activity) { this.iconOverlayFactory = iconOverlayFactory; this.nameFormatter = nameFormatter; this.resources = resources; this.ratingsArray = ratingsArray; this.mapViewBitmapCopier = mapViewBitmapCopier; this.difficultyAndTerrainPainter = difficultyAndTerrainPainter; this.iconRenderer = iconRenderer; this.activity = activity; } GeocacheViewer create(HasViewById hasViewById) { RadarView radarView = (RadarView)hasViewById.findViewById(R.id.radarview); radarView.setUseImperial(false); radarView.setDistanceView((TextView)hasViewById.findViewById(R.id.radar_distance), (TextView)hasViewById.findViewById(R.id.radar_bearing), (TextView)hasViewById.findViewById(R.id.radar_accuracy)); TextView textViewName = (TextView)hasViewById.findViewById(R.id.gcname); ImageView cacheTypeImageView = (ImageView)hasViewById.findViewById(R.id.gcicon); NameViewer gcName = new NameViewer(textViewName, nameFormatter); AttributeViewer gcDifficulty = CompassActivityModule.getLabelledAttributeViewer( hasViewById, resources, ratingsArray, new int[] { R.drawable.ribbon_unselected_dark, R.drawable.ribbon_half_bright, R.drawable.ribbon_selected_bright }, R.id.gc_difficulty, R.id.gc_text_difficulty); AttributeViewer gcTerrain = CompassActivityModule.getLabelledAttributeViewer(hasViewById, resources, ratingsArray, new int[] { R.drawable.paw_unselected_dark, R.drawable.paw_half_light, R.drawable.paw_selected_light }, R.id.gc_terrain, R.id.gc_text_terrain); ResourceImages gcContainer = new ResourceImages( (TextView)hasViewById.findViewById(R.id.gc_text_container), (ImageView)hasViewById.findViewById(R.id.gccontainer), Arrays.asList(GeocacheViewer.CONTAINER_IMAGES)); return new GeocacheViewer(radarView, activity, gcName, cacheTypeImageView, gcDifficulty, gcTerrain, gcContainer, iconOverlayFactory, mapViewBitmapCopier, iconRenderer, difficultyAndTerrainPainter); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.GpsDisabledLocation; import com.google.code.geobeagle.activity.cachelist.presenter.ActionAndTolerance; import com.google.code.geobeagle.activity.cachelist.presenter.AdapterCachesSorter; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceUpdater; import com.google.code.geobeagle.activity.cachelist.presenter.LocationAndAzimuthTolerance; import com.google.code.geobeagle.activity.cachelist.presenter.LocationTolerance; import com.google.code.geobeagle.activity.cachelist.presenter.SqlCacheLoader; import com.google.code.geobeagle.activity.cachelist.presenter.ToleranceStrategy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; class ActionManagerProvider implements Provider<ActionManager> { private final GpsDisabledLocation gpsDisabledLocation; private final AdapterCachesSorter adapterCachesSorter; private final DistanceUpdater distanceUpdater; private final SqlCacheLoader sqlCacheLoader; public ActionManagerProvider(GpsDisabledLocation gpsDisabledLocation, AdapterCachesSorter adapterCachesSorter, DistanceUpdater distanceUpdater, SqlCacheLoader sqlCacheLoader) { this.gpsDisabledLocation = gpsDisabledLocation; this.adapterCachesSorter = adapterCachesSorter; this.distanceUpdater = distanceUpdater; this.sqlCacheLoader = sqlCacheLoader; } @Inject public ActionManagerProvider(Injector injector) { this.gpsDisabledLocation = injector.getInstance(GpsDisabledLocation.class); this.adapterCachesSorter = injector.getInstance(AdapterCachesSorter.class); this.distanceUpdater = injector.getInstance(DistanceUpdater.class); this.sqlCacheLoader = injector.getInstance(SqlCacheLoader.class); } @Override public ActionManager get() { final ToleranceStrategy sqlCacheLoaderTolerance = new LocationTolerance(500, gpsDisabledLocation, 10000); final ToleranceStrategy adapterCachesSorterTolerance = new LocationTolerance(6, gpsDisabledLocation, 5000); final LocationTolerance distanceUpdaterLocationTolerance = new LocationTolerance(1, gpsDisabledLocation, 1000); final ToleranceStrategy distanceUpdaterTolerance = new LocationAndAzimuthTolerance( distanceUpdaterLocationTolerance, 720); final ActionAndTolerance[] actionAndTolerances = new ActionAndTolerance[] { new ActionAndTolerance(sqlCacheLoader, sqlCacheLoaderTolerance), new ActionAndTolerance(adapterCachesSorter, adapterCachesSorterTolerance), new ActionAndTolerance(distanceUpdater, distanceUpdaterTolerance) }; return new ActionManager(actionAndTolerances); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.inject.Inject; public class SearchWhereFactory { private final SearchTarget searchTarget; @Inject SearchWhereFactory(SearchTarget searchTarget) { this.searchTarget = searchTarget; } public String getWhereString() { String target = searchTarget.getTarget(); if (target == null) return ""; return " AND (Id LIKE '%" + target + "%' OR Description LIKE '%" + target + "%')"; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.CacheListActivityStarterHoneycomb; import com.google.code.geobeagle.CacheListActivityStarter; import com.google.code.geobeagle.CacheListActivityStarterPreHoneycomb; import com.google.code.geobeagle.activity.cachelist.actions.menu.CompassFrameHider; import com.google.code.geobeagle.activity.cachelist.actions.menu.HoneycombCompassFrameHider; import com.google.code.geobeagle.activity.cachelist.actions.menu.NullCompassFrameHider; import com.google.code.geobeagle.activity.cachelist.presenter.AbsoluteBearingFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager; import com.google.code.geobeagle.activity.cachelist.presenter.ListActivityOnCreateHandler; import com.google.code.geobeagle.activity.cachelist.presenter.ListFragmentOnCreateHandler; import com.google.code.geobeagle.activity.cachelist.presenter.ListFragtivityOnCreateHandler; import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import com.google.code.geobeagle.formatting.DistanceFormatterImperial; import com.google.code.geobeagle.formatting.DistanceFormatterMetric; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import roboguice.config.AbstractAndroidModule; import android.content.SharedPreferences; import android.os.Build; public class CacheListModule extends AbstractAndroidModule { @Override protected void configure() { bind(ActionManager.class).toProvider(ActionManagerProvider.class).in(Singleton.class); bind(DistanceFormatter.class).toProvider(DistanceFormatterProvider.class); bind(BearingFormatter.class).toProvider(BearingFormatterProvider.class); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) { bind(ListFragtivityOnCreateHandler.class).to(ListFragmentOnCreateHandler.class); bind(CompassFrameHider.class).to(HoneycombCompassFrameHider.class); bind(CacheListActivityStarter.class).to(CacheListActivityStarterHoneycomb.class); bind(ViewMenuAdder.class).to(ViewMenuAdderHoneycomb.class); } else { bind(ListFragtivityOnCreateHandler.class).to(ListActivityOnCreateHandler.class); bind(CompassFrameHider.class).to(NullCompassFrameHider.class); bind(CacheListActivityStarter.class).to(CacheListActivityStarterPreHoneycomb.class); bind(ViewMenuAdder.class).to(ViewMenuAdderPreHoneycomb.class); } } static class DistanceFormatterProvider implements Provider<DistanceFormatter> { private final SharedPreferences preferenceManager; private final DistanceFormatterMetric distanceFormatterMetric; private final DistanceFormatterImperial distanceFormatterImperial; @Inject DistanceFormatterProvider(SharedPreferences preferenceManager) { this.preferenceManager = preferenceManager; this.distanceFormatterMetric = new DistanceFormatterMetric(); this.distanceFormatterImperial = new DistanceFormatterImperial(); } @Override public DistanceFormatter get() { return preferenceManager.getBoolean("imperial", false) ? distanceFormatterImperial : distanceFormatterMetric; } } static class BearingFormatterProvider implements Provider<BearingFormatter> { private final AbsoluteBearingFormatter absoluteBearingFormatter; private final RelativeBearingFormatter relativeBearingFormatter; private final SharedPreferences preferenceManager; @Inject BearingFormatterProvider(SharedPreferences preferenceManager) { this.preferenceManager = preferenceManager; this.absoluteBearingFormatter = new AbsoluteBearingFormatter(); this.relativeBearingFormatter = new RelativeBearingFormatter(); } @Override public BearingFormatter get() { return preferenceManager.getBoolean("absolute-bearing", false) ? absoluteBearingFormatter : relativeBearingFormatter; } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.model; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.inject.Inject; import android.location.Location; public class GeocacheFromMyLocationFactory { private final GeocacheFactory mGeocacheFactory; private final LocationControlBuffered mLocationControl; @Inject public GeocacheFromMyLocationFactory(GeocacheFactory geocacheFactory, LocationControlBuffered locationControl) { mGeocacheFactory = geocacheFactory; mLocationControl = locationControl; } public Geocache create() { Location location = mLocationControl.getLocation(); if (location == null) { return null; } long time = location.getTime(); return mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format( "[%1$tk:%1$tM] My Location", time), location.getLatitude(), location.getLongitude(), Source.MY_LOCATION, null, CacheType.MY_LOCATION, 0, 0, 0, true, false); } }
Java
package com.google.code.geobeagle; import android.content.SearchRecentSuggestionsProvider; public class SuggestionProvider extends SearchRecentSuggestionsProvider { public final static String AUTHORITY = "com.google.code.geobeagle.SuggestionProvider"; public final static int MODE = DATABASE_MODE_QUERIES | DATABASE_MODE_2LINES; public SuggestionProvider() { setupSuggestions(AUTHORITY, MODE); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.code.geobeagle.cachedetails.FileDataVersionWriter; import com.google.code.geobeagle.database.ClearCachesFromSourceImpl; import com.google.code.geobeagle.database.GpxTableWriterGpxFiles; import com.google.code.geobeagle.xmlimport.GpxToCache.GpxToCacheFactory; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.inject.Inject; import android.content.SharedPreferences; class GpxSyncerFactory { private final CacheListRefresh cacheListRefresh; private final FileDataVersionWriter fileDataVersionWriter; private final GpxAndZipFiles gpxAndZipFiles; private final GpxToCacheFactory gpxToCacheFactory; private final MessageHandler messageHandlerInterface; private final OldCacheFilesCleaner oldCacheFilesCleaner; private final UpdateFlag updateFlag; private final GeoBeagleEnvironment geoBeagleEnvironment; private final GpxTableWriterGpxFiles gpxTableWriterGpxFiles; private final SharedPreferences sharedPreferences; private final ClearCachesFromSourceImpl clearCachesFromSource; @Inject public GpxSyncerFactory(MessageHandler messageHandler, CacheListRefresh cacheListRefresh, GpxAndZipFiles gpxAndZipFiles, GpxToCacheFactory gpxToCacheFactory, FileDataVersionWriter fileDataVersionWriter, OldCacheFilesCleaner oldCacheFilesCleaner, UpdateFlag updateFlag, GeoBeagleEnvironment geoBeagleEnvironment, GpxTableWriterGpxFiles gpxTableWriterGpxFiles, SharedPreferences sharedPreferences, ClearCachesFromSourceImpl clearCachesFromSource) { this.messageHandlerInterface = messageHandler; this.cacheListRefresh = cacheListRefresh; this.gpxAndZipFiles = gpxAndZipFiles; this.gpxToCacheFactory = gpxToCacheFactory; this.fileDataVersionWriter = fileDataVersionWriter; this.oldCacheFilesCleaner = oldCacheFilesCleaner; this.updateFlag = updateFlag; this.geoBeagleEnvironment = geoBeagleEnvironment; this.gpxTableWriterGpxFiles = gpxTableWriterGpxFiles; this.sharedPreferences = sharedPreferences; this.clearCachesFromSource = clearCachesFromSource; } public GpxSyncer create() { messageHandlerInterface.start(cacheListRefresh); final GpxToCache gpxToCache = gpxToCacheFactory.create(messageHandlerInterface, gpxTableWriterGpxFiles, clearCachesFromSource); return new GpxSyncer(gpxAndZipFiles, fileDataVersionWriter, messageHandlerInterface, oldCacheFilesCleaner, gpxToCache, updateFlag, geoBeagleEnvironment, sharedPreferences); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.cachedetails.DetailsDatabaseWriter; import com.google.inject.Inject; class TagWriter { private static final String SPACES = " "; private int mLevel; private final DetailsDatabaseWriter writer; private final StringBuffer stringBuffer; private String wpt; @Inject public TagWriter(DetailsDatabaseWriter writer) { this.writer = writer; stringBuffer = new StringBuffer(); } public void close() { writer.write(wpt, stringBuffer.toString()); wpt = null; } public void endTag(String name) { mLevel--; stringBuffer.append("</" + name + ">"); } public void open(String wpt) { mLevel = 0; this.wpt = wpt; stringBuffer.setLength(0); stringBuffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); } public void startTag(Tag tag) { stringBuffer.append("\n" + SPACES.substring(0, Math.min(mLevel, SPACES.length()))); mLevel++; stringBuffer.append("<" + tag.name); for (String key : tag.attributes.keySet()) { stringBuffer.append(" " + key + "='" + tag.attributes.get(key) + "'"); } stringBuffer.append(">"); } public void text(String text) { stringBuffer.append(text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")); } public void start() { writer.start(); } public void end() { writer.end(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.cachedetails.StringWriterWrapper; import com.google.inject.Inject; import java.io.IOException; public class CacheXmlTagsToUrl extends CacheXmlTagHandler { private final StringWriterWrapper stringWriterWrapper; @Inject CacheXmlTagsToUrl(StringWriterWrapper stringWriterWrapper) { this.stringWriterWrapper = stringWriterWrapper; } @Override public void url(String text) { try { stringWriterWrapper.open(); stringWriterWrapper.write(text); } catch (IOException e) { e.printStackTrace(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; import java.util.HashMap; import java.util.Map; public enum GpxPath { GPX_AU_DESCRIPTION("/gpx/wpt/geocache/description", PathType.LINE), GPX_AU_GEOCACHER("/gpx/wpt/geocache/logs/log/geocacher", PathType.LINE), GPX_AU_LOGTEXT("/gpx/wpt/geocache/logs/log/text", PathType.LINE), GPX_AU_LOGTYPE("/gpx/wpt/geocache/logs/log/type", PathType.LINE), GPX_AU_OWNER("/gpx/wpt/geocache/owner", PathType.LINE), GPX_AU_SUMMARY("/gpx/wpt/geocache/summary", PathType.LINE), GPX_CACHE("/gpx/wpt/groundspeak:cache", PathType.CACHE), GPX_CACHE_CONTAINER("/gpx/wpt/groundspeak:cache/groundspeak:container", PathType.CONTAINER), GPX_CACHE_DIFFICULTY("/gpx/wpt/groundspeak:cache/groundspeak:difficulty", PathType.DIFFICULTY), GPX_CACHE_TERRAIN("/gpx/wpt/groundspeak:cache/groundspeak:terrain", PathType.TERRAIN), GPX_EXT_LONGDESC("/gpx/wpt/extensions/cache/long_description", PathType.LONG_DESCRIPTION), GPX_EXT_SHORTDESC("/gpx/wpt/extensions/cache/short_description", PathType.SHORT_DESCRIPTION), GPX_GEOCACHE_CONTAINER("/gpx/wpt/geocache/container", PathType.CONTAINER), GPX_GEOCACHE_DIFFICULTY("/gpx/wpt/geocache/difficulty", PathType.DIFFICULTY), GPX_GEOCACHE_EXT_DIFFICULTY("/gpx/wpt/extensions/cache/difficulty", PathType.DIFFICULTY), GPX_GEOCACHE_EXT_TERRAIN("/gpx/wpt/extensions/cache/terrain", PathType.TERRAIN), GPX_GEOCACHE_TERRAIN("/gpx/wpt/geocache/terrain", PathType.TERRAIN), GPX_GEOCACHE_TYPE("/gpx/wpt/geocache/type", PathType.CACHE_TYPE), GPX_GEOCACHEHINT("/gpx/wpt/geocache/hints", PathType.HINT), GPX_GEOCACHELOGDATE("/gpx/wpt/geocache/logs/log/time", PathType.LOG_DATE), GPX_GEOCACHENAME("/gpx/wpt/geocache/name", PathType.NAME), GPX_GPXTIME("/gpx/time", PathType.GPX_TIME), GPX_GROUNDSPEAKFINDER( "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", PathType.LINE), GPX_GROUNDSPEAKNAME("/gpx/wpt/groundspeak:cache/groundspeak:name", PathType.NAME), GPX_HINT("/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints", PathType.HINT), GPX_LAST_MODIFIED("/gpx/wpt/bcaching:cache/bcaching:lastModified", PathType.LAST_MODIFIED), GPX_LOGDATE("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date", PathType.LOG_DATE), GPX_LOGFINDER("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", PathType.LOG_FINDER), GPX_LOGTEXT("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text", PathType.LOG_TEXT), GPX_LOGTYPE("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type", PathType.LOG_TYPE), GPX_LONGDESC("/gpx/wpt/groundspeak:cache/groundspeak:long_description", PathType.LONG_DESCRIPTION), GPX_OCLOGDATE("/gpx/wpt/extensions/cache/logs/log/date", PathType.LOG_DATE), GPX_OCLOGDATE_OLD("/gpx/wpt/extensions/cache/logs/log/time", PathType.LOG_DATE), GPX_OCLOGFINDER("/gpx/wpt/extensions/cache/logs/log/finder", PathType.LOG_FINDER), GPX_OCLOGFINDER_OLD("/gpx/wpt/extensions/cache/logs/log/geocacher", PathType.LOG_FINDER), GPX_OCLOGTEXT("/gpx/wpt/extensions/cache/logs/log/text", PathType.LOG_TEXT), GPX_OCLOGTYPE("/gpx/wpt/extensions/cache/logs/log/type", PathType.LOG_TYPE), GPX_OCNAME("/gpx/wpt/extensions/cache/name", PathType.NAME), GPX_OCOWNER("/gpx/wpt/extensions/cache/owner", PathType.PLACED_BY), GPX_PLACEDBY("/gpx/wpt/groundspeak:cache/groundspeak:placed_by", PathType.PLACED_BY), GPX_SHORTDESC("/gpx/wpt/groundspeak:cache/groundspeak:short_description", PathType.SHORT_DESCRIPTION), GPX_SYM("/gpx/wpt/sym", PathType.SYMBOL), GPX_TERRACACHINGGPXTIME("/gpx/metadata/time", PathType.GPX_TIME), GPX_URL("/gpx/wpt/url", PathType.GPX_URL), GPX_WAYPOINT_TYPE("/gpx/wpt/type", PathType.CACHE_TYPE), GPX_WPT("/gpx/wpt", PathType.WPT), GPX_WPT_COMMENT("/gpx/wpt/cmt", PathType.LINE), GPX_WPTDESC("/gpx/wpt/desc", PathType.DESC), GPX_WPTNAME("/gpx/wpt/name", PathType.WPT_NAME), GPX_WPTTIME("/gpx/wpt/time", PathType.WPT_TIME), LOC_COORD("/loc/waypoint/coord", PathType.LOC_COORD), LOC_LONGDESC("/loc/waypoint/desc", PathType.LONG_DESCRIPTION), LOC_WPT("/loc/waypoint", PathType.LOC_WPT), LOC_WPTNAME("/loc/waypoint/name", PathType.LOC_WPTNAME), NO_MATCH(null, PathType.NOP); private static final Map<String, GpxPath> stringToEnum = new HashMap<String, GpxPath>(); static { for (GpxPath gpxPath : values()) stringToEnum.put(gpxPath.getPath(), gpxPath); } public static GpxPath fromString(String symbol) { final GpxPath gpxPath = stringToEnum.get(symbol); if (gpxPath == null) { return GpxPath.NO_MATCH; } return gpxPath; } private final String path; private final PathType pathType; GpxPath(String path, PathType pathType) { this.path = path; this.pathType = pathType; } public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { pathType.endTag(cacheXmlTagHandler); } public String getPath() { return path; } public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { pathType.startTag(xmlPullParser, cacheXmlTagHandler); } public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { String trimmedText = text.trim(); if (trimmedText.length() <= 0) return true; return pathType.text(trimmedText, cacheXmlTagHandler); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; enum PathType { CACHE { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.available(xmlPullParser.getAttributeValue(null, "available")); cacheXmlTagHandler.archived(xmlPullParser.getAttributeValue(null, "archived")); } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.symbol(text); return true; } }, CACHE_TYPE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.cacheType(text); return true; } }, CONTAINER { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.container(text); return true; } }, DESC { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.wptDesc(text); return true; } }, DIFFICULTY { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.difficulty(text); return true; } }, GPX_TIME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return cacheXmlTagHandler.gpxTime(text); } }, HINT { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { if (!text.equals("")) cacheXmlTagHandler.hint(text); return true; } }, LAST_MODIFIED { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return true; } }, LINE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.line(text); return true; } }, LOC_COORD { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser.getAttributeValue(null, "lon")); } }, LOC_WPT { @Override public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.endCache(Source.LOC); } }, LOC_WPTNAME { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.startCache(); cacheXmlTagHandler.wptName(xmlPullParser.getAttributeValue(null, "id")); } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.groundspeakName(text.trim()); return true; } }, LOG_DATE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logDate(text); return true; } }, LOG_TEXT { @Override public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.setEncrypted(false); } @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.setEncrypted("true".equalsIgnoreCase(xmlPullParser .getAttributeValue(null, "encoded"))); } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logText(text); return true; } }, LOG_TYPE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logType(text); return true; } }, LONG_DESCRIPTION { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.longDescription(text); return true; } }, NAME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.groundspeakName(text); return true; } }, NOP { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return true; } }, PLACED_BY { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.placedBy(text); return true; } }, SHORT_DESCRIPTION { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.shortDescription(text); return true; } }, SYMBOL { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.symbol(text); return true; } }, TERRAIN { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.terrain(text); return true; } }, WPT { @Override public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.endCache(Source.GPX); } @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.startCache(); cacheXmlTagHandler.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser.getAttributeValue(null, "lon")); } }, WPT_NAME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.wptName(text); return true; } }, WPT_TIME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.wptTime(text); return true; } }, LOG_FINDER { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logFinder(text); return true; } }, GPX_URL { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.url(text); return true; } }; @SuppressWarnings("unused") public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { } @SuppressWarnings("unused") public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { } @SuppressWarnings("unused") public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.code.geobeagle.activity.preferences.Preferences; import com.google.code.geobeagle.cachedetails.FileDataVersionWriter; import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilesAndZipFilesIter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import android.content.SharedPreferences; import android.util.Log; import java.io.File; import java.io.IOException; public class GpxSyncer { private final FileDataVersionWriter fileDataVersionWriter; private final GpxAndZipFiles gpxAndZipFiles; private final GpxToCache gpxToCache; private boolean mHasFiles; private final MessageHandler messageHandler; private final OldCacheFilesCleaner oldCacheFilesCleaner; private final UpdateFlag updateFlag; private final GeoBeagleEnvironment geoBeagleEnvironment; private final SharedPreferences sharedPreferences; public GpxSyncer(GpxAndZipFiles gpxAndZipFiles, FileDataVersionWriter fileDataVersionWriter, MessageHandler messageHandlerInterface, OldCacheFilesCleaner oldCacheFilesCleaner, GpxToCache gpxToCache, UpdateFlag updateFlag, GeoBeagleEnvironment geoBeagleEnvironment, SharedPreferences sharedPreferences) { this.gpxAndZipFiles = gpxAndZipFiles; this.fileDataVersionWriter = fileDataVersionWriter; this.messageHandler = messageHandlerInterface; this.mHasFiles = false; this.oldCacheFilesCleaner = oldCacheFilesCleaner; this.gpxToCache = gpxToCache; this.updateFlag = updateFlag; this.geoBeagleEnvironment = geoBeagleEnvironment; this.sharedPreferences = sharedPreferences; } public void sync(SyncCollectingParameter syncCollectingParameter) throws IOException, ImportException, CancelException { try { updateFlag.setUpdatesEnabled(false); if (!sharedPreferences.getBoolean(Preferences.SDCARD_ENABLED, true)) return; GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = startImport(); while (gpxFilesAndZipFilesIter.hasNext()) { processFile(syncCollectingParameter, gpxFilesAndZipFilesIter); } if (!mHasFiles) syncCollectingParameter.Log(R.string.error_no_gpx_files, geoBeagleEnvironment.getImportFolder()); endImport(); } finally { Log.d("GeoBeagle", "<<< Syncing"); updateFlag.setUpdatesEnabled(true); messageHandler.loadComplete(); } } private void endImport() throws IOException { fileDataVersionWriter.writeVersion(); gpxToCache.end(); } private void processFile(SyncCollectingParameter syncCollectingParameter, GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter) throws IOException, CancelException { IGpxReader gpxReader = gpxFilesAndZipFilesIter.next(); String filename = gpxReader.getFilename(); syncCollectingParameter.Log("***" + (new File(filename).getName()) + "***"); mHasFiles = true; int cachesLoaded = gpxToCache.load(filename, gpxReader.open()); if (cachesLoaded == -1) { syncCollectingParameter.Log(" synced 0 caches"); } else { syncCollectingParameter.Log(" synced " + cachesLoaded + " caches"); } } private GpxFilesAndZipFilesIter startImport() throws ImportException { oldCacheFilesCleaner.clean(messageHandler); gpxToCache.start(); GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = gpxAndZipFiles.iterator(); return gpxFilesAndZipFilesIter; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.cachedetails.StringWriterWrapper; import com.google.inject.Inject; import com.google.inject.Provider; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; public class EventDispatcher { public static class EventDispatcherFactory { private final XmlPathBuilder xmlPathBuilder; private final Provider<XmlPullParser> xmlPullParserProvider; private final StringWriterWrapper stringWriterWrapper; @Inject public EventDispatcherFactory(XmlPathBuilder xmlPathBuilder, Provider<XmlPullParser> xmlPullParserProvider, StringWriterWrapper stringWriterWrapper) { this.xmlPathBuilder = xmlPathBuilder; this.xmlPullParserProvider = xmlPullParserProvider; this.stringWriterWrapper = stringWriterWrapper; } public EventDispatcher create(EventHandler eventHandler) { return new EventDispatcher(xmlPathBuilder, eventHandler, xmlPullParserProvider, stringWriterWrapper); } } public static class XmlPathBuilder { private String mPath = ""; public void endTag(String currentTag) { mPath = mPath.substring(0, mPath.length() - (currentTag.length() + 1)); } public String getPath() { return mPath; } public void reset() { mPath = ""; } public void startTag(String mCurrentTag) { mPath += "/" + mCurrentTag; } } private final EventHandler eventHandler; private final XmlPathBuilder xmlPathBuilder; private XmlPullParser xmlPullParser; private final Provider<XmlPullParser> xmlPullParserProvider; private final StringWriterWrapper stringWriterWrapper; public EventDispatcher(XmlPathBuilder xmlPathBuilder, EventHandler eventHandler, Provider<XmlPullParser> xmlPullParserProvider, StringWriterWrapper stringWriterWrapper) { this.xmlPathBuilder = xmlPathBuilder; this.eventHandler = eventHandler; this.xmlPullParserProvider = xmlPullParserProvider; this.stringWriterWrapper = stringWriterWrapper; } public int getEventType() throws XmlPullParserException { return xmlPullParser.getEventType(); } public boolean handleEvent(int eventType) throws IOException { switch (eventType) { case XmlPullParser.START_TAG: { String name = xmlPullParser.getName(); xmlPathBuilder.startTag(name); eventHandler.startTag(name, xmlPathBuilder.getPath()); break; } case XmlPullParser.END_TAG: { String name = xmlPullParser.getName(); eventHandler.endTag(name, xmlPathBuilder.getPath()); xmlPathBuilder.endTag(name); break; } case XmlPullParser.TEXT: return eventHandler.text(xmlPathBuilder.getPath(), xmlPullParser.getText()); } return true; } public int next() throws XmlPullParserException, IOException { return xmlPullParser.next(); } public void open() { xmlPathBuilder.reset(); eventHandler.start(xmlPullParser); } public void setInput(Reader reader) throws XmlPullParserException { xmlPullParser = xmlPullParserProvider.get(); xmlPullParser.setInput(reader); } public String getString() { return stringWriterWrapper.getString(); } public void close() { eventHandler.end(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import java.io.File; import java.io.FilenameFilter; public class ExtensionFilter implements FilenameFilter { private final String extension; public ExtensionFilter(String extension) { this.extension = extension; } @Override public boolean accept(File dir, String filename) { return (filename.endsWith(extension)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import android.util.Log; import java.io.File; public class OldCacheFilesCleaner { private final String directory; @Inject public OldCacheFilesCleaner(GeoBeagleEnvironment geoBeagleEnvironment) { this.directory = geoBeagleEnvironment.getOldDetailsDirectory(); } public void clean(MessageHandlerInterface messageHandler) { messageHandler.deletingCacheFiles(); String[] list = new File(directory).list(new ExtensionFilter(".html")); if (list == null) return; for (int i = 0; i < list.length; i++) { messageHandler.updateStatus(String.format("Deleting old cache files: [%d/%d] %s", i, list.length, list[i])); File file = new File(directory, list[i]); Log.d("GeoBeagle", file + " deleted : " + file.delete()); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import roboguice.inject.ContextScoped; import android.util.Log; @ContextScoped public class AbortState { private static boolean aborted = false; AbortState() { aborted = false; } public void abort() { Log.d("GeoBeagle", this + ": aborting"); aborted = true; } public boolean isAborted() { return aborted; } public void reset() { aborted = false; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.Pausable; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListPresenter; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.code.geobeagle.xmlimport.ImportThread.ImportThreadFactory; import com.google.inject.Inject; import com.google.inject.Injector; import android.util.Log; import android.widget.Toast; public class CacheSyncer { private final MessageHandler messageHandler; private final Toaster toaster; private final Pausable geocacheListPresenter; private final AbortState abortState; private final ImportThreadFactory importThreadFactory; private ImportThread importThread; CacheSyncer(CacheListPresenter cacheListPresenter, MessageHandler messageHandler, Toaster toaster, AbortState abortState, ImportThreadFactory importThreadFactory) { this.messageHandler = messageHandler; this.toaster = toaster; this.geocacheListPresenter = cacheListPresenter; this.abortState = abortState; this.importThreadFactory = importThreadFactory; } @Inject CacheSyncer(Injector injector) { abortState = injector.getInstance(AbortState.class); messageHandler = injector.getInstance(MessageHandler.class); toaster = injector.getInstance(Toaster.class); geocacheListPresenter = injector.getInstance(CacheListPresenter.class); importThreadFactory = injector.getInstance(ImportThreadFactory.class); } public void abort() { Log.d("GeoBeagle", "CacheSyncer:abort() " + isAlive()); //TODO(sng): Why not use AbortState()? messageHandler.abortLoad(); abortState.abort(); if (isAlive()) { join(); toaster.toast(R.string.import_canceled, Toast.LENGTH_SHORT); } Log.d("GeoBeagle", "CacheSyncer:abort() ending: " + isAlive()); } boolean isAlive() { return importThread.isAliveHack(); } void join() { try { while (isAlive()) { Thread.sleep(1000); } } catch (InterruptedException e) { // Ignore; we are aborting anyway. } } public void syncGpxs() { // TODO(sng): check when onResume is called. geocacheListPresenter.onPause(); importThread = importThreadFactory.create(); importThread.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.cachedetails.CacheDetailsHtmlWriter; import com.google.inject.Inject; import java.io.IOException; public class CacheXmlTagsToDetails extends CacheXmlTagHandler { private final CacheDetailsHtmlWriter cacheDetailsHtmlWriter; private boolean encrypted; @Inject public CacheXmlTagsToDetails(CacheDetailsHtmlWriter cacheDetailsHtmlWriter) { this.cacheDetailsHtmlWriter = cacheDetailsHtmlWriter; } @Override public void cacheType(String text) throws IOException { cacheDetailsHtmlWriter.writeField("Type", text); } @Override public void container(String text) throws IOException { cacheDetailsHtmlWriter.writeField("Container", text); } @Override public void difficulty(String text) throws IOException { cacheDetailsHtmlWriter.writeField("Difficulty", text); } @Override public void endCache(Source source) throws IOException { cacheDetailsHtmlWriter.close(); } @Override public void groundspeakName(String text) throws IOException { cacheDetailsHtmlWriter.writeName(text); } @Override public void hint(String text) throws IOException { cacheDetailsHtmlWriter.writeHint(text); } @Override public void line(String text) throws IOException { cacheDetailsHtmlWriter.writeLine(text); } @Override public void logDate(String text) throws IOException { cacheDetailsHtmlWriter.writeLogDate(text); } @Override public void terrain(String text) throws IOException { cacheDetailsHtmlWriter.writeField("Terrain", text); } @Override public void wpt(String latitude, String longitude) { cacheDetailsHtmlWriter.latitudeLongitude(latitude, longitude); } @Override public void wptName(String wpt) throws IOException { cacheDetailsHtmlWriter.writeWptName(wpt); } @Override public void logText(String trimmedText) throws IOException { cacheDetailsHtmlWriter.writeLogText(trimmedText, encrypted); } @Override public void logType(String trimmedText) throws IOException { cacheDetailsHtmlWriter.logType(trimmedText); } @Override public void placedBy(String trimmedText) throws IOException { cacheDetailsHtmlWriter.placedBy(trimmedText); } @Override public void wptTime(String trimmedText) throws IOException { cacheDetailsHtmlWriter.wptTime(trimmedText); } @Override public void shortDescription(String trimmedText) throws IOException { cacheDetailsHtmlWriter.writeShortDescription(trimmedText); } @Override public void longDescription(String trimmedText) throws IOException { cacheDetailsHtmlWriter.writeLongDescription(trimmedText); } @Override public void setEncrypted(boolean mLogEncrypted) { encrypted = mLogEncrypted; } @Override public void logFinder(String text) { cacheDetailsHtmlWriter.writeLogFinder(text); } @Override public void url(String text) throws IOException { cacheDetailsHtmlWriter.writeUrl(text); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.database.ClearCachesFromSource; import com.google.code.geobeagle.database.GpxTableWriter; import com.google.code.geobeagle.xmlimport.CacheXmlTagsToSql.CacheXmlTagsToSqlFactory; import com.google.code.geobeagle.xmlimport.EventDispatcher.EventDispatcherFactory; import com.google.code.geobeagle.xmlimport.EventHandlerSqlAndFileWriter.EventHandlerSqlAndFileWriterFactory; import com.google.inject.Inject; import com.google.inject.Provider; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.database.sqlite.SQLiteException; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; public class GpxToCache { @SuppressWarnings("serial") public static class CancelException extends Exception { } public static class GpxToCacheFactory { private final AbortState abortState; private final EventDispatcherFactory eventDispatcherFactory; private final EventHandlerSqlAndFileWriterFactory eventHandlerSqlAndFileWriterFactory; private final LocAlreadyLoadedChecker locAlreadyLoadedChecker; private final Provider<ImportWakeLock> importWakeLockProvider; private final ErrorDisplayer errorDisplayer; private final CacheXmlTagsToSqlFactory cacheXmlTagsToSqlFactory; @Inject public GpxToCacheFactory(AbortState abortState, LocAlreadyLoadedChecker locAlreadyLoadedChecker, EventDispatcherFactory eventHelperFactory, EventHandlerSqlAndFileWriterFactory eventHandlerSqlAndFileWriterFactory, Provider<ImportWakeLock> importWakeLockProvider, ErrorDisplayer errorDisplayer, CacheXmlTagsToSqlFactory cacheXmlTagsToSqlFactory) { this.abortState = abortState; this.locAlreadyLoadedChecker = locAlreadyLoadedChecker; this.eventDispatcherFactory = eventHelperFactory; this.eventHandlerSqlAndFileWriterFactory = eventHandlerSqlAndFileWriterFactory; this.importWakeLockProvider = importWakeLockProvider; this.errorDisplayer = errorDisplayer; this.cacheXmlTagsToSqlFactory = cacheXmlTagsToSqlFactory; } public GpxToCache create(MessageHandlerInterface messageHandler, GpxTableWriter gpxTableWriter, ClearCachesFromSource clearCachesFromSource) { CacheXmlTagsToSql cacheXmlTagsToSql = cacheXmlTagsToSqlFactory.create(messageHandler, gpxTableWriter, clearCachesFromSource); EventHandlerSqlAndFileWriter eventHandlerSqlAndFileWriter = eventHandlerSqlAndFileWriterFactory .create(cacheXmlTagsToSql); return new GpxToCache(abortState, locAlreadyLoadedChecker, eventDispatcherFactory.create(eventHandlerSqlAndFileWriter), cacheXmlTagsToSql, importWakeLockProvider, errorDisplayer); } } private final AbortState abortState; private final CacheXmlTagsToSql cacheXmlTagsToSql; private final EventDispatcher eventDispatcher; private final LocAlreadyLoadedChecker locAlreadyLoadedChecker; private final Provider<ImportWakeLock> importWakeLockProvider; public static final int WAKELOCK_DURATION = 15000; private final ErrorDisplayer errorDisplayer; GpxToCache(AbortState abortState, LocAlreadyLoadedChecker locAlreadyLoadedChecker, EventDispatcher eventDispatcher, CacheXmlTagsToSql cacheXmlTagsToSql, Provider<ImportWakeLock> importWakeLockProvider, ErrorDisplayer errorDisplayer) { this.abortState = abortState; this.locAlreadyLoadedChecker = locAlreadyLoadedChecker; this.eventDispatcher = eventDispatcher; this.cacheXmlTagsToSql = cacheXmlTagsToSql; this.importWakeLockProvider = importWakeLockProvider; this.errorDisplayer = errorDisplayer; } public void end() { cacheXmlTagsToSql.end(); } public int load(String path, Reader reader) throws CancelException { try { String filename = new File(path).getName(); importWakeLockProvider.get().acquire(WAKELOCK_DURATION); return loadFile(path, filename, reader); } catch (SQLiteException e) { errorDisplayer.displayError(R.string.error_writing_cache, path + ": " + e.getMessage()); } catch (XmlPullParserException e) { errorDisplayer.displayError(R.string.error_parsing_file, path + ": " + e.getMessage()); } catch (FileNotFoundException e) { errorDisplayer.displayError(R.string.file_not_found, path + ": " + e.getMessage()); } catch (IOException e) { errorDisplayer.displayError(R.string.error_reading_file, path + ": " + e.getMessage()); } catch (CancelException e) { } throw new CancelException(); } private int loadFile(String source, String filename, Reader reader) throws XmlPullParserException, IOException, CancelException { eventDispatcher.setInput(reader); // Just use the filename, not the whole path. cacheXmlTagsToSql.open(filename); boolean markAsComplete = false; try { Log.d("GeoBeagle", this + ": GpxToCache: load"); if (locAlreadyLoadedChecker.isAlreadyLoaded(source)) { return -1; } eventDispatcher.open(); int eventType; for (eventType = eventDispatcher.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = eventDispatcher .next()) { // Log.d("GeoBeagle", "event: " + eventType); if (abortState.isAborted()) { throw new CancelException(); } // File already loaded. if (!eventDispatcher.handleEvent(eventType)) { return -1; } } // Pick up END_DOCUMENT event as well. eventDispatcher.handleEvent(eventType); markAsComplete = true; } finally { eventDispatcher.close(); cacheXmlTagsToSql.close(markAsComplete); } return cacheXmlTagsToSql.getNumberOfCachesLoad(); } public void start() { cacheXmlTagsToSql.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; public interface EventHandler { void endTag(String name, String previousFullPath) throws IOException; void startTag(String name, String mFullPath) throws IOException; boolean text(String fullPath, String text) throws IOException; void start(XmlPullParser xmlPullParser); void end(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import com.google.inject.Singleton; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; import java.util.HashMap; @Singleton public class XmlWriter implements EventHandler { private final TagWriter tagWriter; private Tag tagWpt; private String time; private XmlPullParser xmlPullParser; private static String GPX_WPT = "/gpx/wpt"; private static String GPX_WPTTIME = "/gpx/wpt/time"; private static String GPX_WPTNAME = "/gpx/wpt/name"; private final HashMap<String, String> emptyHashMap; private boolean isWritingCache; @Inject public XmlWriter(TagWriter tagWriter) { this.tagWriter = tagWriter; emptyHashMap = new HashMap<String, String>(); isWritingCache = false; } @Override public void endTag(String name, String previousFullPath) throws IOException { if (!previousFullPath.startsWith(GPX_WPT)) return; if (isWritingCache) tagWriter.endTag(name); if (previousFullPath.equals(GPX_WPT)) { tagWriter.endTag("gpx"); tagWriter.close(); isWritingCache = false; } } @Override public void startTag(String name, String fullPath) throws IOException { if (!fullPath.startsWith(GPX_WPT)) return; HashMap<String, String> attributes = new HashMap<String, String>(); int attributeCount = xmlPullParser.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { attributes.put(xmlPullParser.getAttributeName(i), xmlPullParser.getAttributeValue(i)); } Tag tag = new Tag(name, attributes); if (fullPath.equals(GPX_WPT)) { tagWpt = tag; } else if (isWritingCache) { tagWriter.startTag(tag); } } @Override public boolean text(String fullPath, String text) throws IOException { if (!fullPath.startsWith(GPX_WPT)) return true; if (text.trim().length() == 0) return true; if (fullPath.equals(GPX_WPTTIME)) { time = text; } else if (fullPath.equals(GPX_WPTNAME)) { tagWriter.open(text); tagWriter.startTag(new Tag("gpx", emptyHashMap)); tagWriter.startTag(tagWpt); if (time != null) { tagWriter.startTag(new Tag("time", emptyHashMap)); tagWriter.text(time); tagWriter.endTag("time"); } tagWriter.startTag(new Tag("name", emptyHashMap)); isWritingCache = true; } if (isWritingCache) tagWriter.text(text); return true; } @Override public void start(XmlPullParser xmlPullParser) { this.xmlPullParser = xmlPullParser; tagWriter.start(); } @Override public void end() { tagWriter.end(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import java.io.IOException; public class CacheXmlTagHandler { @SuppressWarnings("unused") public void archived(String attributeValue) { } @SuppressWarnings("unused") public void available(String attributeValue) { } @SuppressWarnings("unused") public void cacheType(String text) throws IOException { } @SuppressWarnings("unused") public void close(boolean success) { } @SuppressWarnings("unused") public void container(String text) throws IOException { } @SuppressWarnings("unused") public void difficulty(String text) throws IOException { } public void end() { } @SuppressWarnings("unused") public void endCache(Source source) throws IOException { } @SuppressWarnings("unused") public boolean gpxTime(String gpxTime) { return false; } @SuppressWarnings("unused") public void groundspeakName(String text) throws IOException { } @SuppressWarnings("unused") public void hint(String text) throws IOException { } @SuppressWarnings("unused") public void lastModified(String trimmedText) { } @SuppressWarnings("unused") public void line(String text) throws IOException { } @SuppressWarnings("unused") public void logDate(String text) throws IOException { } @SuppressWarnings("unused") public void logText(String trimmedText) throws IOException { } @SuppressWarnings("unused") public void logType(String trimmedText) throws IOException { } @SuppressWarnings("unused") public void longDescription(String trimmedText) throws IOException { } @SuppressWarnings("unused") public void open(String path) throws IOException { } @SuppressWarnings("unused") public void placedBy(String trimmedText) throws IOException { } @SuppressWarnings("unused") public void setEncrypted(boolean mLogEncrypted) { } @SuppressWarnings("unused") public void shortDescription(String trimmedText) throws IOException { } public void start() { } public void startCache() { } @SuppressWarnings("unused") public void symbol(String text) { } @SuppressWarnings("unused") public void terrain(String text) throws IOException { } @SuppressWarnings("unused") public void wpt(String latitude, String longitude) { } @SuppressWarnings("unused") public void wptDesc(String cacheName) { } @SuppressWarnings("unused") public void wptName(String wpt) throws IOException { } @SuppressWarnings("unused") public void wptTime(String trimmedText) throws IOException { } @SuppressWarnings("unused") public void logFinder(String text) { } @SuppressWarnings("unused") public void url(String text) throws IOException { } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.inject.Inject; import roboguice.inject.ContextScoped; import android.os.Handler; import android.os.Message; import android.util.Log; @ContextScoped public class MessageHandler extends Handler implements MessageHandlerInterface { public static final String GEOBEAGLE = "GeoBeagle"; static final int MSG_DONE = 1; static final int MSG_PROGRESS = 0; private int mCacheCount; private boolean mLoadAborted; private CacheListRefresh mMenuActionRefresh; private final ProgressDialogWrapper mProgressDialogWrapper; private String mSource; private String mStatus; private String mWaypointId; @Inject public MessageHandler(ProgressDialogWrapper progressDialogWrapper) { mProgressDialogWrapper = progressDialogWrapper; } @Override public void abortLoad() { mLoadAborted = true; mProgressDialogWrapper.dismiss(); } @Override public void handleMessage(Message msg) { Log.d(GEOBEAGLE, "received msg: " + msg.what); switch (msg.what) { case MessageHandler.MSG_PROGRESS: mProgressDialogWrapper.setMessage(mStatus); break; case MessageHandler.MSG_DONE: if (!mLoadAborted) { mProgressDialogWrapper.dismiss(); mMenuActionRefresh.forceRefresh(); } break; default: break; } } @Override public void loadComplete() { sendEmptyMessage(MessageHandler.MSG_DONE); } @Override public void start(CacheListRefresh cacheListRefresh) { mCacheCount = 0; mLoadAborted = false; mMenuActionRefresh = cacheListRefresh; // TODO: move text into resource. mProgressDialogWrapper.show("Sync from sdcard", "Please wait..."); } @Override public void updateName(String name) { mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } @Override public void updateSource(String text) { mSource = text; mStatus = "Opening: " + mSource + "..."; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } @Override public void updateWaypointId(String wpt) { mWaypointId = wpt; } @Override public void updateStatus(String status) { mStatus = status; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } @Override public void deletingCacheFiles() { mStatus = "Deleting old cache files...."; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.database.CacheSqlWriter; import com.google.code.geobeagle.database.ClearCachesFromSource; import com.google.code.geobeagle.database.GpxTableWriter; import com.google.code.geobeagle.database.GpxTableWriterGpxFiles; import com.google.code.geobeagle.database.Tag; import com.google.code.geobeagle.database.TagWriter; import com.google.inject.Inject; import android.util.Log; /** * @author sng */ public class CacheTagSqlWriter { private final CacheTypeFactory mCacheTypeFactory; private CacheType mCacheType; private final CacheSqlWriter mCacheWriter; private final GpxTableWriterGpxFiles mGpxWriter; private int mContainer; private int mDifficulty; private String mGpxName; private CharSequence mId; private double mLatitude; private double mLongitude; private CharSequence mName; private int mTerrain; private final TagWriter mTagWriter; private boolean mArchived; private boolean mAvailable; private boolean mFound; @Inject public CacheTagSqlWriter(CacheSqlWriter cacheSqlWriter, GpxTableWriterGpxFiles gpxTableWriterGpxFiles, CacheTypeFactory cacheTypeFactory, TagWriter tagWriter) { mCacheWriter = cacheSqlWriter; mGpxWriter = gpxTableWriterGpxFiles; mCacheTypeFactory = cacheTypeFactory; mTagWriter = tagWriter; } public void cacheName(String name) { mName = name; } public void cacheType(String type) { mCacheType = mCacheTypeFactory.fromTag(type); } public void clear() { // TODO: ensure source is not reset mId = mName = null; mLatitude = mLongitude = 0; mCacheType = CacheType.NULL; mDifficulty = 0; mTerrain = 0; mContainer = 0; mArchived = false; mAvailable = true; mFound = false; } public void container(String container) { mContainer = mCacheTypeFactory.container(container); } public void difficulty(String difficulty) { mDifficulty = mCacheTypeFactory.stars(difficulty); } public void end(ClearCachesFromSource clearCachesFromSource) { clearCachesFromSource.clearEarlierLoads(); } public void gpxName(String gpxName) { mGpxName = gpxName; Log.d("GeoBeagle", this + ": CacheTagSqlWriter:gpxName: " + mGpxName); } /** * @return true if we should load this gpx; false if the gpx is already * loaded. */ public boolean gpxTime(ClearCachesFromSource clearCachesFromSource, GpxTableWriter gpxTableWriter, String gpxTime) { String sqlDate = isoTimeToSql(gpxTime); Log.d("GeoBeagle", this + ": CacheTagSqlWriter:gpxTime: " + mGpxName); if (gpxTableWriter.isGpxAlreadyLoaded(mGpxName, sqlDate)) { return false; } clearCachesFromSource.clearCaches(mGpxName); return true; } public void id(CharSequence id) { mId = id; } public String isoTimeToSql(String gpxTime) { return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19); } public void latitudeLongitude(String latitude, String longitude) { mLatitude = Double.parseDouble(latitude); mLongitude = Double.parseDouble(longitude); } public void startWriting() { mCacheWriter.startWriting(); } public void stopWriting(boolean successfulGpxImport) { mCacheWriter.stopWriting(); if (successfulGpxImport) mGpxWriter.writeGpx(mGpxName); } public void symbol(String symbol) { if (symbol.equals("Geocache Found")) mFound = true; } public void terrain(String terrain) { mTerrain = mCacheTypeFactory.stars(terrain); } public void write(Source source) { mCacheWriter.insertAndUpdateCache(mId, mName, mLatitude, mLongitude, source, mGpxName, mCacheType, mDifficulty, mTerrain, mContainer, mAvailable, mArchived, mFound); if (mFound) mTagWriter.add(mId, Tag.FOUND, false); } public void archived(boolean fArchived) { mArchived = fArchived; } public void available(boolean fAvailable) { mAvailable = fAvailable; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.preferences.Preferences; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.code.geobeagle.xmlimport.ImportException; import com.google.inject.Inject; import android.content.SharedPreferences; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class GpxAndZipFiles { public static class GpxAndZipFilenameFilter implements FilenameFilter { private final GpxFilenameFilter mGpxFilenameFilter; @Inject public GpxAndZipFilenameFilter(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } @Override public boolean accept(File dir, String name) { String lowerCaseName = name.toLowerCase(); if (!lowerCaseName.startsWith(".") && lowerCaseName.endsWith(".zip")) return true; return mGpxFilenameFilter.accept(lowerCaseName); } } public static class GpxFilenameFilter { public boolean accept(String name) { String lowerCaseName = name.toLowerCase(); return !lowerCaseName.startsWith(".") && (lowerCaseName.endsWith(".gpx") || lowerCaseName.endsWith(".loc")); } } public static class GpxFilesAndZipFilesIter { private final String[] mFileList; private final GpxFileIterAndZipFileIterFactory mGpxAndZipFileIterFactory; private int mIxFileList; private IGpxReaderIter mSubIter; GpxFilesAndZipFilesIter(String[] fileList, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) { mFileList = fileList; mGpxAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; mIxFileList = 0; } public boolean hasNext() throws IOException { // Iterate through actual zip, loc, and gpx files on the filesystem. // If a zip file, a sub iterator will walk through the zip file // contents, otherwise the sub iterator will return just the loc/gpx // file. if (mSubIter != null && mSubIter.hasNext()) return true; while (mIxFileList < mFileList.length) { mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]); if (mSubIter.hasNext()) return true; } return false; } public IGpxReader next() throws IOException { return mSubIter.next(); } } private final FilenameFilter mFilenameFilter; private final GpxFileIterAndZipFileIterFactory mGpxFileIterAndZipFileIterFactory; private final GeoBeagleEnvironment mGeoBeagleEnvironment; private final SharedPreferences mSharedPreferences; @Inject public GpxAndZipFiles(GpxAndZipFilenameFilter filenameFilter, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory, GeoBeagleEnvironment geoBeagleEnvironment, SharedPreferences sharedPreferences) { mFilenameFilter = filenameFilter; mGpxFileIterAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; mGeoBeagleEnvironment = geoBeagleEnvironment; mSharedPreferences = sharedPreferences; } public GpxFilesAndZipFilesIter iterator() throws ImportException { String[] fileList; if (!mSharedPreferences.getBoolean(Preferences.SDCARD_ENABLED, true)) { fileList = new String[0]; } else { String gpxDir = mGeoBeagleEnvironment.getImportFolder(); fileList = new File(gpxDir).list(mFilenameFilter); if (fileList == null) throw new ImportException(R.string.error_cant_read_sd, gpxDir); } mGpxFileIterAndZipFileIterFactory.resetAborter(); return new GpxFilesAndZipFilesIter(fileList, mGpxFileIterAndZipFileIterFactory); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.gpx; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String path; public GpxReader(String path) { this.path = path; } @Override public String getFilename() { return path; } @Override public Reader open() throws FileNotFoundException { return new BufferedReader(new FileReader(path)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.gpx; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; import com.google.inject.Provider; public class GpxFileOpener { public static class GpxFileIter implements IGpxReaderIter { private final Provider<AbortState> aborterProvider; private String filename; public GpxFileIter(Provider<AbortState> aborterProvider, String filename) { this.aborterProvider = aborterProvider; this.filename = filename; } @Override public boolean hasNext() { if (aborterProvider.get().isAborted()) return false; return filename != null; } @Override public IGpxReader next() { final IGpxReader gpxReader = new GpxReader(filename); filename = null; return gpxReader; } } private final Provider<AbortState> aborterProvider; private final String filename; public GpxFileOpener(String filename, Provider<AbortState> aborterProvider) { this.filename = filename; this.aborterProvider = aborterProvider; } public GpxFileIter iterator() { return new GpxFileIter(aborterProvider, filename); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.FileNotFoundException; import java.io.Reader; public interface IGpxReader { String getFilename(); Reader open() throws FileNotFoundException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.IOException; public interface IGpxReaderIter { public boolean hasNext() throws IOException; public IGpxReader next() throws IOException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String filename; private final Reader reader; GpxReader(String filename, Reader reader) { this.filename = filename; this.reader = reader; } @Override public String getFilename() { return filename; } @Override public Reader open() { return reader; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.ZipEntry; public class ZipFileOpener { public static class ZipFileIter implements IGpxReaderIter { private final Provider<AbortState> mAborterProvider; private ZipEntry mNextZipEntry; private final ZipInputFileTester mZipInputFileTester; private final GpxZipInputStream mZipInputStream; ZipFileIter(GpxZipInputStream zipInputStream, Provider<AbortState> aborterProvider, ZipInputFileTester zipInputFileTester, ZipEntry nextZipEntry) { mZipInputStream = zipInputStream; mNextZipEntry = nextZipEntry; mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; } ZipFileIter(GpxZipInputStream zipInputStream, Provider<AbortState> aborterProvider, ZipInputFileTester zipInputFileTester) { mZipInputStream = zipInputStream; mNextZipEntry = null; mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; } @Override public boolean hasNext() throws IOException { // Iterate through zip file entries. if (mNextZipEntry == null) { do { if (mAborterProvider.get().isAborted()) break; mNextZipEntry = mZipInputStream.getNextEntry(); } while (mNextZipEntry != null && !mZipInputFileTester.isValid(mNextZipEntry)); } return mNextZipEntry != null; } @Override public IGpxReader next() throws IOException { final String name = mNextZipEntry.getName(); mNextZipEntry = null; return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream())); } } public static class ZipInputFileTester { private final GpxFilenameFilter mGpxFilenameFilter; @Inject public ZipInputFileTester(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } public boolean isValid(ZipEntry zipEntry) { return (!zipEntry.isDirectory() && mGpxFilenameFilter.accept(zipEntry.getName())); } } private final Provider<AbortState> mAborterProvider; private final String mFilename; private final ZipInputFileTester mZipInputFileTester; private final ZipInputStreamFactory mZipInputStreamFactory; public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory, ZipInputFileTester zipInputFileTester, Provider<AbortState> aborterProvider) { mFilename = filename; mZipInputStreamFactory = zipInputStreamFactory; mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; } public ZipFileIter iterator() throws IOException { return new ZipFileIter(mZipInputStreamFactory.create(mFilename), mAborterProvider, mZipInputFileTester); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class GpxZipInputStream { private ZipEntry mNextEntry; private final ZipInputStream mZipInputStream; public GpxZipInputStream(ZipInputStream zipInputStream) { mZipInputStream = zipInputStream; } ZipEntry getNextEntry() throws IOException { mNextEntry = mZipInputStream.getNextEntry(); return mNextEntry; } InputStream getStream() { return mZipInputStream; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.database.ClearCachesFromSource; import com.google.code.geobeagle.database.GpxTableWriter; import com.google.inject.Inject; import roboguice.inject.ContextScoped; import java.io.File; import java.io.IOException; @ContextScoped public class CacheXmlTagsToSql extends CacheXmlTagHandler { static public class CacheXmlTagsToSqlFactory { private final CacheTagSqlWriter mCacheTagSqlWriter; private final ImportWakeLock mWakeLock; private final GeoBeagleEnvironment mGeoBeagleEnvironment; @Inject CacheXmlTagsToSqlFactory(CacheTagSqlWriter cacheTagSqlWriter, ImportWakeLock importWakeLock, GeoBeagleEnvironment geoBeagleEnvironment) { mCacheTagSqlWriter = cacheTagSqlWriter; mWakeLock = importWakeLock; mGeoBeagleEnvironment = geoBeagleEnvironment; } CacheXmlTagsToSql create(MessageHandlerInterface messageHandlerInterface, GpxTableWriter gpxTableWriter, ClearCachesFromSource clearCachesFromSource) { return new CacheXmlTagsToSql(mCacheTagSqlWriter, messageHandlerInterface, mWakeLock, mGeoBeagleEnvironment, gpxTableWriter, clearCachesFromSource); } } private String mCacheName = ""; private final CacheTagSqlWriter mCacheTagSqlWriter; private final MessageHandlerInterface mMessageHandler; private final ImportWakeLock mWakeLock; private final GeoBeagleEnvironment mGeoBeagleEnvironment; private int mCachesLoaded; private final GpxTableWriter mGpxWriter; private final ClearCachesFromSource mClearCachesFromSource; CacheXmlTagsToSql(CacheTagSqlWriter cacheTagSqlWriter, MessageHandlerInterface messageHandler, ImportWakeLock importWakeLock, GeoBeagleEnvironment geoBeagleEnvironment, GpxTableWriter gpxTableWriter, ClearCachesFromSource clearCachesFromSource) { mCacheTagSqlWriter = cacheTagSqlWriter; mMessageHandler = messageHandler; mWakeLock = importWakeLock; mGeoBeagleEnvironment = geoBeagleEnvironment; mGpxWriter = gpxTableWriter; mClearCachesFromSource = clearCachesFromSource; } @Override public void cacheType(String text) { mCacheTagSqlWriter.cacheType(text); } @Override public void close(boolean success) { mCacheTagSqlWriter.stopWriting(success); } public int getNumberOfCachesLoad() { return mCachesLoaded; } @Override public void container(String text) { mCacheTagSqlWriter.container(text); } @Override public void difficulty(String text) { mCacheTagSqlWriter.difficulty(text); } @Override public void end() { mCacheTagSqlWriter.end(mClearCachesFromSource); } @Override public void endCache(Source source) throws IOException { mMessageHandler.updateName(mCacheName); mCacheTagSqlWriter.write(source); mCachesLoaded++; } @Override public boolean gpxTime(String gpxTime) { return mCacheTagSqlWriter.gpxTime(mClearCachesFromSource, mGpxWriter, gpxTime); } @Override public void groundspeakName(String text) { mCacheTagSqlWriter.cacheName(text); } @Override public void open(String path) { mMessageHandler.updateSource(path); mCacheTagSqlWriter.startWriting(); mCacheTagSqlWriter.gpxName(path); } @Override public void start() { mCachesLoaded = 0; new File(mGeoBeagleEnvironment.getDetailsDirectory()).mkdirs(); } @Override public void startCache() { mCacheName = ""; mCacheTagSqlWriter.clear(); } @Override public void symbol(String text) { mCacheTagSqlWriter.symbol(text); } @Override public void terrain(String text) { mCacheTagSqlWriter.terrain(text); } @Override public void wpt(String latitude, String longitude) { mCacheTagSqlWriter.latitudeLongitude(latitude, longitude); } @Override public void wptDesc(String cacheName) { mCacheName = cacheName; mCacheTagSqlWriter.cacheName(cacheName); } @Override public void wptName(String wpt) throws IOException { mCacheTagSqlWriter.id(wpt); mMessageHandler.updateWaypointId(wpt); mWakeLock.acquire(GpxToCache.WAKELOCK_DURATION); } @Override public void archived(String attributeValue) { if (attributeValue != null) mCacheTagSqlWriter.archived(attributeValue.equalsIgnoreCase("True")); } @Override public void available(String attributeValue) { if (attributeValue != null) mCacheTagSqlWriter.available(attributeValue.equalsIgnoreCase("True")); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.database.GpxTableWriterGpxFiles; import com.google.inject.Inject; import android.util.Log; import java.io.File; import java.text.SimpleDateFormat; public class LocAlreadyLoadedChecker { private final GpxTableWriterGpxFiles gpxTableWriterGpxFiles; private final SimpleDateFormat simpleDateFormat; // For testing. public LocAlreadyLoadedChecker(GpxTableWriterGpxFiles gpxTableWriterGpxFiles, SimpleDateFormat dateFormat) { this.gpxTableWriterGpxFiles = gpxTableWriterGpxFiles; this.simpleDateFormat = dateFormat; } @Inject public LocAlreadyLoadedChecker(GpxTableWriterGpxFiles gpxTableWriterGpxFiles) { this.gpxTableWriterGpxFiles = gpxTableWriterGpxFiles; this.simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); } boolean isAlreadyLoaded(String source) { int len = source.length(); String extension = source.substring(Math.max(0, len - 4), len).toLowerCase(); if (!extension.equalsIgnoreCase(".loc")) return false; File file = new File(source); long lastModified = file.lastModified(); String sqlDate = simpleDateFormat.format(lastModified); Log.d("GeoBeagle", "GET NAME: " + sqlDate + ", " + source + ", " + lastModified); if (gpxTableWriterGpxFiles.isGpxAlreadyLoaded(file.getName(), sqlDate)) { return true; } return false; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import com.google.inject.Singleton; import android.content.res.Resources; @Singleton public class SyncCollectingParameter { private String log; private final Resources resources; @Inject public SyncCollectingParameter(Resources resources) { this.resources = resources; reset(); } public void Log(int resId, Object... args) { Log(resources.getString(resId, args)); } public void NestedLog(int resId, Object... args) { Log(" " + resources.getString(resId, args)); } public void Log(String s) { this.log += s + "\n"; } public String getLog() { return this.log; } public void reset() { this.log = ""; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; import java.util.Arrays; import java.util.List; public class EventHandlerSqlAndFileWriter implements EventHandler { static class EventHandlerSqlAndFileWriterFactory { private final XmlWriter xmlWriter; @Inject public EventHandlerSqlAndFileWriterFactory(XmlWriter xmlWriter) { this.xmlWriter = xmlWriter; } public EventHandlerSqlAndFileWriter create(CacheXmlTagsToSql cacheXmlTagsToSql) { return new EventHandlerSqlAndFileWriter(xmlWriter, cacheXmlTagsToSql); } } private final List<EventHandler> eventHandlers; public EventHandlerSqlAndFileWriter(XmlWriter xmlWriter, CacheXmlTagsToSql cacheXmlTagsToSql) { this.eventHandlers = Arrays.asList(xmlWriter, new EventHandlerGpx(cacheXmlTagsToSql)); } @Override public void endTag(String name, String previousFullPath) throws IOException { for (EventHandler eventHandler : eventHandlers) { eventHandler.endTag(name, previousFullPath); } } @Override public void startTag(String name, String fullPath) throws IOException { for (EventHandler eventHandler : eventHandlers) { eventHandler.startTag(name, fullPath); } } @Override public boolean text(String fullPath, String text) throws IOException { boolean ret = true; for (EventHandler eventHandler : eventHandlers) { ret &= eventHandler.text(fullPath, text); } return ret; } @Override public void start(XmlPullParser xmlPullParser) { for (EventHandler eventHandler : eventHandlers) { eventHandler.start(xmlPullParser); } } @Override public void end() { for (EventHandler eventHandler : eventHandlers) { eventHandler.end(); } } }
Java
package com.google.code.geobeagle.xmlimport; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; public class XmlimportAnnotations { private XmlimportAnnotations() { } @BindingAnnotation @Target( { FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public static @interface SDCard { } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import roboguice.inject.ContextScoped; import android.content.Context; import android.os.PowerManager; import android.os.PowerManager.WakeLock; @ContextScoped class ImportWakeLock { private final WakeLock wakeLock; @Inject ImportWakeLock(Context context) { PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); this.wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Importing"); } public void acquire(long duration) { wakeLock.acquire(duration); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.bcaching.ImportBCachingWorker; import com.google.code.geobeagle.bcaching.communication.BCachingException; import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import roboguice.util.RoboThread; import android.util.Log; import java.io.FileNotFoundException; import java.io.IOException; public class ImportThread extends RoboThread { static class ImportThreadFactory { private final GpxSyncerFactory gpxSyncerFactory; private final Provider<ImportBCachingWorker> importBCachingWorkerProvider; private final ErrorDisplayer errorDisplayer; private final BCachingStartTime bcachingStartTime; private final DbFrontend dbFrontend; private final SyncCollectingParameter syncCollectingParameter; @Inject ImportThreadFactory(Injector injector) { this.gpxSyncerFactory = injector.getInstance(GpxSyncerFactory.class); this.importBCachingWorkerProvider = injector.getProvider(ImportBCachingWorker.class); this.errorDisplayer = injector.getInstance(ErrorDisplayer.class); this.bcachingStartTime = injector.getInstance(BCachingStartTime.class); this.dbFrontend = injector.getInstance(DbFrontend.class); this.syncCollectingParameter = injector.getInstance(SyncCollectingParameter.class); } ImportThread create() { return new ImportThread(gpxSyncerFactory.create(), importBCachingWorkerProvider.get(), errorDisplayer, bcachingStartTime, dbFrontend, syncCollectingParameter); } } private final GpxSyncer gpxSyncer; private final ImportBCachingWorker importBCachingWorker; private boolean isAlive; private final ErrorDisplayer errorDisplayer; private final BCachingStartTime bcachingStartTime; private final DbFrontend dbFrontend; private final SyncCollectingParameter syncCollectingParameter; ImportThread(GpxSyncer gpxSyncer, ImportBCachingWorker importBCachingWorker, ErrorDisplayer errorDisplayer, BCachingStartTime bcachingStartTime, DbFrontend dbFrontend, SyncCollectingParameter syncCollectingParameter) { this.gpxSyncer = gpxSyncer; this.importBCachingWorker = importBCachingWorker; this.errorDisplayer = errorDisplayer; this.bcachingStartTime = bcachingStartTime; this.dbFrontend = dbFrontend; this.syncCollectingParameter = syncCollectingParameter; } @Override public void run() { isAlive = true; try { syncCollectingParameter.reset(); gpxSyncer.sync(syncCollectingParameter); importBCachingWorker.sync(syncCollectingParameter); errorDisplayer.displayError(R.string.string, syncCollectingParameter.getLog()); } catch (final FileNotFoundException e) { errorDisplayer.displayError(R.string.error_opening_file, e.getMessage()); return; } catch (IOException e) { errorDisplayer.displayError(R.string.error_reading_file, e.getMessage()); return; } catch (ImportException e) { errorDisplayer.displayError(e.getError(), e.getPath()); return; } catch (BCachingException e) { errorDisplayer.displayError(R.string.problem_importing_from_bcaching, e.getLocalizedMessage()); } catch (CancelException e) { // Toast can't be displayed in this thread; it must be displayed in // main UI thread. return; } finally { Log.d("GeoBeagle", "<<< Syncing"); isAlive = false; } } public boolean isAliveHack() { return isAlive; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import android.content.SharedPreferences; import android.os.Environment; public class GeoBeagleEnvironment { public static final String IMPORT_FOLDER = "import-folder"; private final SharedPreferences sharedPreferences; private static final String DETAILS_DIR = "GeoBeagle/data/"; private static final String FIELDNOTES_FILE = "GeoBeagleFieldNotes.txt"; @Inject GeoBeagleEnvironment(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public String getExternalStorageDir() { return Environment.getExternalStorageDirectory().getAbsolutePath(); } public String getDetailsDirectory() { return getExternalStorageDir() + "/" + GeoBeagleEnvironment.DETAILS_DIR; } public String getVersionPath() { return getDetailsDirectory() + "/VERSION"; } public String getOldDetailsDirectory() { return getExternalStorageDir() + "/" + "GeoBeagle"; } public String getImportFolder() { String string = sharedPreferences.getString(IMPORT_FOLDER, Environment .getExternalStorageDirectory() + "/Download"); if ((!string.endsWith("/"))) return string + "/"; return string; } public String getFieldNotesFilename() { return getExternalStorageDir() + "/" + FIELDNOTES_FILE; } }
Java
package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.ProgressDialog; import android.content.Context; public class ProgressDialogWrapper { private final Provider<Context> mContextProvider; private ProgressDialog mProgressDialog; @Inject public ProgressDialogWrapper(Provider<Context> context) { mContextProvider = context; } public void dismiss() { if (mProgressDialog != null) mProgressDialog.dismiss(); } public void setMessage(CharSequence message) { mProgressDialog.setMessage(message); } public void show(String title, String msg) { mProgressDialog = ProgressDialog.show(mContextProvider.get(), title, msg); // mProgressDialog.setCancelable(true); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import java.util.HashMap; class Tag { final HashMap<String, String> attributes; final String name; Tag(String name, HashMap<String, String> attributes) { this.name = name; this.attributes = attributes; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; @SuppressWarnings("serial") public class ImportException extends Exception { private final int error; private final String path; public ImportException(int error, String path) { super(); this.error = error; this.path = path; } public int getError() { return error; } public String getPath() { return path; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; public class EventHandlerGpx implements EventHandler { private final CacheXmlTagHandler cacheXmlTagHandler; private XmlPullParser xmlPullParser; public EventHandlerGpx(CacheXmlTagHandler cacheXmlTagHandler) { this.cacheXmlTagHandler = cacheXmlTagHandler; } @Override public void endTag(String name, String previousFullPath) throws IOException { GpxPath.fromString(previousFullPath).endTag(cacheXmlTagHandler); } @Override public void startTag(String name, String fullPath) throws IOException { GpxPath.fromString(fullPath).startTag(xmlPullParser, cacheXmlTagHandler); } @Override public boolean text(String fullPath, String text) throws IOException { return GpxPath.fromString(fullPath).text(text, cacheXmlTagHandler); } @Override public void start(XmlPullParser xmlPullParser) { this.xmlPullParser = xmlPullParser; } @Override public void end() { } }
Java
package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import android.os.Message; public interface MessageHandlerInterface { public abstract void abortLoad(); public abstract void handleMessage(Message msg); public abstract void loadComplete(); public abstract void start(CacheListRefresh cacheListRefresh); public abstract void updateName(String name); public abstract void updateSource(String text); public abstract void updateWaypointId(String wpt); public abstract void updateStatus(String status); public abstract void deletingCacheFiles(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.code.geobeagle.xmlimport.EmotifierPatternProvider; import com.google.inject.Inject; import java.net.URLEncoder; import java.util.regex.Matcher; public class Emotifier { public static final String ICON_PREFIX = "<img src='file:///android_asset/"; public static final String ICON_SUFFIX = ".gif' border=0 align=bottom>"; public static final String EMOTICON_PREFIX = ICON_PREFIX + "icon_smile_"; private final EmotifierPatternProvider patternProvider; @Inject public Emotifier(EmotifierPatternProvider patternProvider) { this.patternProvider = patternProvider; } String emotify(String text) { Matcher matcher = patternProvider.get().matcher(text); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String match = matcher.group(1); String encoded = URLEncoder.encode(match).replace("%", ""); matcher.appendReplacement(sb, EMOTICON_PREFIX + encoded + ICON_SUFFIX); } matcher.appendTail(sb); return sb.toString(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.inject.Inject; import java.io.IOException; public class FileDataVersionWriter { private final WriterWrapper writerWrapper; private final GeoBeagleEnvironment geoBeagleEnvironment; @Inject FileDataVersionWriter(WriterWrapper writerWrapper, GeoBeagleEnvironment geoBeagleEnvironment) { this.writerWrapper = writerWrapper; this.geoBeagleEnvironment = geoBeagleEnvironment; } public void writeVersion() throws IOException { String versionPath = geoBeagleEnvironment.getVersionPath(); writerWrapper.mkdirs(versionPath); writerWrapper.open(versionPath); writerWrapper.write("1"); writerWrapper.close(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.inject.Inject; import android.content.Context; import android.text.format.DateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; class RelativeDateFormatter { private final Calendar gmtCalendar; @Inject RelativeDateFormatter() { this.gmtCalendar = Calendar.getInstance(); } String getRelativeTime(Context context, String utcTime) throws ParseException { long now = System.currentTimeMillis(); gmtCalendar.setTime(parse(utcTime)); long timeInMillis = gmtCalendar.getTimeInMillis(); long duration = Math.abs(now - timeInMillis); if (duration < DateUtils.WEEK_IN_MILLIS) { return (String)DateUtils.getRelativeTimeSpanString(timeInMillis, now, DateUtils.DAY_IN_MILLIS, 0); } return (String)DateUtils.getRelativeTimeSpanString(context, timeInMillis, false); } private Date parse(String input) throws java.text.ParseException { final String formatString = "yyyy-MM-dd'T'HH:mm:ss Z"; SimpleDateFormat df = new SimpleDateFormat(formatString); String s; try { s = input.substring(0, 19) + " +0000"; } catch (Exception e) { throw new ParseException(null, 0); } return df.parse(s); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.inject.Inject; import com.google.inject.Singleton; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.widget.Toast; import java.io.File; @Singleton class SdDatabaseOpener { static final int DATABASE_VERSION = 6; private final GeoBeagleEnvironment geoBeagleEnvironment; private final ShowToastOnUiThread showToastOnUiThread; @Inject SdDatabaseOpener(GeoBeagleEnvironment geoBeagleEnvironment, ShowToastOnUiThread showToastOnUiThread) { this.geoBeagleEnvironment = geoBeagleEnvironment; this.showToastOnUiThread = showToastOnUiThread; } void delete() { new File(geoBeagleEnvironment.getExternalStorageDir() + "/geobeagle.db").delete(); } SQLiteDatabase open() { SQLiteDatabase sqliteDatabase = SQLiteDatabase.openDatabase( geoBeagleEnvironment.getExternalStorageDir() + "/geobeagle.db", null, SQLiteDatabase.CREATE_IF_NECESSARY); int oldVersion = sqliteDatabase.getVersion(); Log.d("GeoBeagle", "SDDatabase verson: " + oldVersion); if (oldVersion < DATABASE_VERSION) { if (oldVersion > 0) showToastOnUiThread.showToast(R.string.upgrading_database, Toast.LENGTH_LONG); if (oldVersion < 6) { sqliteDatabase.execSQL("DROP TABLE IF EXISTS DETAILS"); } sqliteDatabase .execSQL("CREATE TABLE IF NOT EXISTS Details (CacheId TEXT PRIMARY KEY, Details TEXT)"); sqliteDatabase.setVersion(DATABASE_VERSION); } return sqliteDatabase; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.inject.Inject; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class DetailsDatabaseReader { private static final String TABLE_DETAILS = "Details"; private static final String COLUMN_DETAILS = "Details"; private final SdDatabaseOpener sdDatabaseOpener; private final String[] columns = new String[] { COLUMN_DETAILS }; @Inject DetailsDatabaseReader(SdDatabaseOpener sdDatabaseOpener) { this.sdDatabaseOpener = sdDatabaseOpener; } public String read(CharSequence cacheId) { SQLiteDatabase sdDatabase = sdDatabaseOpener.open(); String[] selectionArgs = { (String)cacheId }; Cursor cursor = sdDatabase.query(TABLE_DETAILS, columns, "CacheId=?", selectionArgs, null, null, null); Log.d("GeoBeagle", "count: " + cursor.getCount() + ", " + cursor.getColumnCount()); cursor.moveToFirst(); if (cursor.getCount() < 1) return null; String details = cursor.getString(0); cursor.close(); Log.d("GeoBeagle", "DETAILS: " + details); sdDatabase.close(); return details; } }
Java
package com.google.code.geobeagle.cachedetails; import java.io.IOException; public interface NullWriterOpener { public void open() throws IOException; }
Java