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.cachedetails;
import android.content.Context;
import android.widget.Toast;
class ShowToastRunnable implements Runnable {
private final Context context;
private final int msg;
private final int length;
public ShowToastRunnable(Context context, int msg, int length) {
this.context = context;
this.msg = msg;
this.length = length;
}
@Override
public void run() {
Toast.makeText(context, msg, length).show();
}
}
| 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.activity.compass.Util;
import com.google.inject.Inject;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.text.ParseException;
public class CacheDetailsHtmlWriter {
public static String replaceIllegalFileChars(String wpt) {
return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_");
}
private final Context context;
private final Emotifier emotifier;
private final HtmlWriter htmlWriter;
private String latitude;
private int logNumber;
private String longitude;
private String time;
private String finder;
private String logType;
private String relativeTime;
private final RelativeDateFormatter relativeDateFormatter;
private String wpt;
@Inject
public CacheDetailsHtmlWriter(HtmlWriter htmlWriter,
Emotifier emotifier,
Context context,
RelativeDateFormatter relativeDateFormatter) {
this.htmlWriter = htmlWriter;
this.emotifier = emotifier;
this.context = context;
this.relativeDateFormatter = relativeDateFormatter;
}
public void close() throws IOException {
htmlWriter.writeFooter();
htmlWriter.close();
latitude = longitude = time = finder = logType = relativeTime = "";
logNumber = 0;
}
public void latitudeLongitude(String latitude, String longitude) {
this.latitude = (String)Util.formatDegreesAsDecimalDegreesString(Double.valueOf(latitude));
this.longitude = (String)Util
.formatDegreesAsDecimalDegreesString(Double.valueOf(longitude));
}
public void logType(String trimmedText) {
logType = Emotifier.ICON_PREFIX + "log_" + trimmedText.replace(' ', '_').replace('\'', '_')
+ Emotifier.ICON_SUFFIX;
}
public void placedBy(String text) throws IOException {
Log.d("GeoBeagle", "PLACED BY: " + time);
String on = "";
try {
on = relativeDateFormatter.getRelativeTime(context, time);
} catch (ParseException e) {
on = "PARSE ERROR";
}
writeField("Placed by", text);
writeField("Placed on", on);
}
public void wptTime(String time) {
this.time = time;
}
public void writeField(String fieldName, String field) throws IOException {
htmlWriter.writeln("<font color=grey>" + fieldName + ":</font> " + field);
}
public void writeHint(String text) throws IOException {
htmlWriter
.write("<a class='hint hint_loading' id=hint_link onclick=\"dht('hint_link');return false;\" href=#>"
+ "Encrypt</a>");
htmlWriter.write("<div class=hint_loading id=hint_link_text>" + text + "</div>");
}
public void writeLine(String text) throws IOException {
htmlWriter.writeln(text);
}
public void writeLogDate(String text) throws IOException {
htmlWriter.writeSeparator();
try {
relativeTime = relativeDateFormatter.getRelativeTime(context, text);
} catch (ParseException e) {
htmlWriter.writeln("error parsing date: " + e.getLocalizedMessage());
}
}
public void writeLogText(String text, boolean encoded) throws IOException {
String f;
htmlWriter.writeln("<b>" + logType + " " + relativeTime + " by " + finder + "</b>");
if (encoded)
f = "<a class=hint id=log_%1$s onclick=\"dht('log_%1$s');return false;\" "
+ "href=#>Encrypt</a><div class=hint_text id=log_%1$s_text>%2$s</div>";
else
f = "%2$s";
htmlWriter.writeln(String.format(f, logNumber++, emotifier.emotify(text)));
}
public void writeLongDescription(String trimmedText) throws IOException {
htmlWriter.write(trimmedText);
htmlWriter.writeSeparator();
}
public void writeName(String name) throws IOException {
htmlWriter.write("<center><h3>" + name + "</h3></center>\n");
}
public void writeShortDescription(String trimmedText) throws IOException {
htmlWriter.writeSeparator();
htmlWriter.writeln(trimmedText);
htmlWriter.writeln("");
}
public void writeWptName(String wpt) throws IOException {
htmlWriter.open();
htmlWriter.writeHeader();
writeField("Location", latitude + ", " + longitude);
latitude = longitude = null;
this.wpt = wpt;
}
public void writeLogFinder(String finder) {
this.finder = finder;
}
public void writeUrl(String text) throws IOException {
writeField("Name", "<a href=" + text + ">" + wpt + "</a>");
}
}
| 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 java.io.IOException;
public interface Writer {
public void close() throws IOException;
// public void open(String path, String wpt) throws IOException;
public void write(String str) throws IOException;
public boolean isOpen();
void mkdirs(String 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.cachedetails;
import com.google.inject.Singleton;
import java.io.IOException;
import java.io.StringWriter;
//TODO: remove singleton.
@Singleton
public class StringWriterWrapper implements com.google.code.geobeagle.cachedetails.Writer,
NullWriterOpener {
private final StringWriter stringWriter;
public StringWriterWrapper() {
this.stringWriter = new StringWriter();
}
@Override
public void close() throws IOException {
}
@Override
public boolean isOpen() {
return true;
}
@Override
public void open() throws IOException {
stringWriter.getBuffer().setLength(0);
}
public String getString() {
return stringWriter.toString();
}
@Override
public void write(String str) throws IOException {
// Log.d("GeoBeagle", ":: " + str);
stringWriter.write(str);
}
@Override
public void mkdirs(String 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.cachedetails;
import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment;
import com.google.inject.Inject;
public class FilePathStrategy {
private final GeoBeagleEnvironment geoBeagleEnvironment;
@Inject
public
FilePathStrategy(GeoBeagleEnvironment geoBeagleEnvironment) {
this.geoBeagleEnvironment = geoBeagleEnvironment;
}
private static String replaceIllegalFileChars(String wpt) {
return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_");
}
public String getPath(CharSequence gpxName, String wpt, String extension) {
String string = geoBeagleEnvironment.getDetailsDirectory() + gpxName + "/"
+ String.valueOf(Math.abs(wpt.hashCode()) % 16) + "/"
+ replaceIllegalFileChars(wpt) + "." + extension;
return string;
}
}
| 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 com.google.inject.Provider;
import android.app.Activity;
import android.content.Context;
class ShowToastOnUiThread {
@Inject
public ShowToastOnUiThread(Provider<Context> contextProvider,
Provider<Activity> activityProvider) {
this.contextProvider = contextProvider;
this.activityProvider = activityProvider;
}
private final Provider<Context> contextProvider;
private final Provider<Activity> activityProvider;
public void showToast(int msg, int length) {
Runnable showToast = new ShowToastRunnable(contextProvider.get(), msg, length);
activityProvider.get().runOnUiThread(showToast);
}
}
| Java |
package com.google.code.geobeagle.cachedetails;
import java.io.IOException;
public interface FilerWriterOpener {
public void open(String path) 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.cachedetails;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriterWrapper implements com.google.code.geobeagle.cachedetails.Writer,
FilerWriterOpener {
private java.io.Writer mWriter;
@Override
public void close() throws IOException {
mWriter.close();
mWriter = null;
}
@Override
public void open(String path) throws IOException {
mWriter = new BufferedWriter(new FileWriter(path), 4000);
}
@Override
public void mkdirs(String path) {
new File(new File(path).getParent()).mkdirs();
}
@Override
public void write(String str) throws IOException {
if (mWriter == null) {
Log.e("GeoBeagle", "Attempting to write string but no waypoint received yet: " + str);
return;
}
try {
mWriter.write(str);
} catch (IOException e) {
throw new IOException("Error writing line '" + str + "'");
}
}
@Override
public boolean isOpen() {
return mWriter != 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.cachedetails;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
@Singleton
public class DetailsDatabaseWriter {
private SQLiteDatabase sdDatabase;
private final SdDatabaseOpener sdDatabaseOpener;
private final ContentValues contentValues;
@Inject
DetailsDatabaseWriter(SdDatabaseOpener sdDatabaseOpener) {
this.sdDatabaseOpener = sdDatabaseOpener;
contentValues = new ContentValues();
}
public void write(String cacheId, String details) {
contentValues.put("Details", details);
contentValues.put("CacheId", cacheId);
sdDatabase.replace("Details", "Details", contentValues);
}
public void deleteAll() {
sdDatabaseOpener.delete();
}
public void start() {
sdDatabase = sdDatabaseOpener.open();
Log.d("GeoBeagle", "STARTING TRANSACTION");
sdDatabase.beginTransaction();
}
public void end() {
if (sdDatabase == null)
return;
Log.d("GeoBeagle", "DetailsDatabaseWriter::end()");
sdDatabase.setTransactionSuccessful();
sdDatabase.endTransaction();
sdDatabase.close();
sdDatabase = 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.cachedetails;
import com.google.inject.Inject;
import java.io.IOException;
public class HtmlWriter {
private final StringWriterWrapper mWriter;
static final String HEADER = "<html>\n<head>\n"
+ "<script type=\"text/javascript\" src=\"file:///android_asset/rot13.js\"></script>\n"
+ "<style type='text/css'> div.hint_loading { display: none } a.hint_loading { color: gray } "
+ " a.hint_loading:after { content: 'ing hint, please wait...' }</style>\n"
+ "</head>\n<body onLoad=encryptAll()>";
@Inject
public HtmlWriter(StringWriterWrapper writerWrapper) {
mWriter = writerWrapper;
}
public void close() throws IOException {
mWriter.close();
}
public void open() throws IOException {
mWriter.open();
}
public void writeln(String text) throws IOException {
mWriter.write(text + "<br/>\n");
}
public void write(String text) throws IOException {
mWriter.write(text + "\n");
}
public void writeFooter() throws IOException {
mWriter.write(" </body>\n");
mWriter.write("</html>\n");
}
public void writeHeader() throws IOException {
mWriter.write(HEADER);
}
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;
import com.google.android.maps.GeoPoint;
import com.google.code.geobeagle.GeocacheFactory.Provider;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.compass.GeoUtils;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Geocache or letterbox description, id, and coordinates.
*/
public class Geocache implements Parcelable {
static interface AttributeFormatter {
CharSequence formatAttributes(int difficulty, int terrain);
}
static class AttributeFormatterImpl implements AttributeFormatter {
@Override
public CharSequence formatAttributes(int difficulty, int terrain) {
return (difficulty / 2.0) + " / " + (terrain / 2.0);
}
}
static class AttributeFormatterNull implements AttributeFormatter {
@Override
public CharSequence formatAttributes(int difficulty, int terrain) {
return "";
}
}
public static final String CACHE_TYPE = "cacheType";
public static final String CONTAINER = "container";
public static Parcelable.Creator<Geocache> CREATOR = new GeocacheFactory.CreateGeocacheFromParcel();
public static final String DIFFICULTY = "difficulty";
public static final String ID = "id";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String NAME = "name";
public static final String SOURCE_NAME = "sourceName";
public static final String SOURCE_TYPE = "sourceType";
public static final String TERRAIN = "terrain";
public static final String AVAILABLE = "available";
public static final String ARCHIVED = "archived";
private final AttributeFormatter mAttributeFormatter;
private final CacheType mCacheType;
private final int mContainer;
private final int mDifficulty;
private float[] mDistanceAndBearing = new float[2];
private final CharSequence mId;
private final double mLatitude;
private final double mLongitude;
private final CharSequence mName;
private final String mSourceName;
private final Source mSourceType;
private final int mTerrain;
private final boolean mAvailable;
private final boolean mArchived;
Geocache(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container, AttributeFormatter attributeFormatter, boolean available,
boolean archived) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
mSourceType = sourceType;
mSourceName = sourceName;
mCacheType = cacheType;
mDifficulty = difficulty;
mTerrain = terrain;
mContainer = container;
mAttributeFormatter = attributeFormatter;
mArchived = archived;
mAvailable = available;
}
public float[] calculateDistanceAndBearing(Location here) {
if (here != null) {
Location.distanceBetween(here.getLatitude(), here.getLongitude(), getLatitude(),
getLongitude(), mDistanceAndBearing);
return mDistanceAndBearing;
}
mDistanceAndBearing[0] = -1;
mDistanceAndBearing[1] = -1;
return mDistanceAndBearing;
}
@Override
public int describeContents() {
return 0;
}
public CacheType getCacheType() {
return mCacheType;
}
public int getContainer() {
return mContainer;
}
public GeocacheFactory.Provider getContentProvider() {
// Must use toString() rather than mId.subSequence(0,2).equals("GC"),
// because editing the text in android produces a SpannableString rather
// than a String, so the CharSequences won't be equal.
String prefix = mId.subSequence(0, 2).toString();
for (Provider provider : GeocacheFactory.ALL_PROVIDERS) {
if (prefix.equals(provider.getPrefix()))
return provider;
}
return Provider.GROUNDSPEAK;
}
public int getDifficulty() {
return mDifficulty;
}
public CharSequence getFormattedAttributes() {
return mAttributeFormatter.formatAttributes(mDifficulty, mTerrain);
}
public GeoPoint getGeoPoint() {
int latE6 = (int)(mLatitude * GeoUtils.MILLION);
int lonE6 = (int)(mLongitude * GeoUtils.MILLION);
return new GeoPoint(latE6, lonE6);
}
public CharSequence getId() {
return mId;
}
public CharSequence getIdAndName() {
if (mId.length() == 0)
return mName;
else if (mName.length() == 0)
return mId;
else
return mId + ": " + mName;
}
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
public CharSequence getName() {
return mName;
}
public CharSequence getShortId() {
if (mId.length() > 2)
return mId.subSequence(2, mId.length());
return "";
}
public String getSourceName() {
return mSourceName;
}
public Source getSourceType() {
return mSourceType;
}
public int getTerrain() {
return mTerrain;
}
public void saveToBundle(Bundle bundle) {
bundle.putCharSequence(ID, mId);
bundle.putCharSequence(NAME, mName);
bundle.putDouble(LATITUDE, mLatitude);
bundle.putDouble(LONGITUDE, mLongitude);
bundle.putInt(SOURCE_TYPE, mSourceType.toInt());
bundle.putString(SOURCE_NAME, mSourceName);
bundle.putInt(CACHE_TYPE, mCacheType.toInt());
bundle.putInt(DIFFICULTY, mDifficulty);
bundle.putInt(TERRAIN, mTerrain);
bundle.putInt(CONTAINER, mContainer);
bundle.putBoolean(AVAILABLE, mAvailable);
bundle.putBoolean(ARCHIVED, mArchived);
}
@Override
public void writeToParcel(Parcel out, int flags) {
Bundle bundle = new Bundle();
saveToBundle(bundle);
out.writeBundle(bundle);
}
public void writeToPrefs(Editor editor) {
// Must use toString(), see comment above in getCommentProvider.
editor.putString(ID, mId.toString());
editor.putString(NAME, mName.toString());
editor.putFloat(LATITUDE, (float)mLatitude);
editor.putFloat(LONGITUDE, (float)mLongitude);
editor.putInt(SOURCE_TYPE, mSourceType.toInt());
editor.putString(SOURCE_NAME, mSourceName);
editor.putInt(CACHE_TYPE, mCacheType.toInt());
editor.putInt(DIFFICULTY, mDifficulty);
editor.putInt(TERRAIN, mTerrain);
editor.putInt(CONTAINER, mContainer);
editor.putBoolean(AVAILABLE, mAvailable);
editor.putBoolean(ARCHIVED, mArchived);
}
public boolean getAvailable() {
return mAvailable;
}
public boolean getArchived() {
return mArchived;
}
}
| 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.BCachingException;
import com.google.code.geobeagle.bcaching.communication.BCachingListImporterStateless;
import com.google.code.geobeagle.database.ClearCachesFromSource;
import com.google.code.geobeagle.database.GpxTableWriter;
import com.google.code.geobeagle.xmlimport.GpxToCache;
import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException;
import com.google.code.geobeagle.xmlimport.GpxToCache.GpxToCacheFactory;
import com.google.inject.Inject;
import java.io.BufferedReader;
import java.util.Hashtable;
public class CacheImporter {
private static Hashtable<String, String> params;
static {
params = new Hashtable<String, String>();
params.put("a", "detail");
BCachingListImporterStateless.commonParams(params);
params.put("desc", "html");
params.put("tbs", "0");
params.put("wpts", "1");
params.put("logs", "1000");
params.put("fmt", "gpx");
}
private final BufferedReaderFactory bufferedReaderFactory;
private final GpxToCache gpxToCache;
static class GpxTableWriterBCaching implements GpxTableWriter {
@Override
public boolean isGpxAlreadyLoaded(String mGpxName, String sqlDate) {
return false;
}
}
@Inject
CacheImporter(BufferedReaderFactory bufferedReaderFactory,
GpxToCacheFactory gpxToCacheFactory,
MessageHandlerAdapter messageHandlerAdapter,
GpxTableWriterBCaching gpxTableWriterBcaching,
ClearCachesFromSource clearCachesFromSourceNull) {
this.bufferedReaderFactory = bufferedReaderFactory;
gpxToCache = gpxToCacheFactory.create(messageHandlerAdapter, gpxTableWriterBcaching,
clearCachesFromSourceNull);
}
public void load(String csvIds) throws BCachingException, CancelException {
params.put("ids", csvIds);
BufferedReader bufferedReader = bufferedReaderFactory.create(params);
gpxToCache.load("BCaching.com", bufferedReader);
}
}
| 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 com.google.inject.Inject;
public class BCachingListImporter {
private final BCachingListImporterStateless bcachingListImporterStateless;
private BCachingList bcachingList;
private String startTime;
private long serverTime;
@Inject
public BCachingListImporter(BCachingListImporterStateless bcachingListImporterStateless) {
this.bcachingListImporterStateless = bcachingListImporterStateless;
}
public void readCacheList(int startPosition) throws BCachingException {
bcachingList = bcachingListImporterStateless.getCacheList(String.valueOf(startPosition),
startTime);
serverTime = bcachingList.getServerTime();
}
public int getTotalCount() throws BCachingException {
return bcachingListImporterStateless.getTotalCount(startTime);
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
/**
* Must be called after readCacheList().
*/
public long getServerTime() {
return serverTime;
}
public String getCacheIds() throws BCachingException {
return bcachingList.getCacheIds();
}
public int getCachesRead() throws BCachingException {
return bcachingList.getCachesRead();
}
}
| 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;
public class BCachingException extends Exception {
private static final long serialVersionUID = 5483107564028776147L;
public BCachingException(String string) {
super(string);
}
} | 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 com.google.code.geobeagle.bcaching.BufferedReaderFactory;
import com.google.inject.Inject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Hashtable;
public class BCachingListImportHelper {
private final BCachingListFactory bcachingListFactory;
private final BufferedReaderFactory bufferedReaderFactory;
@Inject
BCachingListImportHelper(BufferedReaderFactory readerFactory,
BCachingListFactory bcachingListFactory) {
this.bufferedReaderFactory = readerFactory;
this.bcachingListFactory = bcachingListFactory;
}
public BCachingList importList(Hashtable<String, String> params) throws BCachingException {
BufferedReader bufferedReader = bufferedReaderFactory.create(params);
StringBuilder result = new StringBuilder();
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.d("GeoBeagle", "importList: " + line);
result.append(line);
result.append('\n');
}
return bcachingListFactory.create(result.toString());
} catch (IOException e) {
throw new BCachingException("IO Error: " + 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.communication;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import java.util.Hashtable;
public class BCachingListImporterStateless {
static final String MAX_COUNT = "50";
private final BCachingListImportHelper bCachingListImportHelper;
private final Hashtable<String, String> params;
@Inject
BCachingListImporterStateless(BCachingListImportHelper bCachingListImportHelper,
SharedPreferences sharedPreferences) {
this.bCachingListImportHelper = bCachingListImportHelper;
params = new Hashtable<String, String>();
params.put("a", "list");
boolean syncFinds = sharedPreferences.getBoolean("bcaching-sync-finds", false);
params.put("found", syncFinds ? "2" : "0"); // 0-no, 1-yes, 2-both
commonParams(params);
}
// For testing.
BCachingListImporterStateless(Hashtable<String, String> params,
BCachingListImportHelper bCachingListImportHelper) {
this.bCachingListImportHelper = bCachingListImportHelper;
this.params = params;
}
private BCachingList importList(String maxCount, String startTime) throws BCachingException {
params.put("maxcount", maxCount);
params.put("since", startTime);
// params.put("since", "1298740607924");
return bCachingListImportHelper.importList(params);
}
public BCachingList getCacheList(String startPosition, String startTime)
throws BCachingException {
params.put("first", startPosition);
return importList(MAX_COUNT, startTime);
}
public int getTotalCount(String startTime) throws BCachingException {
params.remove("first");
BCachingList importList = importList("1", startTime);
return importList.getTotalCount();
}
public static void commonParams(Hashtable<String, String> params) {
params.put("lastuploaddays", "7");
params.put("app", "GeoBeagle");
params.put("timeAsLong", "1");
params.put("own", "2");
}
}
| 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 android.util.Log;
public class BCachingList {
private final BCachingJSONObject cacheList;
BCachingList(BCachingJSONObject cacheList) {
this.cacheList = cacheList;
}
String getCacheIds() throws BCachingException {
BCachingJSONArray summary = cacheList.getJSONArray("data");
Log.d("GeoBeagle", summary.toString());
StringBuilder csvIds = new StringBuilder();
int count = summary.length();
for (int i = 0; i < count; i++) {
csvIds.append(',');
BCachingJSONObject cacheObject = summary.getJSONObject(i);
csvIds.append(String.valueOf(cacheObject.getInt("id")));
}
if (count > 0)
csvIds.deleteCharAt(0);
return csvIds.toString();
}
long getServerTime() throws BCachingException {
return cacheList.getLong("serverTime");
}
int getCachesRead() throws BCachingException {
int length = cacheList.getJSONArray("data").length();
Log.d("GeoBeagle", "getCachesRead: " + length);
return length;
}
int getTotalCount() throws BCachingException {
return cacheList.getInt("totalCount");
}
}
| 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;
public class BCachingJSONObject {
private final JSONObject jsonObject;
public BCachingJSONObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
public BCachingJSONArray getJSONArray(String key) throws BCachingException {
try {
return new BCachingJSONArray(jsonObject.getJSONArray(key));
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
public int getInt(String key) throws BCachingException {
try {
return jsonObject.getInt(key);
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
public long getLong(String key) throws BCachingException {
try {
return jsonObject.getLong(key);
} catch (JSONException e) {
throw new BCachingException(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.communication;
import com.google.code.geobeagle.activity.preferences.Preferences;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.DigestException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Communicates with the bacching.com server to fetch geocaches as a GPX
* InputStream.
*
* @author Mark Bastian
*/
public class BCachingCommunication {
private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++) {
map1[i++] = c;
}
for (char c = 'a'; c <= 'z'; c++) {
map1[i++] = c;
}
for (char c = '0'; c <= '9'; c++) {
map1[i++] = c;
}
map1[i++] = '+';
map1[i++] = '/';
}
public static String base64Encode(byte[] in) {
int iLen = in.length;
int oDataLen = (iLen * 4 + 2) / 3;// output length without padding
int oLen = ((iLen + 2) / 3) * 4;// output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
int i0, i1, i2, o0, o1, o2, o3;
while (ip < iLen) {
i0 = in[ip++] & 0xff;
i1 = ip < iLen ? in[ip++] & 0xff : 0;
i2 = ip < iLen ? in[ip++] & 0xff : 0;
o0 = i0 >>> 2;
o1 = ((i0 & 3) << 4) | (i1 >>> 4);
o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '=';
op++;
out[op] = op < oDataLen ? map1[o3] : '=';
op++;
}
return new String(out);
}
private String baseUrl;
private final String hashword;
private final int timeout = 60000; // millisec
private final String username;
public static class BCachingCredentials {
public final String password;
public final String username;
@Inject
public BCachingCredentials(SharedPreferences sharedPreferences) {
password = sharedPreferences.getString(Preferences.BCACHING_PASSWORD, "");
username = sharedPreferences.getString(Preferences.BCACHING_USERNAME, "");
}
}
@Inject
public BCachingCommunication(BCachingCredentials bcachingCredentials,
SharedPreferences sharedPreferences) {
username = bcachingCredentials.username;
String hashword = "";
try {
hashword = encodeHashword(username, bcachingCredentials.password);
} catch (Exception ex) {
Log.e("GeoBeagle", ex.toString());
}
this.hashword = hashword;
baseUrl = sharedPreferences.getString(Preferences.BCACHING_HOSTNAME,
"http://www.bcaching.com/api");
}
public String encodeHashword(String username, String password) {
return encodeMd5Base64(password + username);
}
public String encodeMd5Base64(String s) {
byte[] buf = s.getBytes();
try {
java.security.MessageDigest md;
md = java.security.MessageDigest.getInstance("MD5");
md.update(buf, 0, buf.length);
buf = new byte[16];
md.digest(buf, 0, buf.length);
} catch (DigestException e) {
// Should never happen.
Log.d("GeoBeagle", "Digest exception encoding md5");
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
// Should never happen.
Log.d("GeoBeagle", "NoSuchAlgorithmException exception encoding md5");
throw new RuntimeException(e);
}
return base64Encode(buf);
}
public InputStream sendRequest(Hashtable<String, String> params) throws BCachingException {
if (params == null || params.size() == 0)
throw new IllegalArgumentException("params are required.");
if (!params.containsKey("a"))
throw new IllegalArgumentException("params must include an action (key=a)");
StringBuffer sb = new StringBuffer();
Enumeration<String> keys = params.keys();
while (keys.hasMoreElements()) {
if (sb.length() > 0)
sb.append('&');
String k = keys.nextElement();
sb.append(k);
sb.append('=');
sb.append(URLEncoder.encode(params.get(k)));
}
return sendRequest(sb.toString());
}
private String encodeQueryString(String username, String hashword, String params) {
if (username == null)
throw new IllegalArgumentException("username is required.");
if (hashword == null)
throw new IllegalArgumentException("hashword is required.");
if (params == null || params.length() == 0)
throw new IllegalArgumentException("params are required.");
StringBuffer sb = new StringBuffer();
sb.append("u=");
sb.append(URLEncoder.encode(username));
sb.append("&");
sb.append(params);
sb.append("&time=");
java.util.Date date = java.util.Calendar.getInstance().getTime();
sb.append(date.getTime());
String signature = encodeMd5Base64(sb.toString() + hashword);
sb.append("&sig=");
sb.append(URLEncoder.encode(signature));
return sb.toString();
}
private URL getURL(String username, String hashword, String params) {
try {
return new URL(baseUrl + "/q.ashx?" + encodeQueryString(username, hashword, params));
} catch (MalformedURLException e) {
// baseUrl is a constant, it should never be malformed.
throw new RuntimeException(e);
}
}
private InputStream sendRequest(String query) throws BCachingException {
if (query == null || query.length() == 0)
throw new IllegalArgumentException("query is required");
final URL url = getURL(username, hashword, query);
Log.d("GeoBeagle", "sending url: " + url);
HttpURLConnection connection;
try {
connection = (HttpURLConnection)url.openConnection();
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
connection.addRequestProperty("Accept-encoding", "gzip");
int responseCode = connection.getResponseCode();
InputStream inputStream = null;
String contentEncoding = connection.getContentEncoding();
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
InputStream errorStream = connection.getErrorStream();
if (contentEncoding != null
&& contentEncoding.equalsIgnoreCase("gzip")) {
errorStream = new java.util.zip.GZIPInputStream(errorStream);
}
InputStreamReader errorStreamReader = new InputStreamReader(errorStream);
BufferedReader reader = new BufferedReader(errorStreamReader);
String string = connection.getResponseCode() + " error: " + reader.readLine();
throw new BCachingException(string);
}
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
inputStream = new java.util.zip.GZIPInputStream(inputStream);
}
if (responseCode != HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
throw new BCachingException("HTTP problem: " + sb.toString());
}
return inputStream;
} catch (IOException e) {
throw new BCachingException("IO error: " + e.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.bcaching.communication;
import org.json.JSONArray;
import org.json.JSONException;
public class BCachingJSONArray {
private final JSONArray jsonArray;
public BCachingJSONArray(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}
public BCachingJSONObject getJSONObject(int index) throws BCachingException {
try {
return new BCachingJSONObject(jsonArray.getJSONObject(index));
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
public int length() {
return jsonArray.length();
}
}
| 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.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.bcaching.progress.ProgressHandler;
import com.google.code.geobeagle.bcaching.progress.ProgressManager;
import com.google.code.geobeagle.bcaching.progress.ProgressMessage;
import com.google.code.geobeagle.xmlimport.MessageHandlerInterface;
import com.google.inject.Inject;
import com.google.inject.Injector;
import android.os.Message;
public class MessageHandlerAdapter implements MessageHandlerInterface {
private final ProgressManager progressManager;
private final ProgressHandler handler;
private String waypoint;
public MessageHandlerAdapter(ProgressHandler handler, ProgressManager progressManager) {
this.handler = handler;
this.progressManager = progressManager;
waypoint = "";
}
@Inject
public MessageHandlerAdapter(Injector injector) {
this.handler = injector.getInstance(ProgressHandler.class);
this.progressManager = injector.getInstance(ProgressManager.class);
waypoint = "";
}
@Override
public void abortLoad() {
}
@Override
public void deletingCacheFiles() {
}
@Override
public void handleMessage(Message msg) {
}
@Override
public void loadComplete() {
}
@Override
public void start(CacheListRefresh cacheListRefresh) {
}
@Override
public void updateName(String name) {
if (waypoint.startsWith("GC"))
progressManager.incrementProgress();
progressManager.update(handler, ProgressMessage.SET_FILE,
progressManager.getCurrentProgress(), waypoint + " - " + name);
}
@Override
public void updateSource(String text) {
}
@Override
public void updateStatus(String status) {
}
@Override
public void updateWaypointId(String wpt) {
this.waypoint = wpt;
}
}
| 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.progress;
import android.os.Message;
public enum ProgressMessage {
DONE {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.done();
}
},
REFRESH {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.refresh();
}
},
SET_FILE {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setFile((String)msg.obj, msg.arg1);
}
},
SET_MAX {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setMax(msg.arg1);
}
},
SET_PROGRESS {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setProgress(msg.arg1);
}
},
START {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setProgress(0);
progressHandler.setMax(100);
progressHandler.show();
}
};
static ProgressMessage fromInt(Integer i) {
return ProgressMessage.class.getEnumConstants()[i];
}
abstract void act(ProgressHandler progressHandler, Message msg);
}
| 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.progress;
import com.google.inject.Singleton;
import android.os.Message;
import android.util.Log;
@Singleton
public class ProgressManager {
private int currentProgress;
public void setCurrentProgress(int currentProgress) {
this.currentProgress = currentProgress;
}
public void update(ProgressHandler handler, ProgressMessage progressMessage, int arg) {
Message.obtain(handler, progressMessage.ordinal(), arg, 0).sendToTarget();
}
public void update(ProgressHandler handler,
ProgressMessage progressMessage,
int arg1,
String arg2) {
if (!handler.hasMessages(progressMessage.ordinal()))
Message.obtain(handler, progressMessage.ordinal(), arg1, 0, arg2).sendToTarget();
}
public int getCurrentProgress() {
return currentProgress;
}
public void incrementProgress() {
Log.d("GeoBeagle", "incrementing Progress: " + currentProgress);
currentProgress++;
}
}
| 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.progress;
import com.google.code.geobeagle.activity.cachelist.ActivityVisible;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.bcaching.BCachingModule;
import com.google.code.geobeagle.bcaching.BCachingProgressDialog;
import com.google.inject.Inject;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class ProgressHandler extends Handler {
private final ProgressDialog progressDialog;
private final CacheListRefresh cacheListRefresher;
private final ActivityVisible activityVisible;
@Inject
public ProgressHandler(BCachingProgressDialog progressDialog,
CacheListRefresh cacheListRefresh, ActivityVisible activityVisible) {
this.progressDialog = progressDialog;
this.cacheListRefresher = cacheListRefresh;
this.activityVisible = activityVisible;
}
public void done() {
progressDialog.setMessage(BCachingModule.BCACHING_INITIAL_MESSAGE);
progressDialog.dismiss();
}
@Override
public void handleMessage(Message msg) {
ProgressMessage progressMessage = ProgressMessage.fromInt(msg.what);
progressMessage.act(this, msg);
}
public void setFile(String filename, int progress) {
progressDialog.setMessage("Loading: " + filename);
progressDialog.setProgress(progress);
}
public void setMax(int max) {
progressDialog.setMax(max);
}
public void setProgress(int progress) {
progressDialog.setProgress(progress);
}
public void show() {
progressDialog.show();
}
public void refresh() {
Log.d("GeoBeagle", "REFRESHING");
if (activityVisible.getVisible()) {
cacheListRefresher.forceRefresh();
}
else
Log.d("GeoBeagle", "NOT VISIBLE, punting");
}
}
| 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.R;
import com.google.code.geobeagle.bcaching.communication.BCachingException;
import com.google.code.geobeagle.bcaching.communication.BCachingListImporter;
import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime;
import com.google.code.geobeagle.bcaching.preferences.LastReadPosition;
import com.google.code.geobeagle.bcaching.progress.ProgressHandler;
import com.google.code.geobeagle.bcaching.progress.ProgressManager;
import com.google.code.geobeagle.bcaching.progress.ProgressMessage;
import com.google.code.geobeagle.xmlimport.SyncCollectingParameter;
import com.google.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
class CacheListCursor {
private final BCachingStartTime bcachingStartTime;
private final BCachingListImporter bcachingListImporter;
private final LastReadPosition lastReadPosition;
private final ProgressHandler progressHandler;
private final ProgressManager progressManager;
private final SimpleDateFormat formatter;
@Inject
CacheListCursor(BCachingStartTime bcachingStartTime, ProgressManager progressManager,
ProgressHandler progressHandler, BCachingListImporter bcachingListImporter,
LastReadPosition lastReadPosition) {
this.bcachingStartTime = bcachingStartTime;
this.progressManager = progressManager;
this.progressHandler = progressHandler;
this.bcachingListImporter = bcachingListImporter;
this.lastReadPosition = lastReadPosition;
this.formatter = new SimpleDateFormat("MM-dd HH:mm");
}
void close() {
bcachingStartTime.resetStartTime();
lastReadPosition.put(0);
}
String getCacheIds() throws BCachingException {
return bcachingListImporter.getCacheIds();
}
void increment() throws BCachingException {
int position = lastReadPosition.get();
if (position == 0) {
bcachingStartTime.putNextStartTime(bcachingListImporter.getServerTime());
}
position += bcachingListImporter.getCachesRead();
lastReadPosition.put(position);
}
boolean open(SyncCollectingParameter syncCollectingParameter) throws BCachingException {
long serverTime = bcachingStartTime.getLastUpdateTime();
// bcachingListImporter.setStartTime("1274686304000");
// bcachingListImporter.setStartTime("1274686304000");
bcachingListImporter.setStartTime(String.valueOf(serverTime));
int totalCount = bcachingListImporter.getTotalCount();
syncCollectingParameter.Log(R.string.sync_message_bcaching_start);
if (serverTime == 0) {
syncCollectingParameter.Log(" initial sync");
} else {
String longModtime = formatter.format(new Date(serverTime));
syncCollectingParameter
.NestedLog(R.string.sync_message_bcaching_last_sync, longModtime);
}
if (totalCount <= 0) {
syncCollectingParameter.NestedLog(R.string.sync_message_bcaching_synced_caches, 0);
return false;
}
progressManager.update(progressHandler, ProgressMessage.SET_MAX, totalCount);
lastReadPosition.load();
int startPosition = lastReadPosition.get();
progressManager.setCurrentProgress(startPosition);
progressManager.update(progressHandler, ProgressMessage.SET_PROGRESS, startPosition);
return true;
}
int readCaches() throws BCachingException {
bcachingListImporter.readCacheList(lastReadPosition.get());
return bcachingListImporter.getCachesRead();
}
}
| 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.inject.Inject;
import roboguice.inject.ContextScoped;
import android.app.ProgressDialog;
import android.content.Context;
@ContextScoped
public class BCachingProgressDialog extends ProgressDialog {
@Inject
public BCachingProgressDialog(Context context) {
super(context);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setTitle("Sync from BCaching.com");
setMessage(BCachingModule.BCACHING_INITIAL_MESSAGE);
setCancelable(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.bcaching;
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.bcaching.communication.BCachingException;
import com.google.code.geobeagle.bcaching.progress.ProgressHandler;
import com.google.code.geobeagle.bcaching.progress.ProgressManager;
import com.google.code.geobeagle.bcaching.progress.ProgressMessage;
import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException;
import com.google.code.geobeagle.xmlimport.SyncCollectingParameter;
import com.google.inject.Inject;
import com.google.inject.Injector;
import roboguice.inject.ContextScoped;
import android.content.SharedPreferences;
import android.util.Log;
/**
* Thread class that does the work of importing caches from the bcaching.com
* site.
*
* @author sng
*/
@ContextScoped
public class ImportBCachingWorker {
private final CacheImporter cacheImporter;
private final CacheListCursor cursor;
private boolean inProgress;
private final ProgressHandler progressHandler;
private final ProgressManager progressManager;
private final UpdateFlag updateFlag;
private final SharedPreferences sharedPreferences;
@Inject
public ImportBCachingWorker(Injector injector) {
this.progressHandler = injector.getInstance(ProgressHandler.class);
this.progressManager = injector.getInstance(ProgressManager.class);
this.cacheImporter = injector.getInstance(CacheImporter.class);
this.cursor = injector.getInstance(CacheListCursor.class);
this.updateFlag = injector.getInstance(UpdateFlag.class);
this.sharedPreferences = injector.getInstance(SharedPreferences.class);
}
public ImportBCachingWorker(ProgressHandler progressHandler,
ProgressManager progressManager,
CacheImporter cacheImporter,
CacheListCursor cacheListCursor,
UpdateFlag updateFlag,
SharedPreferences sharedPreferences) {
this.progressHandler = progressHandler;
this.progressManager = progressManager;
this.cacheImporter = cacheImporter;
this.cursor = cacheListCursor;
this.updateFlag = updateFlag;
this.sharedPreferences = sharedPreferences;
}
/*
* Abort the import thread. This call will block
*/
public synchronized boolean inProgress() {
return inProgress;
}
public void sync(SyncCollectingParameter syncCollectingParameter) throws BCachingException,
CancelException {
if (!sharedPreferences.getBoolean(Preferences.BCACHING_ENABLED, false))
return;
updateFlag.setUpdatesEnabled(false);
Log.d("GeoBeagle", "Starting import");
inProgress = true;
progressManager.update(progressHandler, ProgressMessage.START, 0);
try {
if (!cursor.open(syncCollectingParameter))
return;
int cachesRead;
int totalCachesRead = 0;
while ((cachesRead = cursor.readCaches()) > 0) {
cacheImporter.load(cursor.getCacheIds());
cursor.increment();
totalCachesRead += cachesRead;
Log.d("GeoBeagle", "totalCachesRead: " + totalCachesRead);
}
syncCollectingParameter.NestedLog(R.string.sync_message_bcaching_synced_caches,
totalCachesRead);
cursor.close();
} finally {
updateFlag.setUpdatesEnabled(true);
progressManager.update(progressHandler, ProgressMessage.REFRESH, 0);
progressManager.update(progressHandler, ProgressMessage.DONE, 0);
inProgress = 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.bcaching.preferences;
import com.google.inject.Inject;
import android.content.SharedPreferences;
public class BCachingStartTime {
static final String BCACHING_NEXT_START = "bcaching-next-start";
static final String BCACHING_START = "bcaching-start";
private final LastReadPosition lastReadPosition;
private final SharedPreferences sharedPreferences;
private final PreferencesWriter preferencesWriter;
@Inject
BCachingStartTime(SharedPreferences sharedPreferences,
PreferencesWriter preferencesWriter, LastReadPosition lastReadPosition) {
this.sharedPreferences = sharedPreferences;
this.preferencesWriter = preferencesWriter;
this.lastReadPosition = lastReadPosition;
}
public void clearStartTime() {
preferencesWriter.putLong(BCACHING_START, 0);
lastReadPosition.put(0);
}
public long getLastUpdateTime() {
return sharedPreferences.getLong(BCACHING_START, 0);
}
public void putNextStartTime(long serverTime) {
preferencesWriter.putLong(BCACHING_NEXT_START, serverTime);
}
public void resetStartTime() {
preferencesWriter
.putLong(BCACHING_START, sharedPreferences.getLong(BCACHING_NEXT_START, 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.bcaching.preferences;
import com.google.inject.Inject;
import android.content.SharedPreferences;
class PreferencesWriter {
private final SharedPreferences sharedPreferences;
@Inject
PreferencesWriter(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
void putInt(String pref, int i) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(pref, i);
editor.commit();
}
void putLong(String pref, long l) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong(pref, l);
editor.commit();
}
}
| 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.preferences;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import android.util.Log;
public class LastReadPosition {
static final String BCACHING_LAST_READ_POSITION = "bcaching-last-read-position";
private int lastRead;
private final PreferencesWriter preferencesWriter;
private final SharedPreferences sharedPreferences;
@Inject
LastReadPosition(SharedPreferences sharedPreferences,
PreferencesWriter preferencesWriter) {
this.preferencesWriter = preferencesWriter;
this.sharedPreferences = sharedPreferences;
}
public int get() {
return lastRead;
}
public void load() {
lastRead = sharedPreferences.getInt(BCACHING_LAST_READ_POSITION, 0);
Log.d("GeoBeagle", "Load last read: " + lastRead);
}
public void put(int lastRead) {
Log.d("GeoBeagle", "Put last read: " + lastRead);
preferencesWriter.putInt(BCACHING_LAST_READ_POSITION, lastRead);
this.lastRead = lastRead;
}
}
| 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.shakewaker;
import com.google.inject.Inject;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Handler;
import android.util.Log;
class ShakeListener implements SensorEventListener {
private final ForceThresholdStrategy forceThresholdStrategy;
private final Handler handler;
private int shakeWakeDuration;
private final WakeLockReleaser wakeLockReleaser;
private final WakeLockView wakeLockView;
@Inject
ShakeListener(ForceThresholdStrategy forceThresholdStrategy,
Handler handler,
WakeLockReleaser wakeLockReleaser,
WakeLockView wakeLockView) {
this.forceThresholdStrategy = forceThresholdStrategy;
this.handler = handler;
this.wakeLockReleaser = wakeLockReleaser;
this.wakeLockView = wakeLockView;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (forceThresholdStrategy.exceedsThreshold(event.values)) {
renewWakeLock();
Log.d("GeoBeagle", "shaked; wakelocking: " + event.values[0] + ", " + event.values[1]
+ ", " + event.values[2]);
}
}
private void renewWakeLock() {
Log.d("GeoBeagle", "Acquiring wakelock");
wakeLockView.keepScreenOn(true);
handler.removeCallbacks(wakeLockReleaser);
handler.postDelayed(wakeLockReleaser, shakeWakeDuration * 1000);
}
void acquireWakeLock(int shakeWakeDuration) {
this.shakeWakeDuration = shakeWakeDuration;
renewWakeLock();
}
void removeAllWakeLocks() {
wakeLockView.keepScreenOn(false);
handler.removeCallbacks(wakeLockReleaser);
}
}
| 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.shakewaker;
import com.google.inject.Inject;
class WakeLockReleaser implements Runnable {
private final WakeLockView wakeLockView;
@Inject
WakeLockReleaser(WakeLockView wakeLockView) {
this.wakeLockView = wakeLockView;
}
@Override
public void run() {
wakeLockView.keepScreenOn(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.shakewaker;
import com.google.inject.Inject;
import android.app.Activity;
import android.view.View;
class WakeLockView {
private final View view;
@Inject
WakeLockView(Activity activity) {
this.view = activity.getWindow().getDecorView();
}
void keepScreenOn(boolean b) {
// Don't use a real WakeLock, because of
// http://code.google.com/p/android/issues/detail?id=11622.
view.setKeepScreenOn(b);
}
}
| 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.shakewaker;
import android.hardware.SensorManager;
class ForceThresholdStrategy {
public boolean exceedsThreshold(float[] values) {
double totalForce = 0.0f;
totalForce += Math.pow(values[SensorManager.DATA_X] / SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(values[SensorManager.DATA_Y] / SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(values[SensorManager.DATA_Z] / SensorManager.GRAVITY_EARTH, 2.0);
totalForce = Math.sqrt(totalForce);
double abs = Math.abs(1.0 - totalForce);
return abs > 0.1;
}
}
| 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.shakewaker;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import java.util.List;
public class ShakeWaker {
static final String SHAKE_WAKE = "shake-wake-duration";
private final SharedPreferences sharedPreferences;
private final SensorManager sensorManager;
private final ShakeListener shakeListener;
@Inject
ShakeWaker(SharedPreferences sharedPreferences,
SensorManager sensorManager,
ShakeListener shakeListener) {
this.sharedPreferences = sharedPreferences;
this.sensorManager = sensorManager;
this.shakeListener = shakeListener;
}
public void register() {
String sShakeWakeDuration = sharedPreferences.getString(SHAKE_WAKE, "0");
int nShakeWakeDuration = Integer.parseInt(sShakeWakeDuration);
if (nShakeWakeDuration == 0) {
shakeListener.removeAllWakeLocks();
return;
}
shakeListener.acquireWakeLock(nShakeWakeDuration);
List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensorList.size() <= 0)
return;
sensorManager.registerListener(shakeListener, sensorList.get(0),
SensorManager.SENSOR_DELAY_UI);
}
public void unregister() {
sensorManager.unregisterListener(shakeListener);
shakeListener.removeAllWakeLocks();
}
}
| 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.cachelist.CacheListModule;
import com.google.code.geobeagle.activity.cachelist.model.ModelModule;
import com.google.code.geobeagle.activity.compass.CompassActivityModule;
import com.google.code.geobeagle.activity.map.click.MapModule;
import com.google.code.geobeagle.bcaching.BCachingModule;
import com.google.code.geobeagle.database.DatabaseModule;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetModule;
import com.google.code.geobeagle.location.LocationModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import roboguice.application.GuiceApplication;
import roboguice.config.AbstractAndroidModule;
import java.util.ArrayList;
import java.util.List;
public class GeoBeagleApplication extends GuiceApplication {
public static Timing timing = new Timing();
@Override
protected Injector createInjector() {
ArrayList<Module> modules = new ArrayList<Module>();
Module roboguiceModule = new FasterRoboGuiceModule(contextScope, throwingContextProvider,
contextProvider, resourceListener, viewListener, extrasListener, this);
modules.add(roboguiceModule);
addApplicationModules(modules);
for (Module m : modules) {
if (m instanceof AbstractAndroidModule) {
((AbstractAndroidModule)m).setStaticTypeListeners(staticTypeListeners);
}
}
return Guice.createInjector(Stage.DEVELOPMENT, modules);
}
@Override
protected void addApplicationModules(List<Module> modules) {
timing.start();
// Debug.startMethodTracing("dmtrace", 32 * 1024 * 1024);
modules.add(new CompassActivityModule()); // +1 second (11.0)
modules.add(new GeoBeaglePackageModule());
modules.add(new DatabaseModule());
modules.add(new CacheListModule());
modules.add(new LocationModule());
modules.add(new ModelModule());
modules.add(new GpsStatusWidgetModule());
modules.add(new BCachingModule());
modules.add(new MapModule());
}
}
| 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.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.ActivityVisible;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.inject.Inject;
import com.google.inject.Injector;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
/*
* Listener for the Location control.
*/
public class CombinedLocationListener implements LocationListener {
private final LocationControlBuffered mLocationControlBuffered;
private final LocationListener mLocationListener;
private final ActivityVisible mActivityVisible;
public CombinedLocationListener(LocationControlBuffered locationControlBuffered,
GpsStatusWidgetDelegate locationListener, ActivityVisible activityVisible) {
mLocationListener = locationListener;
mLocationControlBuffered = locationControlBuffered;
mActivityVisible = activityVisible;
}
@Inject
public CombinedLocationListener(Injector injector) {
mLocationListener = injector.getInstance(GpsStatusWidgetDelegate.class);
mLocationControlBuffered = injector.getInstance(LocationControlBuffered.class);
mActivityVisible = injector.getInstance(ActivityVisible.class);
}
@Override
public void onLocationChanged(Location location) {
if (!mActivityVisible.getVisible())
return;
// Ask the location control to pick the most accurate location (might
// not be this one).
// Log.d("GeoBeagle", "onLocationChanged:" + location);
final Location chosenLocation = mLocationControlBuffered.getLocation();
// Log.d("GeoBeagle", "onLocationChanged chosen Location" +
// chosenLocation);
mLocationListener.onLocationChanged(chosenLocation);
}
@Override
public void onProviderDisabled(String provider) {
if (!mActivityVisible.getVisible())
return;
mLocationListener.onProviderDisabled(provider);
}
@Override
public void onProviderEnabled(String provider) {
if (!mActivityVisible.getVisible())
return;
mLocationListener.onProviderEnabled(provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (!mActivityVisible.getVisible())
return;
mLocationListener.onStatusChanged(provider, status, extras);
}
}
| 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 android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import java.util.ArrayList;
public class CombinedLocationManager {
private final ArrayList<LocationListener> mLocationListeners;
private GpsStatus.Listener mGpsStatusListener;
private final LocationManager mLocationManager;
public CombinedLocationManager(LocationManager locationManager,
ArrayList<LocationListener> locationListeners) {
mLocationManager = locationManager;
mLocationListeners = locationListeners;
}
public boolean isProviderEnabled() {
return mLocationManager.isProviderEnabled("gps")
|| mLocationManager.isProviderEnabled("network");
}
public void removeUpdates() {
for (LocationListener locationListener : mLocationListeners) {
mLocationManager.removeUpdates(locationListener);
}
mLocationListeners.clear();
if (mGpsStatusListener != null) {
mLocationManager.removeGpsStatusListener(mGpsStatusListener);
mGpsStatusListener = null;
}
}
public void requestLocationUpdates(int minTime,
int minDistance,
LocationListener locationListener) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime,
minDistance, locationListener);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance,
locationListener);
mLocationListeners.add(locationListener);
}
public void addGpsStatusListener(GpsStatus.Listener gpsStatusListener) {
mLocationManager.addGpsStatusListener(gpsStatusListener);
mGpsStatusListener = gpsStatusListener;
}
public Location getLastKnownLocation() {
Location gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null)
return gpsLocation;
return mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
| 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.Inject;
import android.location.Location;
import android.location.LocationManager;
public class LocationControl {
public static class LocationChooser {
/**
* Choose the better of two locations: If one location is newer and more
* accurate, choose that. (This favors the gps). Otherwise, if one
* location is newer, less accurate, but farther away than the sum of
* the two accuracies, choose that. (This favors the network locator if
* you've driven a distance and haven't been able to get a gps fix yet.)
*/
public Location choose(Location location1, Location location2) {
if (location1 == null)
return location2;
if (location2 == null)
return location1;
if (location2.getTime() > location1.getTime()) {
if (location2.getAccuracy() <= location1.getAccuracy())
return location2;
else if (location1.distanceTo(location2) >= location1.getAccuracy()
+ location2.getAccuracy()) {
return location2;
}
}
return location1;
}
}
private final LocationChooser mLocationChooser;
private final LocationManager mLocationManager;
@Inject
public LocationControl(LocationManager locationManager, LocationChooser locationChooser) {
mLocationManager = locationManager;
mLocationChooser = locationChooser;
}
/*
* (non-Javadoc)
* @see
* com.android.geobrowse.GpsControlI#getLocation(android.content.Context)
*/
public Location getLocation() {
final Location choose = mLocationChooser.choose(mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER), mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
// choose.setLatitude(choose.getLatitude() + .1 * Math.random());
return choose;
}
}
| 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.code.geobeagle.activity.compass.LifecycleManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.LocationListener;
import android.location.LocationManager;
/*
* Handle onPause and onResume for the LocationManager.
*/
public class LocationLifecycleManager implements LifecycleManager {
private final LocationListener mLocationListener;
private final LocationManager mLocationManager;
public LocationLifecycleManager(LocationListener locationListener,
LocationManager locationManager) {
mLocationListener = locationListener;
mLocationManager = locationManager;
}
@Override
public void onPause(Editor editor) {
mLocationManager.removeUpdates(mLocationListener);
}
@Override
public void onResume(SharedPreferences preferences) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mLocationListener);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListener);
}
}
| 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.code.geobeagle.Time;
import com.google.inject.Inject;
import android.graphics.Color;
import android.view.View;
import android.widget.TextView;
class MeterFader {
private long mLastUpdateTime;
private final View mParent;
private final Time mTime;
private final TextView mBarsAndAzimuth;
@Inject
MeterFader(InflatedGpsStatusWidget parent, Time time) {
mLastUpdateTime = -1;
mBarsAndAzimuth = (TextView)parent.findViewById(R.id.location_viewer);
mParent = parent;
mTime = time;
}
void paint() {
long currentTime = mTime.getCurrentTime();
if (mLastUpdateTime == -1)
mLastUpdateTime = currentTime;
long lastUpdateLag = currentTime - mLastUpdateTime;
setLag(lastUpdateLag);
if (lastUpdateLag < 1000)
mParent.postInvalidateDelayed(100);
// Log.d("GeoBeagle", "painting " + lastUpdateLag);
}
void setLag(long lag) {
mBarsAndAzimuth.setTextColor(Color.argb(lagToAlpha(lag), 147, 190, 38));
}
int lagToAlpha(long milliseconds) {
return Math.max(128, 255 - (int)(milliseconds >> 3));
}
void reset() {
mLastUpdateTime = -1;
mParent.postInvalidate();
}
}
| 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.code.geobeagle.Time;
import com.google.code.geobeagle.location.CombinedLocationManager;
import com.google.inject.Inject;
import roboguice.inject.ContextScoped;
import android.location.Location;
import android.widget.TextView;
import java.util.Formatter;
@ContextScoped
class TextLagUpdater {
static interface Lag {
String getFormatted(long currentTime);
}
static class LagImpl implements Lag {
private final long mLastTextLagUpdateTime;
LagImpl(long lastTextLagUpdateTime) {
mLastTextLagUpdateTime = lastTextLagUpdateTime;
}
@Override
public String getFormatted(long currentTime) {
return formatTime((currentTime - mLastTextLagUpdateTime) / 1000);
}
}
static class LagNull implements Lag {
@Override
public String getFormatted(long currentTime) {
return "";
}
}
static class LastKnownLocation implements LastLocation {
private final LagImpl mLagImpl;
public LastKnownLocation(long time) {
mLagImpl = new LagImpl(time);
}
@Override
public Lag getLag() {
return mLagImpl;
}
}
static class LastKnownLocationUnavailable implements LastLocation {
private final Lag mLagNull;
@Inject
public LastKnownLocationUnavailable(LagNull lagNull) {
mLagNull = lagNull;
}
@Override
public Lag getLag() {
return mLagNull;
}
}
static interface LastLocation {
Lag getLag();
}
static class LastLocationUnknown implements LastLocation {
private final CombinedLocationManager mCombinedLocationManager;
private final LastKnownLocationUnavailable mLastKnownLocationUnavailable;
@Inject
public LastLocationUnknown(CombinedLocationManager combinedLocationManager,
LastKnownLocationUnavailable lastKnownLocationUnavailable) {
mCombinedLocationManager = combinedLocationManager;
mLastKnownLocationUnavailable = lastKnownLocationUnavailable;
}
@Override
public Lag getLag() {
return getLastLocation(mCombinedLocationManager.getLastKnownLocation()).getLag();
}
private LastLocation getLastLocation(Location lastKnownLocation) {
if (lastKnownLocation == null)
return mLastKnownLocationUnavailable;
return new LastKnownLocation(lastKnownLocation.getTime());
}
}
private final static StringBuilder aStringBuilder = new StringBuilder();
private final static Formatter mFormatter = new Formatter(aStringBuilder);
static String formatTime(long l) {
aStringBuilder.setLength(0);
if (l < 60) {
return mFormatter.format("%ds", l).toString();
} else if (l < 3600) {
return mFormatter.format("%dm %ds", l / 60, l % 60).toString();
}
return mFormatter.format("%dh %dm", l / 3600, (l % 3600) / 60).toString();
}
private LastLocation mLastLocation;
private final TextView mTextLag;
private final Time mTime;
@Inject
TextLagUpdater(LastLocationUnknown lastLocationUnknown,
InflatedGpsStatusWidget inflatedGpsStatusWidget, Time time) {
mLastLocation = lastLocationUnknown;
mTextLag = (TextView)inflatedGpsStatusWidget.findViewById(R.id.lag);
mTime = time;
}
void reset(long time) {
mLastLocation = new LastKnownLocation(time);
}
void setDisabled() {
mTextLag.setText("");
}
void updateTextLag() {
mTextLag.setText(mLastLocation.getLag().getFormatted(mTime.getCurrentTime()));
}
}
| 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.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.ActivityVisible;
import com.google.inject.Inject;
import com.google.inject.Provider;
import android.os.Handler;
public class UpdateGpsWidgetRunnable implements Runnable {
private final Handler mHandler;
private final Provider<LocationControlBuffered> mLocationControlBufferedProvider;
private final Meter mMeterWrapper;
private final TextLagUpdater mTextLagUpdater;
private final ActivityVisible mActivityVisible;
@Inject
UpdateGpsWidgetRunnable(Handler handler,
Provider<LocationControlBuffered> locationControlBufferedProvider,
Meter meter, TextLagUpdater textLagUpdater, ActivityVisible activityVisible) {
mLocationControlBufferedProvider = locationControlBufferedProvider;
mMeterWrapper = meter;
mTextLagUpdater = textLagUpdater;
mHandler = handler;
mActivityVisible = activityVisible;
}
@Override
public void run() {
if (!mActivityVisible.getVisible())
return;
// Update the lag time and the orientation.
mTextLagUpdater.updateTextLag();
LocationControlBuffered locationControlBuffered = mLocationControlBufferedProvider.get();
mMeterWrapper.setAzimuth(locationControlBuffered.getAzimuth());
mHandler.postDelayed(this, 500);
}
}
| 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.inject.Inject;
import android.content.Context;
import android.widget.LinearLayout;
/**
* @author sng Displays the GPS status (mAccuracy, availability, etc).
*/
public class GpsStatusWidget extends LinearLayout {
@Inject
public GpsStatusWidget(Context context) {
super(context);
}
}
| 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;
/*
* Displays the accuracy (graphically) and azimuth of the gps.
*/
import com.google.code.geobeagle.R;
import com.google.inject.Inject;
import android.graphics.Color;
import android.widget.TextView;
class MeterBars {
private final TextView mBarsAndAzimuth;
private final MeterFormatter mMeterFormatter;
@Inject
MeterBars(InflatedGpsStatusWidget inflatedGpsStatusWidget, MeterFormatter meterFormatter) {
mBarsAndAzimuth = (TextView)inflatedGpsStatusWidget.findViewById(R.id.location_viewer);
mMeterFormatter = meterFormatter;
}
void set(float accuracy, float azimuth) {
final String center = String.valueOf((int)azimuth);
final int barCount = mMeterFormatter.accuracyToBarCount(accuracy);
final String barsToMeterText = mMeterFormatter.barsToMeterText(barCount, center);
mBarsAndAzimuth.setText(barsToMeterText);
}
void setLag(long lag) {
mBarsAndAzimuth.setTextColor(Color.argb(mMeterFormatter.lagToAlpha(lag), 147, 190, 38));
}
}
| 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.inject.Singleton;
@Singleton
class MeterState {
private float accuracy;
private float azimuth;
public void setAccuracy(float accuracy) {
this.accuracy = accuracy;
}
public float getAzimuth() {
return azimuth;
}
public void setAzimuth(float azimuth) {
this.azimuth = azimuth;
}
public float getAccuracy() {
return accuracy;
}
}
| 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.Inject;
import android.content.Context;
class MeterFormatter {
private static String mMeterLeft;
private static String mMeterRight;
private static String mDegreesSymbol;
private static StringBuilder mStringBuilder;
@Inject
MeterFormatter(Context context) {
mMeterLeft = context.getString(R.string.meter_left);
mMeterRight = context.getString(R.string.meter_right);
mDegreesSymbol = context.getString(R.string.degrees_symbol);
mStringBuilder = new StringBuilder();
}
int accuracyToBarCount(float accuracy) {
return Math.min(mMeterLeft.length(), (int)(Math.log(Math.max(1, accuracy)) / Math.log(2)));
}
String barsToMeterText(int bars, String center) {
mStringBuilder.setLength(0);
mStringBuilder.append('[').append(mMeterLeft.substring(mMeterLeft.length() - bars)).append(
center + mDegreesSymbol).append(mMeterRight.substring(0, bars)).append(']');
return mStringBuilder.toString();
}
int lagToAlpha(long milliseconds) {
return Math.max(128, 255 - (int)(milliseconds >> 3));
}
}
| 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.code.geobeagle.formatting.DistanceFormatter;
import com.google.inject.Inject;
import android.widget.TextView;
class Meter {
private final TextView mAccuracyView;
private final MeterBars mMeterView;
private final MeterState mMeterState;
@Inject
Meter(MeterBars meterBars,
InflatedGpsStatusWidget inflatedGpsStatusWidget,
MeterState meterState) {
mAccuracyView = ((TextView)inflatedGpsStatusWidget.findViewById(R.id.accuracy));
mMeterState = meterState;
mMeterView = meterBars;
}
void setAccuracy(float accuracy, DistanceFormatter distanceFormatter) {
mMeterState.setAccuracy(accuracy);
distanceFormatter.formatDistance(accuracy);
mAccuracyView.setText(distanceFormatter.formatDistance(accuracy));
mMeterView.set(accuracy, mMeterState.getAzimuth());
}
void setAzimuth(float azimuth) {
mMeterState.setAzimuth(azimuth);
mMeterView.set(mMeterState.getAccuracy(), azimuth);
}
void setDisabled() {
mAccuracyView.setText("");
mMeterView.set(Float.MAX_VALUE, 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.gpsstatuswidget;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.location.CombinedLocationManager;
import com.google.inject.Inject;
import com.google.inject.Provider;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;
public class GpsStatusWidgetDelegate implements LocationListener {
private final CombinedLocationManager mCombinedLocationManager;
private final Provider<DistanceFormatter> mDistanceFormatterProvider;
private final MeterFader mMeterFader;
private final Meter mMeterWrapper;
private final TextView mProvider;
private final Context mContext;
private final TextView mStatus;
private final TextLagUpdater mTextLagUpdater;
@Inject
public GpsStatusWidgetDelegate(CombinedLocationManager combinedLocationManager,
Provider<DistanceFormatter> distanceFormatterProvider,
Meter meter,
MeterFader meterFader,
Context context,
TextLagUpdater textLagUpdater,
InflatedGpsStatusWidget inflatedGpsStatusWidget) {
mCombinedLocationManager = combinedLocationManager;
mDistanceFormatterProvider = distanceFormatterProvider;
mMeterFader = meterFader;
mMeterWrapper = meter;
mProvider = (TextView)inflatedGpsStatusWidget.findViewById(R.id.provider);
mContext = context;
mStatus = (TextView)inflatedGpsStatusWidget.findViewById(R.id.status);
mTextLagUpdater = textLagUpdater;
}
@Override
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "GpsStatusWidget onLocationChanged " + location);
if (location == null)
return;
if (!mCombinedLocationManager.isProviderEnabled()) {
mMeterWrapper.setDisabled();
mTextLagUpdater.setDisabled();
return;
}
mMeterWrapper.setAccuracy(location.getAccuracy(), mDistanceFormatterProvider.get());
mMeterFader.reset();
mTextLagUpdater.reset(location.getTime());
}
@Override
public void onProviderDisabled(String provider) {
mStatus.setText(provider + " DISABLED");
}
@Override
public void onProviderEnabled(String provider) {
mStatus.setText(provider + " ENABLED");
}
public void setProvider(String provider) {
mProvider.setText(provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
mStatus.setText(provider + " status: "
+ mContext.getString(R.string.out_of_service));
break;
case LocationProvider.AVAILABLE:
mStatus.setText(provider + " status: " + mContext.getString(R.string.available));
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mStatus.setText(provider + " status: "
+ mContext.getString(R.string.temporarily_unavailable));
break;
}
}
public void paint() {
mMeterFader.paint();
}
}
| 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 android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
public class InflatedGpsStatusWidget extends LinearLayout {
private GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
public InflatedGpsStatusWidget(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
public InflatedGpsStatusWidget(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
mGpsStatusWidgetDelegate.paint();
}
public void setDelegate(GpsStatusWidgetDelegate gpsStatusWidgetDelegate) {
mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate;
}
public GpsStatusWidgetDelegate getDelegate() {
return mGpsStatusWidgetDelegate;
}
}
| 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.cachelist.model.GeocacheVector;
public class GpsEnabledLocation implements IGpsLocation {
private final float mLatitude;
private final float mLongitude;
public GpsEnabledLocation(float latitude, float longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
@Override
public float distanceTo(IGpsLocation gpsLocation) {
return gpsLocation.distanceToGpsEnabledLocation(this);
}
@Override
public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) {
final float calculateDistanceFast = GeocacheVector.calculateDistanceFast(mLatitude,
mLongitude, gpsEnabledLocation.mLatitude, gpsEnabledLocation.mLongitude);
return calculateDistanceFast;
}
}
| 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.actions;
import com.google.code.geobeagle.activity.preferences.EditPreferences;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.Intent;
public class MenuActionSettings implements Action {
private final Activity mActivity;
@Inject
public MenuActionSettings(Activity activity) {
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, EditPreferences.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.actions;
import com.google.code.geobeagle.activity.searchonline.SearchOnlineActivity;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.Intent;
public class MenuActionSearchOnline implements Action {
private final Activity mActivity;
@Inject
public MenuActionSearchOnline(Activity activity) {
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, SearchOnlineActivity.class));
}
}
| Java |
package com.google.code.geobeagle.actions;
public interface Action {
public void act();
}
| 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.actions;
public interface MenuAction {
/** Must be the id of a resource string - used to set label */
public int getId();
public Action getAction();
}
| 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.actions;
public class MenuActionBase implements MenuAction {
private final int id;
private final Action action;
public MenuActionBase(int id, Action action) {
this.id = id;
this.action = action;
}
@Override
public Action getAction() {
return action;
}
@Override
public int getId() {
return id;
}
}
| 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.actions;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import java.util.ArrayList;
public class MenuActions {
private ArrayList<MenuAction> mMenuActions = new ArrayList<MenuAction>();
private final Resources mResources;
public MenuActions(Resources resources) {
mResources = resources;
}
public MenuActions(Resources resources, MenuAction[] menuActions) {
mResources = resources;
for (int ix = 0; ix < menuActions.length; ix++) {
add(menuActions[ix]);
}
}
public boolean act(int itemId) {
for (MenuAction action : mMenuActions) {
if (action.getId() == itemId) {
action.getAction().act();
return true;
}
}
return false;
}
public void add(MenuAction action) {
mMenuActions.add(action);
}
/** Creates an Options Menu from the items in this MenuActions */
public boolean onCreateOptionsMenu(Menu menu) {
if (mMenuActions.isEmpty()) {
Log.w("GeoBeagle", "MenuActions.onCreateOptionsMenu: menu is empty, will not be shown");
return false;
}
menu.clear();
int ix = 0;
for (MenuAction action : mMenuActions) {
final int id = action.getId();
menu.add(0, id, ix, mResources.getString(id));
ix++;
}
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.actions;
import com.google.code.geobeagle.CacheListActivityStarter;
import com.google.inject.Inject;
public class MenuActionCacheList implements Action {
private CacheListActivityStarter cacheListActivityStarter;
@Inject
public MenuActionCacheList(CacheListActivityStarter cacheListActivityStarter) {
this.cacheListActivityStarter = cacheListActivityStarter;
}
@Override
public void act() {
cacheListActivityStarter.start();
}
}
| Java |
package com.google.code.geobeagle.actions;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.map.GeoMapActivity;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
/** Show the map, centered around the current location */
public class MenuActionMap implements Action {
private final LocationControlBuffered mLocationControl;
private final Activity mActivity;
@Inject
public MenuActionMap(Activity activity, LocationControlBuffered locationControl) {
mActivity = activity;
mLocationControl = locationControl;
}
@Override
public void act() {
Location location = mLocationControl.getLocation();
final Intent intent =
new Intent(mActivity, GeoMapActivity.class);
if (location != null) {
intent.putExtra("latitude", (float)location.getLatitude());
intent.putExtra("longitude", (float)location.getLongitude());
}
mActivity.startActivity(intent);
}
}
| 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.actions;
import com.google.code.geobeagle.activity.EditCacheActivity;
import com.google.code.geobeagle.activity.compass.CompassActivity;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.Intent;
public class MenuActionEditGeocache implements Action {
private final CompassActivity parent;
@Inject
public MenuActionEditGeocache(Activity parent) {
this.parent = (CompassActivity)parent;
}
@Override
public void act() {
Intent intent = new Intent(parent, EditCacheActivity.class);
intent.putExtra("geocache", parent.getGeocache());
parent.startActivityForResult(intent, 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.actions;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextAction;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionEdit;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionView;
import com.google.inject.Inject;
import com.google.inject.Injector;
import android.os.Build;
import java.util.ArrayList;
public class ContextActions {
private final ArrayList<ContextAction> contextActions = new ArrayList<ContextAction>();
@Inject
public ContextActions(Injector injector) {
contextActions.add(injector.getInstance(ContextActionEdit.class));
contextActions.add(injector.getInstance(ContextActionDelete.class));
if (Integer.parseInt(Build.VERSION.SDK) <= Build.VERSION_CODES.HONEYCOMB) {
contextActions.add(injector.getInstance(ContextActionView.class));
}
}
public void act(int menuIndex, int position) {
contextActions.get(menuIndex).act(position);
}
}
| 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.code.geobeagle.database.DatabaseDI.CacheReaderCursorFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import android.database.Cursor;
public class CacheReader {
public static final String[] READER_COLUMNS = new String[] {
"Latitude", "Longitude", "Id", "Description", "Source", "CacheType", "Difficulty",
"Terrain", "Container", "Available", "Archived"
};
public static final String SQL_QUERY_LIMIT = "1000";
private final CacheReaderCursorFactory mCacheReaderCursorFactory;
private final Provider<ISQLiteDatabase> mSqliteWrapperProvider;
@Inject
CacheReader(Provider<ISQLiteDatabase> sqliteWrapperProvider,
CacheReaderCursorFactory cacheReaderCursorFactory) {
mSqliteWrapperProvider = sqliteWrapperProvider;
mCacheReaderCursorFactory = cacheReaderCursorFactory;
}
public int getTotalCount() {
Cursor cursor = mSqliteWrapperProvider.get()
.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}
public CacheReaderCursor open(double latitude, double longitude, WhereFactory whereFactory,
String limit) {
ISQLiteDatabase sqliteWrapper = mSqliteWrapperProvider.get();
String where = whereFactory.getWhere(sqliteWrapper, latitude, longitude);
Cursor cursor = sqliteWrapper.query(Database.TBL_CACHES, CacheReader.READER_COLUMNS,
where, null, null, null, limit);
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return mCacheReaderCursorFactory.create(cursor);
}
public CacheReaderCursor open(CharSequence cacheId) {
Cursor cursor = mSqliteWrapperProvider.get().query(Database.TBL_CACHES, CacheReader.READER_COLUMNS,
"Id='" + cacheId + "'", null, null, null, null);
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return mCacheReaderCursorFactory.create(cursor);
}
}
| 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.code.geobeagle.R;
import com.google.code.geobeagle.database.filter.Filter;
import com.google.inject.Inject;
import com.google.inject.Injector;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class TagWriter {
private final Filter filter;
private final TagStore tagStore;
private final Context context;
public TagWriter(Filter filter, TagStore tagStore, Context context) {
this.filter = filter;
this.context = context;
this.tagStore = tagStore;
}
@Inject
public TagWriter(Injector injector) {
this.filter = injector.getInstance(Filter.class);
this.tagStore = injector.getInstance(TagStore.class);
this.context = injector.getInstance(Context.class);
}
public void add(CharSequence geocacheId, Tag tag, boolean interactive) {
Log.d("GeoBeagle", "TagWriter: " + geocacheId + ", " + tag);
tagStore.addTag(geocacheId, tag);
if (interactive
&& (!filter.showBasedOnFoundState(tag == Tag.FOUND) || !filter
.showBasedOnDnfState(geocacheId))) {
Toast.makeText(context, R.string.removing_found_cache_from_cache_list,
Toast.LENGTH_LONG).show();
tagStore.hideCache(geocacheId);
}
}
}
| 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.util.Log;
public class OpenHelperDelegate {
public void onCreate(ISQLiteDatabase db) {
db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V16);
db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10);
db.execSQL(Database.SQL_CREATE_TAGS_TABLE_V12);
db.execSQL(Database.SQL_CREATE_IDX_LATITUDE);
db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE);
db.execSQL(Database.SQL_CREATE_IDX_SOURCE);
db.execSQL(Database.SQL_CREATE_IDX_TAGS);
db.execSQL(Database.SQL_CREATE_IDX_VISIBLE);
db.execSQL(Database.SQL_CREATE_IDX_DESCRIPTION);
}
public void onUpgrade(ISQLiteDatabase db, int oldVersion) {
Log.d("GeoBeagle", "UPGRADING: " + oldVersion + " --> " + Database.DATABASE_VERSION);
if (oldVersion < 10) {
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DELETE_ME);
db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10);
}
if (oldVersion < 11) {
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CACHE_TYPE);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CONTAINER);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DIFFICULTY);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_TERRAIN);
// This date has to precede 2000-01-01 (due to a bug in
// CacheTagSqlWriter.java in v10).
db.execSQL("UPDATE GPX SET ExportTime = \"1990-01-01\"");
}
if (oldVersion < 12) {
db.execSQL(Database.SQL_CREATE_TAGS_TABLE_V12);
db.execSQL(Database.SQL_CREATE_IDX_TAGS);
}
if (oldVersion < 13) {
db.execSQL(Database.SQL_FORCE_UPDATE_ALL);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_AVAILABLE);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_ARCHIVED);
}
if (oldVersion < 14) {
// to get new gpx details.
db.execSQL(Database.SQL_FORCE_UPDATE_ALL);
}
if (oldVersion < 16) {
db.execSQL("ALTER TABLE CACHES ADD COLUMN Visible BOOLEAN NOT NULL Default 1");
db.execSQL(Database.SQL_CREATE_IDX_VISIBLE);
}
if (oldVersion < 17) {
db.execSQL(Database.SQL_CREATE_IDX_VISIBLE);
}
if (oldVersion < 18) {
db.execSQL(Database.SQL_CREATE_IDX_DESCRIPTION);
}
}
}
| Java |
/*
** Licensed under the Apache License, Versimport com.google.inject.Inject;
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.Inject;
public class TagReader {
private final TagStore tagStore;
@Inject
TagReader(TagStore tagStore) {
this.tagStore = tagStore;
}
public boolean hasTag(CharSequence geocacheId, Tag tag) {
return tagStore.hasTag(geocacheId, tag);
}
}
| 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.code.geobeagle.Geocache;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class LocationSaver {
private final Provider<CacheSqlWriter> cacheWriterProvider;
private final TagReader tagReader;
@Inject
public LocationSaver(Provider<CacheSqlWriter> cacheWriterProvider, TagReader tagWriter) {
this.cacheWriterProvider = cacheWriterProvider;
this.tagReader = tagWriter;
}
public void saveLocation(Geocache geocache) {
CharSequence id = geocache.getId();
CacheSqlWriter cacheSqlWriter = cacheWriterProvider.get();
cacheSqlWriter.startWriting();
boolean found = tagReader.hasTag(id, Tag.FOUND);
cacheSqlWriter.insertAndUpdateCache(id, geocache.getName(), geocache.getLatitude(),
geocache.getLongitude(), geocache.getSourceType(), geocache.getSourceName(),
geocache.getCacheType(), geocache.getDifficulty(), geocache.getTerrain(),
geocache.getContainer(), geocache.getAvailable(), geocache.getArchived(), found);
cacheSqlWriter.stopWriting();
}
}
| 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;
public class Database {
public static final String DATABASE_NAME = "GeoBeagle.db";
public static final int DATABASE_VERSION = 18;
public static final String S0_COLUMN_CACHE_TYPE = "CacheType INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_CONTAINER = "Container INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1";
public static final String S0_COLUMN_DIFFICULTY = "Difficulty INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_TERRAIN = "Terrain INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_ARCHIVED = "Archived BOOLEAN NOT NULL Default 0";
public static final String S0_COLUMN_AVAILABLE = "Available BOOLEAN NOT NULL Default 1";
public static final String S0_INTENT = "intent";
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_V08 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR);";
public static final String SQL_CREATE_CACHE_TABLE_V10 = "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_CACHE_TABLE_V11 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", "
+ S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY
+ ", " + S0_COLUMN_TERRAIN + ");";
public static final String SQL_CREATE_CACHE_TABLE_V13 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", "
+ S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY
+ ", " + S0_COLUMN_TERRAIN + ", " + S0_COLUMN_AVAILABLE + ", " + S0_COLUMN_ARCHIVED + ");";
public static final String SQL_CREATE_CACHE_TABLE_V16 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", "
+ S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY
+ ", " + S0_COLUMN_TERRAIN + ", " + S0_COLUMN_AVAILABLE + ", " + S0_COLUMN_ARCHIVED
+ ", Visible BOOLEAN NOT NULL Default 1);";
public static final String SQL_CREATE_GPX_TABLE_V10 = "CREATE TABLE GPX ("
+ "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL);";
public static final String SQL_CREATE_TAGS_TABLE_V12 = "CREATE TABLE TAGS ("
+ "Cache VARCHAR NOT NULL, Id INTEGER 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_CREATE_IDX_TAGS = "CREATE INDEX IDX_TAGS on TAGS (Cache);";
public static final String SQL_CREATE_IDX_DESCRIPTION = "CREATE INDEX IF NOT EXISTS IDX_DESCRIPTION on CACHES (Description);";
public static final String SQL_CREATE_IDX_VISIBLE = "CREATE INDEX IF NOT EXISTS IDX_VISIBLE on CACHES (Visible);";
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_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, CacheType, Difficulty, "
+ "Terrain, Container, Available, Archived, Visible) 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 + "'" + "AND SOURCE != 'BCaching.com'";
public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1";
public static final String SQL_DELETE_ALL_CACHES = "DELETE FROM CACHES";
public static final String SQL_DELETE_ALL_GPX = "DELETE FROM GPX";
public static final String SQL_GET_EXPORT_TIME = "SELECT ExportTime FROM GPX WHERE Name = ?";
public static final String TBL_CACHES = "CACHES";
public static final String TBL_GPX = "GPX";
public static final String SQL_FORCE_UPDATE_ALL = "UPDATE GPX SET ExportTime = '1970-01-01'";
}
| 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;
public class WhereFactoryAllCaches implements WhereFactory {
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
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.database;
import android.database.Cursor;
import java.util.Iterator;
public class CursorIterator implements Iterator<String> {
private final Cursor cursor;
CursorIterator(Cursor cursor) {
this.cursor = cursor;
}
@Override
public boolean hasNext() {
return !cursor.isAfterLast();
}
@Override
public String next() {
String cache = cursor.getString(0);
cursor.moveToNext();
return cache;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 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.code.geobeagle.CacheType;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.database.filter.Filter;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* @author sng
*/
public class CacheSqlWriter {
static final String ANALYZE = "ANALYZE";
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
};
private final DbToGeocacheAdapter dbToGeocacheAdapter;
private final Provider<ISQLiteDatabase> sqliteProvider;
private final Filter filter;
@Inject
CacheSqlWriter(Provider<ISQLiteDatabase> writableDatabaseProvider,
DbToGeocacheAdapter dbToGeocacheAdapter,
Filter filter) {
sqliteProvider = writableDatabaseProvider;
this.dbToGeocacheAdapter = dbToGeocacheAdapter;
this.filter = filter;
}
public void deleteCache(CharSequence id) {
sqliteProvider.get().execSQL(Database.SQL_DELETE_CACHE, id);
}
public void insertAndUpdateCache(CharSequence id,
CharSequence name,
double latitude,
double longitude,
Source sourceType,
String sourceName,
CacheType cacheType,
int difficulty,
int terrain,
int container,
boolean available,
boolean archived,
boolean found) {
boolean visible = filter.showBasedOnFoundState(found)
&& filter.showBasedOnAvailableState(available)
&& filter.showBasedOnCacheType(cacheType) && filter.showBasedOnDnfState(id);
sqliteProvider.get().execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude),
new Double(longitude),
dbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName),
cacheType.toInt(), difficulty, terrain, container, available, archived, visible);
}
public void startWriting() {
sqliteProvider.get().beginTransaction();
}
public void stopWriting() {
// TODO: abort if no writes--otherwise sqlite is unhappy.
ISQLiteDatabase sqliteDatabase = sqliteProvider.get();
sqliteDatabase.setTransactionSuccessful();
sqliteDatabase.endTransaction();
sqliteDatabase.execSQL(ANALYZE);
}
}
| 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.code.geobeagle.activity.cachelist.SearchWhereFactory;
import com.google.code.geobeagle.database.DatabaseDI.SearchFactory;
import com.google.inject.Inject;
import android.database.Cursor;
import android.util.Log;
public class WhereFactoryNearestCaches implements WhereFactory {
static class BoundingBox {
public static final String[] ID_COLUMN = new String[] {
"Id"
};
private final ISQLiteDatabase mSqliteWrapper;
private final WhereStringFactory mWhereStringFactory;
private final double mLatitude;
private final double mLongitude;
private final SearchWhereFactory mSearchWhereFactory;
BoundingBox(double latitude,
double longitude,
ISQLiteDatabase sqliteWrapper,
WhereStringFactory whereStringFactory,
SearchWhereFactory searchWhereFactory) {
mLatitude = latitude;
mLongitude = longitude;
mSqliteWrapper = sqliteWrapper;
mWhereStringFactory = whereStringFactory;
mSearchWhereFactory = searchWhereFactory;
}
int getCount(float degreesDelta, int maxCount) {
String where = mWhereStringFactory.getWhereString(mLatitude, mLongitude, degreesDelta)
+ mSearchWhereFactory.getWhereString();
Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, ID_COLUMN, where, null, null,
null, "" + maxCount);
int count = cursor.getCount();
Log.d("GeoBeagle", "search: " + degreesDelta + ", count/maxCount: " + count + "/"
+ maxCount + " where: " + where);
cursor.close();
return count;
}
}
static class Search {
private final BoundingBox mBoundingBox;
private final SearchDown mSearchDown;
private final SearchUp mSearchUp;
public Search(BoundingBox boundingBox, SearchDown searchDown, SearchUp searchUp) {
mBoundingBox = boundingBox;
mSearchDown = searchDown;
mSearchUp = searchUp;
}
public float search(float guess, int target) {
if (mBoundingBox.getCount(guess, target + 1) > target)
return mSearchDown.search(guess, target);
return mSearchUp.search(guess, target);
}
}
static public class SearchDown {
private final BoundingBox mHasValue;
private final float mMin;
public SearchDown(BoundingBox boundingBox, float min) {
mHasValue = boundingBox;
mMin = min;
}
public float search(float guess, int targetMin) {
final float lowerGuess = guess / WhereFactoryNearestCaches.DISTANCE_MULTIPLIER;
if (lowerGuess < mMin)
return guess;
if (mHasValue.getCount(lowerGuess, targetMin + 1) >= targetMin)
return search(lowerGuess, targetMin);
return guess;
}
}
static class SearchUp {
private final BoundingBox mBoundingBox;
private final float mMax;
public SearchUp(BoundingBox boundingBox, float max) {
mBoundingBox = boundingBox;
mMax = max;
}
public float search(float guess, int targetMin) {
final float nextGuess = guess * WhereFactoryNearestCaches.DISTANCE_MULTIPLIER;
if (nextGuess > mMax)
return guess;
if (mBoundingBox.getCount(guess, targetMin) < targetMin) {
return search(nextGuess, targetMin);
}
return guess;
}
}
// 1 degree ~= 111km
static final float DEGREES_DELTA = 0.1f;
static final float DISTANCE_MULTIPLIER = 1.414f;
static final int GUESS_MAX = 180;
static final float GUESS_MIN = 0.01f;
static final int MAX_NUMBER_OF_CACHES = 100;
public static class WhereStringFactory {
String getWhereString(double latitude, double longitude, float degrees) {
double latLow = latitude - degrees;
double latHigh = latitude + degrees;
double lat_radians = Math.toRadians(latitude);
double cos_lat = Math.cos(lat_radians);
double lonLow = Math.max(-180, longitude - degrees / cos_lat);
double lonHigh = Math.min(180, longitude + degrees / cos_lat);
return "Visible = 1 AND Latitude > " + latLow + " AND Latitude < " + latHigh
+ " AND Longitude > " + lonLow + " AND Longitude < " + lonHigh;
}
}
private float mLastGuess = 0.1f;
private final SearchFactory mSearchFactory;
private final WhereStringFactory mWhereStringFactory;
private final DbFrontend mDbFrontend;
private final SearchWhereFactory mSearchWhereFactory;
@Inject
public WhereFactoryNearestCaches(SearchFactory searchFactory,
WhereStringFactory whereStringFactory,
SearchWhereFactory searchWhereFactory,
DbFrontend dbFrontend) {
mSearchFactory = searchFactory;
mWhereStringFactory = whereStringFactory;
mDbFrontend = dbFrontend;
mSearchWhereFactory = searchWhereFactory;
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
int totalCaches = mDbFrontend.countAll();
int maxNumberOfCaches = Math.min(totalCaches, MAX_NUMBER_OF_CACHES);
mLastGuess = mSearchFactory.createSearch(latitude, longitude, GUESS_MIN, GUESS_MAX).search(
mLastGuess, maxNumberOfCaches);
return mWhereStringFactory.getWhereString(latitude, longitude, mLastGuess)
+ mSearchWhereFactory.getWhereString();
}
}
| 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.database.Cursor;
public class FoundCaches {
private final Cursor cursor;
public FoundCaches(Cursor cursor) {
this.cursor = cursor;
}
public int getCount() {
return cursor.getCount();
}
public Iterable<String> getCaches() {
return new IterableIterator<String>(new CursorIterator(cursor));
}
public void close() {
cursor.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.database;
public interface HasValue {
int get(float search, int maxCaches);
}
| 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.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import android.database.Cursor;
public class CacheReaderCursor {
private final Cursor mCursor;
private final DbToGeocacheAdapter mDbToGeocacheAdapter;
private final GeocacheFactory mGeocacheFactory;
public CacheReaderCursor(Cursor cursor, GeocacheFactory geocacheFactory,
DbToGeocacheAdapter dbToGeocacheAdapter) {
mCursor = cursor;
mGeocacheFactory = geocacheFactory;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
public void close() {
mCursor.close();
}
public Geocache getCache() {
String sourceName = mCursor.getString(4);
CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(Integer.parseInt(mCursor
.getString(5)));
int difficulty = Integer.parseInt(mCursor.getString(6));
int terrain = Integer.parseInt(mCursor.getString(7));
int container = Integer.parseInt(mCursor.getString(8));
boolean available = mCursor.getInt(9) != 0;
boolean archived = mCursor.getInt(10) != 0;
return mGeocacheFactory.create(mCursor.getString(2), mCursor.getString(3), mCursor
.getDouble(0), mCursor.getDouble(1), mDbToGeocacheAdapter
.sourceNameToSourceType(sourceName), sourceName, cacheType, difficulty, terrain,
container, available, archived);
}
public int count() {
return mCursor.getCount();
}
public boolean moveToNext() {
return mCursor.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.database;
public interface ClearCachesFromSource {
public void clearCaches(String source);
void clearEarlierLoads();
}
| 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;
/**
* Where clause with limits set during construction, not when calling getWhere()
*/
public class WhereFactoryFixedArea implements WhereFactory {
private final double mLatLow;
private final double mLonLow;
private final double mLatHigh;
private final double mLonHigh;
public WhereFactoryFixedArea(double latLow, double lonLow, double latHigh, double lonHigh) {
//TODO(sng): I don't think these min/max'es should be necessary; try removing them.
mLatLow = Math.min(latLow, latHigh);
mLonLow = Math.min(lonLow, lonHigh);
mLatHigh = Math.max(latLow, latHigh);
mLonHigh = Math.max(lonLow, lonHigh);
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
return "Latitude >= " + mLatLow + " AND Latitude < " + mLatHigh + " AND Longitude >= "
+ mLonLow + " AND Longitude < " + mLonHigh;
}
}
| 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.Inject;
import com.google.inject.Provider;
public class ClearCachesFromSourceImpl implements ClearCachesFromSource {
private final Provider<ISQLiteDatabase> sqliteProvider;
@Inject
public
ClearCachesFromSourceImpl(Provider<ISQLiteDatabase> sqliteProvider) {
this.sqliteProvider = sqliteProvider;
}
@Override
public void clearCaches(String source) {
sqliteProvider.get().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.
*/
@Override
public void clearEarlierLoads() {
ISQLiteDatabase sqliteDatabase = sqliteProvider.get();
for (String sql : CacheSqlWriter.SQLS_CLEAR_EARLIER_LOADS) {
sqliteDatabase.execSQL(sql);
}
}
} | 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;
public interface GpxTableWriter {
boolean isGpxAlreadyLoaded(String mGpxName, String sqlDate);
}
| 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.filter;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.Tag;
import com.google.inject.Inject;
class CacheVisibilityStore {
private final DbFrontend dbFrontEnd;
@Inject
public CacheVisibilityStore(DbFrontend dbFrontend) {
this.dbFrontEnd = dbFrontend;
}
void setInvisible(String cache) {
dbFrontEnd.getDatabase().execSQL("UPDATE CACHES SET Visible = 0 WHERE ID = ?", cache);
}
void setAllVisible() {
dbFrontEnd.getDatabase().execSQL("UPDATE CACHES SET Visible = 1");
}
public void hideUnavailableCaches() {
dbFrontEnd.getDatabase().execSQL("UPDATE CACHES SET Visible = 0 WHERE Available = 0");
}
public void hideWaypoints() {
dbFrontEnd.getDatabase().execSQL("UPDATE CACHES SET Visible = 0 WHERE CacheType >= 20");
}
public void hideFoundCaches(boolean hideFound, boolean hideDnf) {
String whereString = "";
if (hideFound && hideDnf) {
whereString = "";
} else if (hideFound && !hideDnf) {
whereString = "WHERE Id = " + Tag.FOUND.ordinal();
} else if (!hideFound && hideDnf) {
whereString = "WHERE Id = " + Tag.DNF.ordinal();
} else {
return;
}
dbFrontEnd.getDatabase().execSQL(
"UPDATE CACHES SET Visible = 0 WHERE Id IN " + "(SELECT Cache FROM TAGS "
+ whereString + ")");
}
}
| 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.filter;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class FilterCleanliness {
private static final String PREF_FILTER_DIRTY = "filter-dirty";
private final SharedPreferences sharedPreferences;
@Inject
FilterCleanliness(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
public void markDirty(boolean dirty) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(PREF_FILTER_DIRTY, dirty);
editor.commit();
}
public boolean isDirty() {
return sharedPreferences.getBoolean(PREF_FILTER_DIRTY, 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.database.filter;
import com.google.code.geobeagle.activity.cachelist.presenter.filter.UpdateFilterHandler;
import com.google.code.geobeagle.activity.preferences.Preferences;
import com.google.inject.Inject;
import roboguice.util.RoboThread;
import android.content.SharedPreferences;
public class UpdateFilterWorker extends RoboThread {
private final UpdateFilterHandler updateFilterHandler;
private final SharedPreferences sharedPreferences;
private final CacheVisibilityStore cacheVisibilityStore;
@Inject
public UpdateFilterWorker(SharedPreferences sharedPreferences,
UpdateFilterHandler updateFilterHandler,
CacheVisibilityStore cacheVisibilityStore) {
this.updateFilterHandler = updateFilterHandler;
this.sharedPreferences = sharedPreferences;
this.cacheVisibilityStore = cacheVisibilityStore;
}
@Override
public void run() {
cacheVisibilityStore.setAllVisible();
if (!sharedPreferences.getBoolean(Preferences.SHOW_WAYPOINTS, false)) {
updateFilterHandler.setProgressMessage("Filtering waypoints");
cacheVisibilityStore.hideWaypoints();
}
if (!sharedPreferences.getBoolean(Preferences.SHOW_UNAVAILABLE_CACHES, false)) {
updateFilterHandler.setProgressMessage("Filtering unavailable caches");
cacheVisibilityStore.hideUnavailableCaches();
}
boolean showFound = sharedPreferences.getBoolean(Preferences.SHOW_FOUND_CACHES, false);
boolean showDnf = sharedPreferences.getBoolean(Preferences.SHOW_DNF_CACHES, true);
if (!showFound || !showDnf) {
updateFilterHandler.setProgressMessage("Filtering found/dnf caches");
cacheVisibilityStore.hideFoundCaches(!showFound, !showDnf);
}
updateFilterHandler.endFiltering();
}
}
| 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.filter;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.database.WhereFactory;
import com.google.code.geobeagle.database.WhereFactoryAllCaches;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches;
import com.google.inject.Inject;
import roboguice.inject.ContextScoped;
@ContextScoped
public class FilterNearestCaches {
private boolean mIsFiltered = true;
private final WhereFactory mWhereFactories[];
@Inject
public FilterNearestCaches(WhereFactoryAllCaches whereFactoryAllCaches,
WhereFactoryNearestCaches whereFactoryNearestCaches) {
mWhereFactories = new WhereFactory[] {
whereFactoryAllCaches, whereFactoryNearestCaches
};
}
public int getMenuString() {
return mIsFiltered ? R.string.menu_show_all_caches : R.string.menu_show_nearest_caches;
}
public int getTitleText() {
return mIsFiltered ? R.string.cache_list_title : R.string.cache_list_title_all;
}
public WhereFactory getWhereFactory() {
return mWhereFactories[mIsFiltered ? 1 : 0];
}
public void toggle() {
mIsFiltered = !mIsFiltered;
}
}
| 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.filter;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.activity.preferences.Preferences;
import com.google.code.geobeagle.database.Tag;
import com.google.code.geobeagle.database.TagReader;
import com.google.inject.Inject;
import android.content.SharedPreferences;
public class Filter {
private final SharedPreferences sharedPreferences;
private final TagReader tagReader;
@Inject
public Filter(SharedPreferences sharedPreferences, TagReader tagReader) {
this.sharedPreferences = sharedPreferences;
this.tagReader = tagReader;
}
public boolean showBasedOnFoundState(boolean found) {
boolean showFoundCaches = sharedPreferences.getBoolean(Preferences.SHOW_FOUND_CACHES,
false);
return showFoundCaches || !found;
}
public boolean showBasedOnDnfState(CharSequence geocacheId) {
boolean showDnfCaches = sharedPreferences.getBoolean(Preferences.SHOW_DNF_CACHES, true);
return showDnfCaches || !tagReader.hasTag(geocacheId, Tag.DNF);
}
public boolean showBasedOnAvailableState(boolean available) {
boolean showUnavailableCaches = sharedPreferences.getBoolean(
Preferences.SHOW_UNAVAILABLE_CACHES, false);
return showUnavailableCaches || available;
}
public boolean showBasedOnCacheType(CacheType cacheType) {
boolean showWaypoints = sharedPreferences.getBoolean(Preferences.SHOW_WAYPOINTS, false);
return showWaypoints || cacheType.toInt() < CacheType.WAYPOINT.toInt();
}
}
| 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.filter;
import com.google.inject.Inject;
import roboguice.inject.ContextScoped;
import android.app.ProgressDialog;
import android.content.Context;
@ContextScoped
public class FilterProgressDialog extends ProgressDialog {
@Inject
public FilterProgressDialog(Context context) {
super(context);
setIndeterminate(true);
setTitle("Filtering caches");
setCancelable(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.database;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.cachedetails.DetailsDatabaseWriter;
import com.google.code.geobeagle.database.DatabaseDI.GeoBeagleSqliteOpenHelper;
import com.google.code.geobeagle.preferences.PreferencesUpgrader;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
/**
* Will develop to represent the front-end to access a database. It takes
* responsibility to mSqliteOpenHelper and close the actual database connection
* without involving the clients of this class.
*/
@Singleton
public class DbFrontend {
private final CacheReader mCacheReader;
private final Context mContext;
private ISQLiteDatabase mDatabase;
private GeoBeagleSqliteOpenHelper mSqliteOpenHelper;
private final PreferencesUpgrader mPreferencesUpgrader;
private final DetailsDatabaseWriter mSdDatabase;
@Inject
DbFrontend(Activity activity,
CacheReader cacheReader,
PreferencesUpgrader preferencesUpgrader,
DetailsDatabaseWriter detailsDatabaseWriter) {
mCacheReader = cacheReader;
mPreferencesUpgrader = preferencesUpgrader;
mContext = activity.getApplicationContext();
mSdDatabase = detailsDatabaseWriter;
}
public synchronized void closeDatabase() {
Log.d("GeoBeagleDb", this + ": DbFrontend.closeDatabase() " + mContext);
if (mContext == null || mSqliteOpenHelper == null)
return;
mSqliteOpenHelper.close();
mDatabase = null;
mSqliteOpenHelper = null;
}
public int count(int latitude, int longitude, WhereFactoryFixedArea whereFactory) {
openDatabase();
Cursor countCursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES
+ " WHERE " + whereFactory.getWhere(mDatabase, latitude, longitude), null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
Log.d("GeoBeagle", this + ": DbFrontEnd.count:" + count);
return count;
}
public int countAll() {
openDatabase();
Cursor countCursor = mDatabase
.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES, null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
Log.d("GeoBeagle", this + ": DbFrontEnd.count all:" + count);
return count;
}
public ArrayList<Geocache> loadCaches(double latitude, double longitude,
WhereFactory whereFactory) {
Log.d("GeoBeagle", "DbFrontend.loadCaches " + latitude + ", " + longitude);
openDatabase();
CacheReaderCursor cursor = mCacheReader.open(latitude, longitude, whereFactory, null);
ArrayList<Geocache> geocaches = new ArrayList<Geocache>();
if (cursor != null) {
do {
geocaches.add(cursor.getCache());
} while (cursor.moveToNext());
cursor.close();
}
return geocaches;
}
public synchronized void openDatabase() {
if (mSqliteOpenHelper != null)
return;
Log.d("GeoBeagleDb", this + ": DbFrontend.openDatabase() " + mContext);
mSqliteOpenHelper = new GeoBeagleSqliteOpenHelper(mContext, mPreferencesUpgrader);
mDatabase = new DatabaseDI.SQLiteWrapper(mSqliteOpenHelper.getWritableDatabase());
}
public Geocache getCache(CharSequence cacheId) {
CacheReaderCursor cacheReader = mCacheReader.open(cacheId);
Geocache cache = cacheReader.getCache();
cacheReader.close();
return cache;
}
public void deleteAll() {
openDatabase();
mDatabase.execSQL(Database.SQL_DELETE_ALL_CACHES);
mDatabase.execSQL(Database.SQL_DELETE_ALL_GPX);
mSdDatabase.deleteAll();
}
public void forceUpdate() {
openDatabase();
mDatabase.execSQL(Database.SQL_FORCE_UPDATE_ALL);
}
public ISQLiteDatabase getDatabase() {
openDatabase();
return mDatabase;
}
/*
* public void onPause() { closeDatabase(); }
*/
/*
* public void onResume() { //Lazy evaluation - mSqliteOpenHelper database
* when needed }
*/
}
| 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.code.geobeagle.Geocache;
import java.util.ArrayList;
public class Geocaches {
private final ArrayList<Geocache> mGeocaches;
public Geocaches() {
mGeocaches = new ArrayList<Geocache>();
}
public void add(Geocache geocache) {
mGeocaches.add(geocache);
}
public void clear() {
mGeocaches.clear();
}
public ArrayList<Geocache> getAll() {
return mGeocaches;
}
}
| 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;
public enum Tag {
FOUND, 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.database;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
class TagStore {
private static final String COLUMN_CACHE = "Cache";
private static final String TBL_TAGS = "TAGS";
private final ContentValues hideColumn;
private final Provider<ISQLiteDatabase> databaseProvider;
private final String[] columns;
@Inject
public TagStore(Provider<ISQLiteDatabase> databaseProvider) {
this.databaseProvider = databaseProvider;
hideColumn = new ContentValues();
hideColumn.put("Visible", 0);
columns = new String[] {
COLUMN_CACHE, "Id"
};
}
void addTag(CharSequence geocacheId, Tag tag) {
ISQLiteDatabase database = databaseProvider.get();
database.delete(TBL_TAGS, COLUMN_CACHE, (String)geocacheId);
database.insert(TBL_TAGS, columns, new Object[] {
geocacheId, tag.ordinal()
});
}
void hideCache(CharSequence geocacheId) {
ISQLiteDatabase database = databaseProvider.get();
database.update(Database.TBL_CACHES, hideColumn, "ID=?", new String[] {
geocacheId.toString()
});
}
Cursor getFoundCaches() {
ISQLiteDatabase database = databaseProvider.get();
Cursor foundCachesCursor = database.query(TBL_TAGS, new String[] {
COLUMN_CACHE
}, "Id = ?", new String[] {
String.valueOf(Tag.FOUND.ordinal())
}, null, null, null, null);
foundCachesCursor.moveToFirst();
return foundCachesCursor;
}
boolean hasTag(CharSequence geocacheId, Tag tag) {
ISQLiteDatabase database = null;
try {
database = databaseProvider.get();
} catch (ProvisionException e) {
Log.e("GeoBeagle", "Provision exception");
return false;
}
boolean hasValue = database.hasValue(TBL_TAGS, columns, new String[] {
geocacheId.toString(), String.valueOf(tag.ordinal())
});
return hasValue;
}
}
| 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;
public interface WhereFactory {
public abstract String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude);
}
| 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.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.activity.cachelist.SearchWhereFactory;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.BoundingBox;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.Search;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.SearchDown;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.SearchUp;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.WhereStringFactory;
import com.google.code.geobeagle.preferences.PreferencesUpgrader;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Arrays;
public class DatabaseDI {
public static class CacheReaderCursorFactory {
public CacheReaderCursor create(Cursor cursor) {
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheReaderCursor(cursor, geocacheFactory, dbToGeocacheAdapter);
}
}
static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper {
private final OpenHelperDelegate mOpenHelperDelegate;
private final PreferencesUpgrader mPreferencesUpgrader;
GeoBeagleSqliteOpenHelper(Context context, PreferencesUpgrader preferencesUpgrader) {
super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
mOpenHelperDelegate = new OpenHelperDelegate();
mPreferencesUpgrader = preferencesUpgrader;
}
SQLiteWrapper getWritableSqliteWrapper() {
return new SQLiteWrapper(this.getWritableDatabase());
}
@Override
public void onCreate(SQLiteDatabase db) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onCreate(sqliteWrapper);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onUpgrade(sqliteWrapper, oldVersion);
mPreferencesUpgrader.upgrade(oldVersion);
}
}
public static class SQLiteWrapper implements ISQLiteDatabase {
private final SQLiteDatabase mSQLiteDatabase;
SQLiteWrapper(SQLiteDatabase writableDatabase) {
mSQLiteDatabase = writableDatabase;
}
@Override
public void beginTransaction() {
mSQLiteDatabase.beginTransaction();
}
@Override
public int countResults(String table, String selection, String... selectionArgs) {
Cursor cursor = mSQLiteDatabase.query(table, null, selection, selectionArgs, null,
null, null, null);
int count = cursor.getCount();
Log.d("GeoBeagle", "SQL count results: " + selection + ", "
+ Arrays.toString(selectionArgs) + ": " + count);
cursor.close();
return count;
}
@Override
public void endTransaction() {
mSQLiteDatabase.endTransaction();
}
public void execSQL(String sql) {
Log.d("GeoBeagle", this + " :SQL: " + sql);
mSQLiteDatabase.execSQL(sql);
}
@Override
public void execSQL(String sql, Object... bindArgs) {
Log.d("GeoBeagle", this + " :SQL: " + sql + ", " + Arrays.toString(bindArgs));
mSQLiteDatabase.execSQL(sql, bindArgs);
}
@Override
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
final Cursor query = mSQLiteDatabase.query(table, columns, selection, selectionArgs,
groupBy, orderBy, having, limit);
// Log.d("GeoBeagle", "limit: " + limit + ", count: " +
// query.getCount() + ", query: "
// + selection);
Log.d("GeoBeagle", "limit: " + limit + ", query: " + selection);
return query;
}
@Override
public Cursor query(String table,
String[] columns,
String selection,
String selectionArgs[],
String groupBy,
String having,
String orderBy,
String limit) {
final Cursor query = mSQLiteDatabase.query(table, columns, selection, selectionArgs,
groupBy, orderBy, having, limit);
Log.d("GeoBeagle", "limit: " + limit + ", query: " + selection);
return query;
}
@Override
public Cursor rawQuery(String sql, String[] selectionArgs) {
return mSQLiteDatabase.rawQuery(sql, selectionArgs);
}
@Override
public void setTransactionSuccessful() {
mSQLiteDatabase.setTransactionSuccessful();
}
@Override
public void close() {
Log.d("GeoBeagle", "----------closing sqlite------");
mSQLiteDatabase.close();
}
@Override
public boolean isOpen() {
return mSQLiteDatabase.isOpen();
}
@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);
}
mSQLiteDatabase.execSQL("REPLACE INTO " + table + " (" + columnsAsString.substring(2)
+ ") VALUES (?, ?)", bindArgs);
}
@Override
public boolean hasValue(String table, String[] columns, String[] selectionArgs) {
StringBuilder where = new StringBuilder();
where.append(columns[0] + "=?");
for (int ix = 1; ix < columns.length; ix++) {
where.append(" AND " + columns[ix] + "=?");
}
Cursor c = mSQLiteDatabase.query(table, new String[] {
columns[0]
}, where.toString(), selectionArgs, null, null, null);
boolean hasValues = c.moveToFirst();
c.close();
return hasValues;
}
@Override
public void delete(String table, String whereClause, String whereArg) {
mSQLiteDatabase.delete(table, whereClause + "=?", new String[] {
whereArg
});
}
@Override
public void update(String table,
ContentValues values,
String whereClause,
String[] whereArgs) {
Log.d("GeoBeagle", "updating: " + table + ", " + values + ", " + whereClause + ", "
+ whereArgs);
mSQLiteDatabase.update(table, values, whereClause, whereArgs);
}
}
static public class SearchFactory {
private final SearchWhereFactory searchWhereFactory;
private final WhereStringFactory whereStringFactory;
private final Provider<ISQLiteDatabase> sqliteWrapperProvider;
SearchFactory(WhereStringFactory whereStringFactory,
Provider<ISQLiteDatabase> sqliteWrapperProvider,
SearchWhereFactory searchWhereFactory) {
this.searchWhereFactory = searchWhereFactory;
this.whereStringFactory = whereStringFactory;
this.sqliteWrapperProvider = sqliteWrapperProvider;
}
@Inject
SearchFactory(Injector injector) {
this.whereStringFactory = injector.getInstance(WhereStringFactory.class);
this.sqliteWrapperProvider = injector.getProvider(ISQLiteDatabase.class);
this.searchWhereFactory = injector.getInstance(SearchWhereFactory.class);
}
public Search createSearch(double latitude, double longitude, float min, float max) {
BoundingBox boundingBox = new BoundingBox(latitude, longitude,
sqliteWrapperProvider.get(), whereStringFactory, searchWhereFactory);
SearchDown searchDown = new SearchDown(boundingBox, min);
SearchUp searchUp = new SearchUp(boundingBox, max);
return new WhereFactoryNearestCaches.Search(boundingBox, searchDown, searchUp);
}
}
}
| 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.code.geobeagle.xmlimport.SyncCollectingParameter;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import android.database.Cursor;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Singleton
public class GpxTableWriterGpxFiles implements GpxTableWriter {
private String currentGpxTimeString;
private final Provider<ISQLiteDatabase> sqliteProvider;
private final String[] queryArgs = new String[1];
private final SimpleDateFormat displayDateFormat = new SimpleDateFormat("MM-dd HH:mm");
private final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final SyncCollectingParameter syncCollectingParameter;
@Inject
GpxTableWriterGpxFiles(Provider<ISQLiteDatabase> sqliteProvider,
SyncCollectingParameter syncCollectingParameter) {
this.sqliteProvider = sqliteProvider;
this.currentGpxTimeString = "2000-01-01 01:00:00.000";
this.syncCollectingParameter = syncCollectingParameter;
}
/**
* Return True if the gpx is already loaded. Mark this gpx and its caches in
* the database to protect them from being nuked when the load is complete.
*
* @param gpxName
* @param gpxTimeString
* @return
*/
@Override
public boolean isGpxAlreadyLoaded(String gpxName, String gpxTimeString) {
Cursor cursor = null;
ISQLiteDatabase sqliteDatabase;
String dbTimeString = "";
try {
currentGpxTimeString = gpxTimeString;
sqliteDatabase = sqliteProvider.get();
queryArgs[0] = gpxName;
cursor = sqliteDatabase.rawQuery(Database.SQL_GET_EXPORT_TIME, queryArgs);
if (!cursor.moveToFirst()) {
syncCollectingParameter.Log(" initial sync");
return false;
}
dbTimeString = cursor.getString(0);
Date gpxTime = sqlDateFormat.parse(gpxTimeString);
Date dbTime = sqlDateFormat.parse(dbTimeString);
if (gpxTime.after(dbTime)) {
syncCollectingParameter.Log(displayDateFormat.format(dbTime) + " --> "
+ displayDateFormat.format(gpxTime));
return false;
}
syncCollectingParameter.Log(" no changes since " + displayDateFormat.format(dbTime));
return true;
} catch (ParseException e) {
Log.d("GeoBeagle", "error parsing dates:" + gpxTimeString + ", " + dbTimeString);
return false;
} finally {
if (cursor != null)
cursor.close();
}
}
public void writeGpx(String gpxName) {
sqliteProvider.get().execSQL(Database.SQL_REPLACE_GPX, gpxName, currentGpxTimeString);
currentGpxTimeString = "2000-01-01 01:00:00.000";
}
}
| 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 java.util.Iterator;
class IterableIterator<T> implements Iterable<T> {
private final Iterator<T> iter;
public IterableIterator(Iterator<T> iter) {
this.iter = iter;
}
@Override
public Iterator<T> iterator() {
return iter;
}
}
| 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;
public interface ISQLiteDatabase {
void beginTransaction();
void close();
int countResults(String table, String sql, String... args);
void delete(String table, String where, String bindArg);
void endTransaction();
void execSQL(String s, Object... bindArg1);
boolean hasValue(String table, String[] selection, String[] selectionArgs);
void insert(String table, String[] columns, Object[] bindArgs);
boolean isOpen();
Cursor query(String table,
String[] columns,
String selection,
String groupBy,
String having,
String orderBy,
String limit,
String... selectionArgs);
Cursor query(String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit);
Cursor rawQuery(String string, String[] object);
void setTransactionSuccessful();
void update(String string, ContentValues contentValues, String whereClause, String[] strings);
}
| 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.Inject;
public class ClearCachesFromSourceNull implements ClearCachesFromSource {
@Inject
public
ClearCachesFromSourceNull() {
}
@Override
public void clearCaches(String source) {
}
@Override
public void clearEarlierLoads() {
}
} | 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.code.geobeagle.GeocacheFactory.Source;
public class DbToGeocacheAdapter {
public Source sourceNameToSourceType(String sourceName) {
if (sourceName == null)
return Source.GPX;
if (sourceName.equals("intent"))
return Source.WEB_URL;
else if (sourceName.equals("mylocation"))
return Source.MY_LOCATION;
else if (sourceName.toLowerCase().endsWith((".loc")))
return Source.LOC;
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;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
@SuppressWarnings("unchecked")
class ClassToTypeLiteralMatcherAdapter extends AbstractMatcher<TypeLiteral> {
protected final Matcher<Class> classMatcher;
public ClassToTypeLiteralMatcherAdapter(Matcher<Class> classMatcher) {
this.classMatcher = classMatcher;
}
public boolean matches(TypeLiteral typeLiteral) {
return classMatcher.matches(typeLiteral.getRawType());
}
}
| 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 android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
public class Azimuth {
private double currentAzimuth;
private float[] gravity;
private float[] geomagnetic;
private float rotationMatrix[] = new float[9];
private float identityMatrix[] = new float[9];
private float orientations[] = new float[3];
public Azimuth() {
rotationMatrix = new float[9];
identityMatrix = new float[9];
orientations = new float[9];
}
public void sensorChanged(SensorEvent event) {
boolean sensorReady = false;
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
gravity = event.values.clone();
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
geomagnetic = event.values.clone();
sensorReady = true;
}
if (gravity == null || geomagnetic == null || !sensorReady) {
return;
}
if (!SensorManager.getRotationMatrix(rotationMatrix, identityMatrix, gravity, geomagnetic)) {
return;
}
SensorManager.getOrientation(rotationMatrix, orientations);
currentAzimuth = Math.toDegrees(orientations[0]);
}
public double getAzimuth() {
return currentAzimuth;
}
}
| 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;
public enum CacheType {
NULL(0, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "null"),
MULTI(2, R.drawable.cache_multi, R.drawable.cache_multi_big,
R.drawable.pin_multi, "multi"),
TRADITIONAL(1, R.drawable.cache_tradi, R.drawable.cache_tradi_big,
R.drawable.pin_tradi, "traditional"),
UNKNOWN(3, R.drawable.cache_mystery, R.drawable.cache_mystery_big,
R.drawable.pin_mystery, "unknown"),
MY_LOCATION(4, R.drawable.blue_dot, R.drawable.blue_dot,
R.drawable.pin_default, "my location"),
//Caches without unique icons
EARTHCACHE(5, R.drawable.cache_earth, R.drawable.cache_earth_big,
R.drawable.pin_earth, "earth"),
VIRTUAL(6, R.drawable.cache_virtual, R.drawable.cache_virtual_big,
R.drawable.pin_virtual, "virtual"),
LETTERBOX_HYBRID(7, R.drawable.cache_letterbox, R.drawable.cache_letterbox_big,
R.drawable.pin_letter, "letterbox"),
EVENT(8, R.drawable.cache_event, R.drawable.cache_event_big,
R.drawable.pin_event, "event"),
WEBCAM(9, R.drawable.cache_webcam, R.drawable.cache_webcam_big,
R.drawable.pin_webcam, "webcam"),
//Caches without unique icons
CITO(10, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "cache in trash out"),
LOCATIONLESS(11, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "reverse"),
APE(12, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "project ape"),
MEGA(13, R.drawable.cache_mega, R.drawable.cache_mega_big,
R.drawable.pin_mega, "mega-event"),
WHERIGO(14, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "wherigo"),
//Waypoint types
WAYPOINT(20, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.pin_default, "waypoint"), //Not actually seen in GPX...
WAYPOINT_PARKING(21, R.drawable.cache_waypoint_p, R.drawable.cache_waypoint_p_big,
R.drawable.map_pin2_wp_p, "waypoint|parking area"),
WAYPOINT_REFERENCE(22, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "waypoint|reference point"),
WAYPOINT_STAGES(23, R.drawable.cache_waypoint_s, R.drawable.cache_waypoint_s_big,
R.drawable.map_pin2_wp_s, "waypoint|stages of a multicache"),
WAYPOINT_TRAILHEAD(24, R.drawable.cache_waypoint_t, R.drawable.cache_waypoint_t_big,
R.drawable.map_pin2_wp_t, "waypoint|trailhead"),
WAYPOINT_FINAL(25, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "waypoint|final location"); //TODO: Doesn't have unique graphics yet
private final int mIconId;
private final int mIconIdBig;
private final int mIx;
private final int mIconIdMap;
private final String mTag;
CacheType(int ix, int drawableId, int drawableIdBig, int drawableIdMap,
String tag) {
mIx = ix;
mIconId = drawableId;
mIconIdBig = drawableIdBig;
mIconIdMap = drawableIdMap;
mTag = tag;
}
public int icon() {
return mIconId;
}
public int iconBig() {
return mIconIdBig;
}
public int toInt() {
return mIx;
}
public int iconMap() {
return mIconIdMap;
}
public String getTag() {
return mTag;
}
}
| 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.Inject;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface.OnClickListener;
public class ErrorDisplayer {
static class DisplayErrorRunnable implements Runnable {
private final Builder mAlertDialogBuilder;
DisplayErrorRunnable(Builder alertDialogBuilder) {
mAlertDialogBuilder = alertDialogBuilder;
}
@Override
public void run() {
mAlertDialogBuilder.create().show();
}
}
private final Activity mActivity;
private final OnClickListener mOnClickListener;
@Inject
public ErrorDisplayer(Activity activity, OnClickListenerNOP onClickListener) {
mActivity = activity;
mOnClickListener = onClickListener;
}
public void displayError(int resId, Object... args) {
final Builder alertDialogBuilder = new Builder(mActivity);
alertDialogBuilder.setMessage(String.format((String)mActivity.getText(resId), args));
alertDialogBuilder.setNeutralButton("Ok", mOnClickListener);
mActivity.runOnUiThread(new DisplayErrorRunnable(alertDialogBuilder));
}
}
| 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.formatting;
public class DistanceFormatterImperial implements DistanceFormatter {
public CharSequence formatDistance(float distance) {
if (distance == -1) {
return "";
}
final float miles = distance / 1609.344f;
if (miles > 0.05)
return String.format("%1$1.2fmi", miles);
final int feet = (int)(miles * 5280.0f);
return String.format("%1$1dft", feet);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.