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.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
public interface HasDistanceFormatter {
public abstract void setDistanceFormatter(DistanceFormatter distanceFormatter);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import com.google.code.geobeagle.activity.cachelist.model.CacheListData;
public class AdapterCachesSorter implements RefreshAction {
private final CacheListData mCacheListData;
private final LocationControlBuffered mLocationControlBuffered;
private final CacheListDelegateDI.Timing mTiming;
public AdapterCachesSorter(CacheListData cacheListData, CacheListDelegateDI.Timing timing,
LocationControlBuffered locationControlBuffered) {
mCacheListData = cacheListData;
mTiming = timing;
mLocationControlBuffered = locationControlBuffered;
}
public void refresh() {
mLocationControlBuffered.getSortStrategy().sort(mCacheListData.get());
mTiming.lap("sort time");
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
public class LocationTolerance implements ToleranceStrategy {
private IGpsLocation mLastRefreshLocation;
private final float mLocationTolerance;
private final int mMinTimeBetweenRefresh;
private long mLastRefreshTime;
public LocationTolerance(float locationTolerance, IGpsLocation lastRefreshed,
int minTimeBetweenRefresh) {
mLocationTolerance = locationTolerance;
mLastRefreshLocation = lastRefreshed;
mMinTimeBetweenRefresh = minTimeBetweenRefresh;
mLastRefreshTime = 0;
}
public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) {
if (now < mLastRefreshTime + mMinTimeBetweenRefresh)
return false;
final float distanceTo = here.distanceTo(mLastRefreshLocation);
// Log.d("GeoBeagle", "distance, tolerance: " + distanceTo + ", " +
// mLocationTolerance);
final boolean fExceedsTolerance = distanceTo >= mLocationTolerance;
return fExceedsTolerance;
}
public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) {
// Log.d("GeoBeagle", "updateLastRefreshed here: " + here);
mLastRefreshLocation = here;
mLastRefreshTime = now;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI.Timing;
import com.google.code.geobeagle.activity.cachelist.model.CacheListData;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.FilterNearestCaches;
import android.location.Location;
import java.util.ArrayList;
public class SqlCacheLoader implements RefreshAction {
private final CacheListData mCacheListData;
private final FilterNearestCaches mFilterNearestCaches;
private final DbFrontend mDbFrontend;
private final LocationControlBuffered mLocationControlBuffered;
private final Timing mTiming;
private final TitleUpdater mTitleUpdater;
public SqlCacheLoader(DbFrontend dbFrontend, FilterNearestCaches filterNearestCaches,
CacheListData cacheListData, LocationControlBuffered locationControlBuffered,
TitleUpdater titleUpdater, Timing timing) {
mDbFrontend = dbFrontend;
mFilterNearestCaches = filterNearestCaches;
mCacheListData = cacheListData;
mLocationControlBuffered = locationControlBuffered;
mTiming = timing;
mTitleUpdater = titleUpdater;
}
public void refresh() {
final Location location = mLocationControlBuffered.getLocation();
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
// Log.d("GeoBeagle", "Location: " + location);
ArrayList<Geocache> geocaches =
mDbFrontend.loadCaches(latitude, longitude, mFilterNearestCaches.getWhereFactory());
mTiming.lap("SQL time");
mCacheListData.add(geocaches, mLocationControlBuffered);
mTiming.lap("add to list time");
final int sqlCount = geocaches.size();
final int nearestCachesCount = mCacheListData.size();
mTitleUpdater.update(sqlCount, nearestCachesCount);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.R;
public class ListTitleFormatter {
int getBodyText(int sqlCount) {
return sqlCount > 0 ? R.string.no_nearby_caches : R.string.no_caches;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector.LocationComparator;
import java.util.ArrayList;
import java.util.Collections;
public class DistanceSortStrategy implements SortStrategy {
private final LocationComparator mLocationComparator;
public DistanceSortStrategy(LocationComparator locationComparator) {
mLocationComparator = locationComparator;
}
public void sort(ArrayList<GeocacheVector> geocacheVectors) {
for (GeocacheVector geocacheVector : geocacheVectors) {
geocacheVector.setDistance(geocacheVector.getDistanceFast());
}
Collections.sort(geocacheVectors, mLocationComparator);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import com.google.code.geobeagle.database.FilterNearestCaches;
import android.app.ListActivity;
import android.widget.TextView;
public class TitleUpdater {
private final FilterNearestCaches mFilterNearestCaches;
private final ListActivity mListActivity;
private final ListTitleFormatter mListTitleFormatter;
private final CacheListDelegateDI.Timing mTiming;
public TitleUpdater(ListActivity listActivity, FilterNearestCaches filterNearestCaches,
ListTitleFormatter listTitleFormatter, CacheListDelegateDI.Timing timing) {
mListActivity = listActivity;
mFilterNearestCaches = filterNearestCaches;
mListTitleFormatter = listTitleFormatter;
mTiming = timing;
}
public void update(int sqlCount, int nearestCachesCount) {
mListActivity.setTitle(mListActivity.getString(mFilterNearestCaches.getTitleText(),
nearestCachesCount, sqlCount));
if (0 == nearestCachesCount) {
TextView textView = (TextView)mListActivity.findViewById(android.R.id.empty);
textView.setText(mListTitleFormatter.getBodyText(sqlCount));
}
mTiming.lap("update title time");
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
public class ActionAndTolerance {
private final RefreshAction mRefreshAction;
private final ToleranceStrategy mToleranceStrategy;
public ActionAndTolerance(RefreshAction refreshAction, ToleranceStrategy toleranceStrategy) {
mRefreshAction = refreshAction;
mToleranceStrategy = toleranceStrategy;
}
public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) {
return mToleranceStrategy.exceedsTolerance(here, azimuth, now);
}
public void refresh() {
mRefreshAction.refresh();
}
public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) {
mToleranceStrategy.updateLastRefreshed(here, azimuth, now);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class GeocacheListAdapter extends BaseAdapter {
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final GeocacheVectors mGeocacheVectors;
public GeocacheListAdapter(GeocacheVectors geocacheVectors,
GeocacheSummaryRowInflater geocacheSummaryRowInflater) {
mGeocacheVectors = geocacheVectors;
mGeocacheSummaryRowInflater = geocacheSummaryRowInflater;
}
public int getCount() {
return mGeocacheVectors.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = mGeocacheSummaryRowInflater.inflate(convertView);
mGeocacheSummaryRowInflater.setData(view, position);
return view;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
public class RelativeBearingFormatter implements BearingFormatter {
private static final String[] ARROWS = {
"^", ">", "v", "<",
};
public String formatBearing(float absBearing, float myHeading) {
return ARROWS[((((int)(absBearing - myHeading) + 45 + 720) % 360) / 90)];
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
public class LocationAndAzimuthTolerance implements ToleranceStrategy {
private float mLastAzimuth;
LocationTolerance mLocationTolerance;
public LocationAndAzimuthTolerance(LocationTolerance locationTolerance, float lastAzimuth) {
mLocationTolerance = locationTolerance;
mLastAzimuth = lastAzimuth;
}
public boolean exceedsTolerance(IGpsLocation here, float currentAzimuth, long now) {
if (mLastAzimuth != currentAzimuth) {
// Log.d("GeoBeagle", "new azimuth: " + currentAzimuth);
mLastAzimuth = currentAzimuth;
return true;
}
return mLocationTolerance.exceedsTolerance(here, currentAzimuth, now);
}
public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) {
mLocationTolerance.updateLastRefreshed(here, azimuth, now);
mLastAzimuth = azimuth;
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.view;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.presenter.AbsoluteBearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.HasDistanceFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class GeocacheSummaryRowInflater implements HasDistanceFormatter {
static class RowViews {
private final TextView mAttributes;
private final TextView mCacheName;
private final TextView mDistance;
private final ImageView mIcon;
private final TextView mId;
RowViews(TextView attributes, TextView cacheName, TextView distance, ImageView icon,
TextView id) {
mAttributes = attributes;
mCacheName = cacheName;
mDistance = distance;
mIcon = icon;
mId = id;
}
void set(GeocacheVector geocacheVector, DistanceFormatter distanceFormatter,
BearingFormatter relativeBearingFormatter) {
CacheType type = geocacheVector.getGeocache().getCacheType();
mIcon.setImageResource(type.icon());
mId.setText(geocacheVector.getId());
mAttributes.setText(geocacheVector.getFormattedAttributes());
mCacheName.setText(geocacheVector.getName());
mDistance.setText(geocacheVector.getFormattedDistance(distanceFormatter,
relativeBearingFormatter));
}
}
private BearingFormatter mBearingFormatter;
private DistanceFormatter mDistanceFormatter;
private final GeocacheVectors mGeocacheVectors;
private final LayoutInflater mLayoutInflater;
public GeocacheSummaryRowInflater(DistanceFormatter distanceFormatter,
GeocacheVectors geocacheVectors, LayoutInflater layoutInflater,
BearingFormatter relativeBearingFormatter) {
mLayoutInflater = layoutInflater;
mGeocacheVectors = geocacheVectors;
mDistanceFormatter = distanceFormatter;
mBearingFormatter = relativeBearingFormatter;
}
BearingFormatter getBearingFormatter() {
return mBearingFormatter;
}
public View inflate(View convertView) {
if (convertView != null)
return convertView;
//Log.d("GeoBeagle", "SummaryRow::inflate(" + convertView + ")");
View view = mLayoutInflater.inflate(R.layout.cache_row, null);
RowViews rowViews = new RowViews((TextView)view.findViewById(R.id.txt_gcattributes),
((TextView)view.findViewById(R.id.txt_cache)), ((TextView)view
.findViewById(R.id.distance)), ((ImageView)view
.findViewById(R.id.gc_row_icon)), ((TextView)view
.findViewById(R.id.txt_gcid)));
view.setTag(rowViews);
return view;
}
public void setBearingFormatter(boolean absoluteBearing) {
mBearingFormatter = absoluteBearing ? new AbsoluteBearingFormatter()
: new RelativeBearingFormatter();
}
public void setData(View view, int position) {
((RowViews)view.getTag()).set(mGeocacheVectors.get(position), mDistanceFormatter,
mBearingFormatter);
}
public void setDistanceFormatter(DistanceFormatter distanceFormatter) {
mDistanceFormatter = distanceFormatter;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextAction;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.database.FilterNearestCaches;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class GeocacheListController {
public static class CacheListOnCreateContextMenuListener implements OnCreateContextMenuListener {
private final GeocacheVectors mGeocacheVectors;
public CacheListOnCreateContextMenuListener(GeocacheVectors geocacheVectors) {
mGeocacheVectors = geocacheVectors;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo;
if (acmi.position > 0) {
menu.setHeaderTitle(mGeocacheVectors.get(acmi.position - 1).getId());
menu.add(0, MENU_VIEW, 0, "View");
menu.add(0, MENU_EDIT, 1, "Edit");
menu.add(0, MENU_DELETE, 2, "Delete");
}
}
}
static final int MENU_DELETE = 0;
static final int MENU_VIEW = 1;
static final int MENU_EDIT = 2;
public static final String SELECT_CACHE = "SELECT_CACHE";
private final CacheListRefresh mCacheListRefresh;
private final ContextAction mContextActions[];
private final FilterNearestCaches mFilterNearestCaches;
private final MenuActions mMenuActions;
private final MenuActionSyncGpx mMenuActionSyncGpx;
public GeocacheListController(CacheListRefresh cacheListRefresh,
ContextAction[] contextActions, FilterNearestCaches filterNearestCaches,
MenuActionSyncGpx menuActionSyncGpx, MenuActions menuActions) {
mCacheListRefresh = cacheListRefresh;
mContextActions = contextActions;
mFilterNearestCaches = filterNearestCaches;
mMenuActionSyncGpx = menuActionSyncGpx;
mMenuActions = menuActions;
}
public boolean onContextItemSelected(MenuItem menuItem) {
AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo)menuItem
.getMenuInfo();
mContextActions[menuItem.getItemId()].act(adapterContextMenuInfo.position - 1);
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public void onListItemClick(ListView l, View v, int position, long id) {
if (position > 0)
mContextActions[MENU_VIEW].act(position - 1);
else
mCacheListRefresh.forceRefresh();
}
public boolean onMenuOpened(int featureId, Menu menu) {
menu.findItem(R.string.menu_toggle_filter).setTitle(mFilterNearestCaches.getMenuString());
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
public void onPause() {
mMenuActionSyncGpx.abort();
}
public void onResume(CacheListRefresh cacheListRefresh, boolean fImport) {
mCacheListRefresh.forceRefresh();
if (fImport)
mMenuActionSyncGpx.act();
}
}
| Java |
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.location.CombinedLocationListener;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class SearchOnlineActivityDelegate {
private final ActivitySaver mActivitySaver;
private final CombinedLocationListener mCombinedLocationListener;
private final CombinedLocationManager mCombinedLocationManager;
private final CompassListener mCompassListener;
private final DistanceFormatterManager mDistanceFormatterManager;
private final LocationControlBuffered mLocationControlBuffered;
private final SensorManager mSensorManager;
private final WebView mWebView;
public SearchOnlineActivityDelegate(WebView webView, SensorManager sensorManager,
CompassListener compassListener, CombinedLocationManager combinedLocationManager,
CombinedLocationListener combinedLocationListener,
LocationControlBuffered locationControlBuffered,
DistanceFormatterManager distanceFormatterManager, ActivitySaver activitySaver) {
mSensorManager = sensorManager;
mCompassListener = compassListener;
mCombinedLocationListener = combinedLocationListener;
mCombinedLocationManager = combinedLocationManager;
mLocationControlBuffered = locationControlBuffered;
mWebView = webView;
mDistanceFormatterManager = distanceFormatterManager;
mActivitySaver = activitySaver;
}
public void configureWebView(JsInterface jsInterface) {
mWebView.loadUrl("file:///android_asset/search.html");
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setBackgroundColor(Color.BLACK);
mWebView.addJavascriptInterface(jsInterface, "gb");
}
public void onPause() {
mCombinedLocationManager.removeUpdates();
mSensorManager.unregisterListener(mCompassListener);
mActivitySaver.save(ActivityType.SEARCH_ONLINE);
}
public void onResume() {
mCombinedLocationManager.requestLocationUpdates(1000, 0, mLocationControlBuffered);
mCombinedLocationManager.requestLocationUpdates(1000, 0, mCombinedLocationListener);
mSensorManager.registerListener(mCompassListener, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
mDistanceFormatterManager.setFormatter();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.Refresher;
public class NullRefresher implements Refresher {
public void refresh() {
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.R;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import java.util.Locale;
class JsInterface {
private final LocationControlBuffered mLocationControlBuffered;
private final JsInterfaceHelper mHelper;
static class JsInterfaceHelper {
private final Activity mActivity;
public JsInterfaceHelper(Activity activity) {
mActivity = activity;
}
public void launch(String uri) {
mActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
}
public String getTemplate(int ix) {
return mActivity.getResources().getStringArray(R.array.nearest_objects)[ix];
}
public String getNS(double latitude) {
return latitude > 0 ? "N" : "S";
}
public String getEW(double longitude) {
return longitude > 0 ? "E" : "W";
}
}
public JsInterface(LocationControlBuffered locationControlBuffered,
JsInterfaceHelper jsInterfaceHelper) {
mHelper = jsInterfaceHelper;
mLocationControlBuffered = locationControlBuffered;
}
public int atlasQuestOrGroundspeak(int ix) {
final Location location = mLocationControlBuffered.getLocation();
final String uriTemplate = mHelper.getTemplate(ix);
mHelper.launch(String.format(Locale.US, uriTemplate, location.getLatitude(), location
.getLongitude()));
return 0;
}
public int openCaching(int ix) {
final Location location = mLocationControlBuffered.getLocation();
final String uriTemplate = mHelper.getTemplate(ix);
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
final String NS = mHelper.getNS(latitude);
final String EW = mHelper.getEW(longitude);
final double abs_latitude = Math.abs(latitude);
final double abs_longitude = Math.abs(longitude);
final int lat_h = (int)abs_latitude;
final double lat_m = 60 * (abs_latitude - lat_h);
final int lon_h = (int)abs_longitude;
final double lon_m = 60 * (abs_longitude - lon_h);
mHelper.launch(String.format(Locale.US, uriTemplate, NS, lat_h, lat_m, EW, lon_h, lon_m));
return 0;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
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;
}
public void run() {
mAlertDialogBuilder.create().show();
}
}
private final Activity mActivity;
private final OnClickListener mOnClickListener;
public ErrorDisplayer(Activity activity, OnClickListener 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.xmlimport;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import java.io.IOException;
class EventHandlerGpx implements EventHandler {
static final String XPATH_CACHE_CONTAINER = "/gpx/wpt/groundspeak:cache/groundspeak:container";
static final String XPATH_CACHE_DIFFICULTY = "/gpx/wpt/groundspeak:cache/groundspeak:difficulty";
static final String XPATH_CACHE_TERRAIN = "/gpx/wpt/groundspeak:cache/groundspeak:terrain";
static final String XPATH_CACHE_TYPE = "/gpx/wpt/groundspeak:cache/groundspeak:type";
static final String XPATH_GEOCACHE_CONTAINER = "/gpx/wpt/geocache/container";
static final String XPATH_GEOCACHE_DIFFICULTY = "/gpx/wpt/geocache/difficulty";
static final String XPATH_GEOCACHE_TERRAIN = "/gpx/wpt/geocache/terrain";
static final String XPATH_GEOCACHE_TYPE = "/gpx/wpt/geocache/type";
static final String XPATH_GEOCACHEHINT = "/gpx/wpt/geocache/hints";
static final String XPATH_GEOCACHELOGDATE = "/gpx/wpt/geocache/logs/log/time";
static final String XPATH_GEOCACHENAME = "/gpx/wpt/geocache/name";
static final String XPATH_GPXNAME = "/gpx/name";
static final String XPATH_GPXTIME = "/gpx/time";
static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name";
static final String XPATH_HINT = "/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints";
static final String XPATH_LOGDATE = "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date";
static final String[] XPATH_PLAINLINES = {
"/gpx/wpt/cmt", "/gpx/wpt/desc", "/gpx/wpt/groundspeak:cache/groundspeak:type",
"/gpx/wpt/groundspeak:cache/groundspeak:container",
"/gpx/wpt/groundspeak:cache/groundspeak:short_description",
"/gpx/wpt/groundspeak:cache/groundspeak:long_description",
"/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type",
"/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder",
"/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text",
/* here are the geocaching.com.au entries */
"/gpx/wpt/geocache/owner", "/gpx/wpt/geocache/type", "/gpx/wpt/geocache/summary",
"/gpx/wpt/geocache/description", "/gpx/wpt/geocache/logs/log/geocacher",
"/gpx/wpt/geocache/logs/log/type", "/gpx/wpt/geocache/logs/log/text"
};
static final String XPATH_SYM = "/gpx/wpt/sym";
static final String XPATH_WPT = "/gpx/wpt";
static final String XPATH_WPTDESC = "/gpx/wpt/desc";
static final String XPATH_WPTNAME = "/gpx/wpt/name";
static final String XPATH_WAYPOINT_TYPE = "/gpx/wpt/type";
private final CachePersisterFacade mCachePersisterFacade;
public EventHandlerGpx(CachePersisterFacade cachePersisterFacade) {
mCachePersisterFacade = cachePersisterFacade;
}
public void endTag(String previousFullPath) throws IOException {
if (previousFullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.endCache(Source.GPX);
}
}
public void startTag(String fullPath, XmlPullParserWrapper xmlPullParser) {
if (fullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.startCache();
mCachePersisterFacade.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser
.getAttributeValue(null, "lon"));
}
}
public boolean text(String fullPath, String text) throws IOException {
text = text.trim();
//Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text);
if (fullPath.equals(XPATH_WPTNAME)) {
mCachePersisterFacade.wptName(text);
} else if (fullPath.equals(XPATH_WPTDESC)) {
mCachePersisterFacade.wptDesc(text);
} else if (fullPath.equals(XPATH_GPXTIME)) {
return mCachePersisterFacade.gpxTime(text);
} else if (fullPath.equals(XPATH_GROUNDSPEAKNAME) || fullPath.equals(XPATH_GEOCACHENAME)) {
mCachePersisterFacade.groundspeakName(text);
} else if (fullPath.equals(XPATH_LOGDATE) || fullPath.equals(XPATH_GEOCACHELOGDATE)) {
mCachePersisterFacade.logDate(text);
} else if (fullPath.equals(XPATH_SYM)) {
mCachePersisterFacade.symbol(text);
} else if (fullPath.equals(XPATH_HINT) || fullPath.equals(XPATH_GEOCACHEHINT)) {
if (!text.equals("")) {
mCachePersisterFacade.hint(text);
}
} else if (fullPath.equals(XPATH_CACHE_TYPE) || fullPath.equals(XPATH_GEOCACHE_TYPE)
|| fullPath.equals(XPATH_WAYPOINT_TYPE)) {
//Log.d("GeoBeagle", "Setting cache type " + text);
mCachePersisterFacade.cacheType(text);
} else if (fullPath.equals(XPATH_CACHE_DIFFICULTY)
|| fullPath.equals(XPATH_GEOCACHE_DIFFICULTY)) {
mCachePersisterFacade.difficulty(text);
} else if (fullPath.equals(XPATH_CACHE_TERRAIN) || fullPath.equals(XPATH_GEOCACHE_TERRAIN)) {
mCachePersisterFacade.terrain(text);
} else if (fullPath.equals(XPATH_CACHE_CONTAINER)
|| fullPath.equals(XPATH_GEOCACHE_CONTAINER)) {
mCachePersisterFacade.container(text);
}
for (String writeLineMatch : XPATH_PLAINLINES) {
if (fullPath.equals(writeLineMatch)) {
mCachePersisterFacade.line(text);
return true;
}
}
return true;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx.gpx;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter;
public class GpxFileOpener {
public class GpxFileIter implements IGpxReaderIter {
public boolean hasNext() {
if (mAborter.isAborted())
return false;
return mFilename != null;
}
public IGpxReader next() {
final IGpxReader gpxReader = new GpxReader(mFilename);
mFilename = null;
return gpxReader;
}
}
private Aborter mAborter;
private String mFilename;
public GpxFileOpener(String filename, Aborter aborter) {
mFilename = filename;
mAborter = aborter;
}
public GpxFileIter iterator() {
return new GpxFileIter();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx.gpx;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
public GpxReader(String filename) {
mFilename = filename;
}
public String getFilename() {
return mFilename;
}
public Reader open() throws FileNotFoundException {
return new BufferedReader(new FileReader(mFilename));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx;
import java.io.IOException;
public interface IGpxReaderIter {
public boolean hasNext() throws IOException;
public IGpxReader next() throws IOException;
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.gpx.gpx.GpxFileOpener;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester;
import java.io.IOException;
/**
* @author sng Takes a filename and returns an IGpxReaderIter based on the
* extension: zip: ZipFileIter gpx/loc: GpxFileIter
*/
public class GpxFileIterAndZipFileIterFactory {
private final Aborter mAborter;
private final ZipInputFileTester mZipInputFileTester;
public GpxFileIterAndZipFileIterFactory(ZipInputFileTester zipInputFileTester, Aborter aborter) {
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
public IGpxReaderIter fromFile(String filename) throws IOException {
if (filename.endsWith(".zip")) {
return new ZipFileOpener(GpxAndZipFiles.GPX_DIR + filename,
new ZipInputStreamFactory(), mZipInputFileTester, mAborter).iterator();
}
return new GpxFileOpener(GpxAndZipFiles.GPX_DIR + filename, mAborter).iterator();
}
public void resetAborter() {
mAborter.reset();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class GpxAndZipFiles {
public static class GpxAndZipFilenameFilter implements FilenameFilter {
private final GpxFilenameFilter mGpxFilenameFilter;
public GpxAndZipFilenameFilter(GpxFilenameFilter gpxFilenameFilter) {
mGpxFilenameFilter = gpxFilenameFilter;
}
public boolean accept(File dir, String name) {
name = name.toLowerCase();
if (!name.startsWith(".") && name.endsWith(".zip"))
return true;
return mGpxFilenameFilter.accept(name);
}
}
public static class GpxFilenameFilter {
public boolean accept(String name) {
name = name.toLowerCase();
return !name.startsWith(".") && (name.endsWith(".gpx") || name.endsWith(".loc"));
}
}
public static class GpxFilesAndZipFilesIter {
private final String[] mFileList;
private final GpxFileIterAndZipFileIterFactory mGpxAndZipFileIterFactory;
private int mIxFileList;
private IGpxReaderIter mSubIter;
GpxFilesAndZipFilesIter(String[] fileList,
GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) {
mFileList = fileList;
mGpxAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory;
mIxFileList = 0;
}
public boolean hasNext() throws IOException {
// Iterate through actual zip and gpx files on the filesystem.
if (mSubIter != null && mSubIter.hasNext())
return true;
while (mIxFileList < mFileList.length) {
mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]);
if (mSubIter.hasNext())
return true;
}
return false;
}
public IGpxReader next() throws IOException {
return mSubIter.next();
}
}
public static final String GPX_DIR = "/sdcard/download/";
private final FilenameFilter mFilenameFilter;
private final GpxFileIterAndZipFileIterFactory mGpxFileIterAndZipFileIterFactory;
public GpxAndZipFiles(FilenameFilter filenameFilter,
GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) {
mFilenameFilter = filenameFilter;
mGpxFileIterAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory;
}
public GpxFilesAndZipFilesIter iterator() {
String[] fileList = new File(GPX_DIR).list(mFilenameFilter);
if (fileList == null)
return null;
mGpxFileIterAndZipFileIterFactory.resetAborter();
return new GpxFilesAndZipFilesIter(fileList, mGpxFileIterAndZipFileIterFactory);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx;
import java.io.FileNotFoundException;
import java.io.Reader;
public interface IGpxReader {
String getFilename();
Reader open() throws FileNotFoundException;
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx.zip;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GpxZipInputStream {
private ZipEntry mNextEntry;
private final ZipInputStream mZipInputStream;
public GpxZipInputStream(ZipInputStream zipInputStream) {
mZipInputStream = zipInputStream;
}
ZipEntry getNextEntry() throws IOException {
mNextEntry = mZipInputStream.getNextEntry();
return mNextEntry;
}
InputStream getStream() {
return mZipInputStream;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx.zip;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
private final Reader mReader;
GpxReader(String filename, Reader reader) {
mFilename = filename;
mReader = reader;
}
public String getFilename() {
return mFilename;
}
public Reader open() {
return mReader;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx.zip;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
public class ZipFileOpener {
public static class ZipFileIter implements IGpxReaderIter {
private final Aborter mAborter;
private ZipEntry mNextZipEntry;
private final ZipInputFileTester mZipInputFileTester;
private final GpxZipInputStream mZipInputStream;
ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter,
ZipInputFileTester zipInputFileTester, ZipEntry nextZipEntry) {
mZipInputStream = zipInputStream;
mNextZipEntry = nextZipEntry;
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter,
ZipInputFileTester zipInputFileTester) {
mZipInputStream = zipInputStream;
mNextZipEntry = null;
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
public boolean hasNext() throws IOException {
// Iterate through zip file entries.
if (mNextZipEntry == null) {
do {
if (mAborter.isAborted())
break;
mNextZipEntry = mZipInputStream.getNextEntry();
} while (mNextZipEntry != null && !mZipInputFileTester.isValid(mNextZipEntry));
}
return mNextZipEntry != null;
}
public IGpxReader next() throws IOException {
final String name = mNextZipEntry.getName();
mNextZipEntry = null;
return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream()));
}
}
public static class ZipInputFileTester {
private final GpxFilenameFilter mGpxFilenameFilter;
public ZipInputFileTester(GpxFilenameFilter gpxFilenameFilter) {
mGpxFilenameFilter = gpxFilenameFilter;
}
public boolean isValid(ZipEntry zipEntry) {
return (!zipEntry.isDirectory() && mGpxFilenameFilter.accept(zipEntry.getName()));
}
}
private final Aborter mAborter;
private final String mFilename;
private final ZipInputFileTester mZipInputFileTester;
private final ZipInputStreamFactory mZipInputStreamFactory;
public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory,
ZipInputFileTester zipInputFileTester, Aborter aborter) {
mFilename = filename;
mZipInputStreamFactory = zipInputStreamFactory;
mAborter = aborter;
mZipInputFileTester = zipInputFileTester;
}
public ZipFileIter iterator() throws IOException {
return new ZipFileIter(mZipInputStreamFactory.create(mFilename), mAborter,
mZipInputFileTester);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException;
import org.xmlpull.v1.XmlPullParserException;
import android.database.sqlite.SQLiteException;
import android.os.PowerManager.WakeLock;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
public class GpxLoader {
private final CachePersisterFacade mCachePersisterFacade;
private final ErrorDisplayer mErrorDisplayer;
private final GpxToCache mGpxToCache;
private final WakeLock mWakeLock;
public static final int WAKELOCK_DURATION = 15000;
GpxLoader(CachePersisterFacade cachePersisterFacade, ErrorDisplayer errorDisplayer,
GpxToCache gpxToCache, WakeLock wakeLock) {
mGpxToCache = gpxToCache;
mCachePersisterFacade = cachePersisterFacade;
mErrorDisplayer = errorDisplayer;
mWakeLock = wakeLock;
}
public void abort() {
mGpxToCache.abort();
}
public void end() {
mCachePersisterFacade.end();
}
/**
* @return true if we should continue loading more files, false if we should
* terminate.
*/
public boolean load(EventHelper eventHelper) {
boolean markLoadAsComplete = false;
boolean continueLoading = false;
try {
mWakeLock.acquire(WAKELOCK_DURATION);
boolean alreadyLoaded = mGpxToCache.load(eventHelper);
markLoadAsComplete = !alreadyLoaded;
continueLoading = true;
} catch (final SQLiteException e) {
mErrorDisplayer.displayError(R.string.error_writing_cache, mGpxToCache.getSource()
+ ": " + e.getMessage());
} catch (XmlPullParserException e) {
mErrorDisplayer.displayError(R.string.error_parsing_file, mGpxToCache.getSource()
+ ": " + e.getMessage());
} catch (FileNotFoundException e) {
mErrorDisplayer.displayError(R.string.file_not_found, mGpxToCache.getSource() + ": "
+ e.getMessage());
} catch (IOException e) {
mErrorDisplayer.displayError(R.string.error_reading_file, mGpxToCache.getSource()
+ ": " + e.getMessage());
} catch (CancelException e) {
}
mCachePersisterFacade.close(markLoadAsComplete);
return continueLoading;
}
public void open(String path, Reader reader) throws XmlPullParserException {
mGpxToCache.open(path, reader);
mCachePersisterFacade.open(path);
}
public void start() {
mCachePersisterFacade.start();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.actions.menu.Abortable;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.ImportThreadWrapper;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.ToastFactory;
import android.app.ListActivity;
import android.widget.Toast;
public class GpxImporter implements Abortable {
private final ErrorDisplayer mErrorDisplayer;
private final EventHandlers mEventHandlers;
private final GpxLoader mGpxLoader;
private final ImportThreadWrapper mImportThreadWrapper;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final ToastFactory mToastFactory;
private final GeocacheListPresenter mGeocacheListPresenter;
GpxImporter(GeocacheListPresenter geocacheListPresenter, GpxLoader gpxLoader,
ListActivity listActivity, ImportThreadWrapper importThreadWrapper,
MessageHandler messageHandler, ToastFactory toastFactory, EventHandlers eventHandlers,
ErrorDisplayer errorDisplayer) {
mListActivity = listActivity;
mGpxLoader = gpxLoader;
mEventHandlers = eventHandlers;
mImportThreadWrapper = importThreadWrapper;
mMessageHandler = messageHandler;
mErrorDisplayer = errorDisplayer;
mToastFactory = toastFactory;
mGeocacheListPresenter = geocacheListPresenter;
}
public void abort() {
mMessageHandler.abortLoad();
mGpxLoader.abort();
if (mImportThreadWrapper.isAlive()) {
mImportThreadWrapper.join();
mToastFactory.showToast(mListActivity, R.string.import_canceled, Toast.LENGTH_SHORT);
}
}
public void importGpxs(CacheListRefresh cacheListRefresh) {
mGeocacheListPresenter.onPause();
mImportThreadWrapper.open(cacheListRefresh, mGpxLoader, mEventHandlers, mErrorDisplayer);
mImportThreadWrapper.start();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.cachedetails.CacheDetailsWriter;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.FileFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import android.os.PowerManager.WakeLock;
import java.io.File;
import java.io.IOException;
public class CachePersisterFacade {
private final CacheDetailsWriter mCacheDetailsWriter;
private String mCacheName = "";
private final CacheTagSqlWriter mCacheTagWriter;
private final FileFactory mFileFactory;
private final MessageHandler mMessageHandler;
private final WakeLock mWakeLock;
CachePersisterFacade(CacheTagSqlWriter cacheTagSqlWriter, FileFactory fileFactory,
CacheDetailsWriter cacheDetailsWriter, MessageHandler messageHandler, WakeLock wakeLock) {
mCacheDetailsWriter = cacheDetailsWriter;
mCacheTagWriter = cacheTagSqlWriter;
mFileFactory = fileFactory;
mMessageHandler = messageHandler;
mWakeLock = wakeLock;
}
void cacheType(String text) {
mCacheTagWriter.cacheType(text);
}
void close(boolean success) {
mCacheTagWriter.stopWriting(success);
}
void container(String text) {
mCacheTagWriter.container(text);
}
void difficulty(String text) {
mCacheTagWriter.difficulty(text);
}
void end() {
mCacheTagWriter.end();
}
void endCache(Source source) throws IOException {
mMessageHandler.updateName(mCacheName);
mCacheDetailsWriter.close();
mCacheTagWriter.write(source);
}
boolean gpxTime(String gpxTime) {
return mCacheTagWriter.gpxTime(gpxTime);
}
void groundspeakName(String text) {
mCacheTagWriter.cacheName(text);
}
void hint(String text) throws IOException {
mCacheDetailsWriter.writeHint(text);
}
void line(String text) throws IOException {
mCacheDetailsWriter.writeLine(text);
}
void logDate(String text) throws IOException {
mCacheDetailsWriter.writeLogDate(text);
}
void open(String path) {
mMessageHandler.updateSource(path);
mCacheTagWriter.startWriting();
mCacheTagWriter.gpxName(path);
}
void start() {
File file = mFileFactory.createFile(CacheDetailsWriter.GEOBEAGLE_DIR);
file.mkdirs();
}
void startCache() {
mCacheName = "";
mCacheTagWriter.clear();
}
void symbol(String text) {
mCacheTagWriter.symbol(text);
}
void terrain(String text) {
mCacheTagWriter.terrain(text);
}
void wpt(String latitude, String longitude) {
mCacheTagWriter.latitudeLongitude(latitude, longitude);
mCacheDetailsWriter.latitudeLongitude(latitude, longitude);
}
void wptDesc(String cacheName) {
mCacheName = cacheName;
mCacheTagWriter.cacheName(cacheName);
}
void wptName(String wpt) throws IOException {
mCacheDetailsWriter.open(wpt);
mCacheDetailsWriter.writeWptName(wpt);
mCacheTagWriter.id(wpt);
mMessageHandler.updateWaypointId(wpt);
mWakeLock.acquire(GpxLoader.WAKELOCK_DURATION);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import org.xmlpull.v1.XmlPullParser;
import java.io.IOException;
public class EventHelper {
public static class XmlPathBuilder {
private String mPath = "";
public void endTag(String currentTag) {
mPath = mPath.substring(0, mPath.length() - (currentTag.length() + 1));
}
public String getPath() {
return mPath;
}
public void startTag(String mCurrentTag) {
mPath += "/" + mCurrentTag;
}
}
private final EventHandler mEventHandler;
private final XmlPathBuilder mXmlPathBuilder;
private final XmlPullParserWrapper mXmlPullParser;
EventHelper(XmlPathBuilder xmlPathBuilder, EventHandler eventHandler,
XmlPullParserWrapper xmlPullParser) {
mXmlPathBuilder = xmlPathBuilder;
mXmlPullParser = xmlPullParser;
mEventHandler = eventHandler;
}
public boolean handleEvent(int eventType) throws IOException {
switch (eventType) {
case XmlPullParser.START_TAG:
mXmlPathBuilder.startTag(mXmlPullParser.getName());
mEventHandler.startTag(mXmlPathBuilder.getPath(), mXmlPullParser);
break;
case XmlPullParser.END_TAG:
mEventHandler.endTag(mXmlPathBuilder.getPath());
mXmlPathBuilder.endTag(mXmlPullParser.getName());
break;
case XmlPullParser.TEXT:
return mEventHandler.text(mXmlPathBuilder.getPath(), mXmlPullParser.getText());
}
return true;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import java.io.IOException;
interface EventHandler {
void endTag(String previousFullPath) throws IOException;
void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException;
boolean text(String mFullPath, String text) throws IOException;
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
public class GpxToCache {
public static class Aborter {
private static boolean mAborted = false;
public Aborter() {
mAborted = false;
}
public void abort() {
mAborted = true;
}
public boolean isAborted() {
return mAborted;
}
public void reset() {
mAborted = false;
}
}
@SuppressWarnings("serial")
public static class CancelException extends Exception {
}
private final Aborter mAborter;
private final XmlPullParserWrapper mXmlPullParserWrapper;
GpxToCache(XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) {
mXmlPullParserWrapper = xmlPullParserWrapper;
mAborter = aborter;
}
public void abort() {
mAborter.abort();
}
public String getSource() {
return mXmlPullParserWrapper.getSource();
}
/**
* @param eventHelper
* @return false if this file has already been loaded.
* @throws XmlPullParserException
* @throws IOException
* @throws CancelException
*/
public boolean load(EventHelper eventHelper) throws XmlPullParserException, IOException,
CancelException {
int eventType;
for (eventType = mXmlPullParserWrapper.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = mXmlPullParserWrapper
.next()) {
if (mAborter.isAborted())
throw new CancelException();
// File already loaded.
if (!eventHelper.handleEvent(eventType))
return true;
}
// Pick up END_DOCUMENT event as well.
eventHelper.handleEvent(eventType);
return false;
}
public void open(String source, Reader reader) throws XmlPullParserException {
mXmlPullParserWrapper.open(source, reader);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.xmlimport.gpx.IGpxReader;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilesAndZipFilesIter;
import org.xmlpull.v1.XmlPullParserException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ImportThreadDelegate {
public static class ImportThreadHelper {
private final ErrorDisplayer mErrorDisplayer;
private final EventHandlers mEventHandlers;
private final EventHelperFactory mEventHelperFactory;
private final GpxLoader mGpxLoader;
private boolean mHasFiles;
private final MessageHandler mMessageHandler;
public ImportThreadHelper(GpxLoader gpxLoader, MessageHandler messageHandler,
EventHelperFactory eventHelperFactory, EventHandlers eventHandlers,
ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mGpxLoader = gpxLoader;
mMessageHandler = messageHandler;
mEventHelperFactory = eventHelperFactory;
mEventHandlers = eventHandlers;
mHasFiles = false;
}
public void cleanup() {
mMessageHandler.loadComplete();
}
public void end() {
mGpxLoader.end();
if (!mHasFiles)
mErrorDisplayer.displayError(R.string.error_no_gpx_files);
}
public boolean processFile(IGpxReader gpxReader) throws XmlPullParserException, IOException {
String filename = gpxReader.getFilename();
mHasFiles = true;
mGpxLoader.open(filename, gpxReader.open());
return mGpxLoader.load(mEventHelperFactory.create(mEventHandlers.get(filename)));
}
public void start() {
mGpxLoader.start();
}
}
private final ErrorDisplayer mErrorDisplayer;
private final GpxAndZipFiles mGpxAndZipFiles;
private final ImportThreadHelper mImportThreadHelper;
public ImportThreadDelegate(GpxAndZipFiles gpxAndZipFiles,
ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) {
mGpxAndZipFiles = gpxAndZipFiles;
mImportThreadHelper = importThreadHelper;
mErrorDisplayer = errorDisplayer;
}
public void run() {
try {
tryRun();
} catch (final FileNotFoundException e) {
mErrorDisplayer.displayError(R.string.error_opening_file, e.getMessage());
} catch (IOException e) {
mErrorDisplayer.displayError(R.string.error_reading_file, e.getMessage());
} catch (XmlPullParserException e) {
mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage());
} finally {
mImportThreadHelper.cleanup();
}
}
protected void tryRun() throws IOException, XmlPullParserException {
GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = mGpxAndZipFiles.iterator();
if (gpxFilesAndZipFilesIter == null) {
mErrorDisplayer.displayError(R.string.error_cant_read_sd);
return;
}
mImportThreadHelper.start();
while (gpxFilesAndZipFilesIter.hasNext()) {
if (!mImportThreadHelper.processFile(gpxFilesAndZipFilesIter.next()))
return;
}
mImportThreadHelper.end();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import java.io.IOException;
class EventHandlerLoc implements EventHandler {
static final String XPATH_COORD = "/loc/waypoint/coord";
static final String XPATH_GROUNDSPEAKNAME = "/loc/waypoint/name";
static final String XPATH_LOC = "/loc";
static final String XPATH_WPT = "/loc/waypoint";
static final String XPATH_WPTNAME = "/loc/waypoint/name";
private final CachePersisterFacade mCachePersisterFacade;
EventHandlerLoc(CachePersisterFacade cachePersisterFacade) {
mCachePersisterFacade = cachePersisterFacade;
}
public void endTag(String previousFullPath) throws IOException {
if (previousFullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.endCache(Source.LOC);
}
}
public void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException {
if (mFullPath.equals(XPATH_COORD)) {
mCachePersisterFacade.wpt(mXmlPullParser.getAttributeValue(null, "lat"), mXmlPullParser
.getAttributeValue(null, "lon"));
} else if (mFullPath.equals(XPATH_WPTNAME)) {
mCachePersisterFacade.startCache();
mCachePersisterFacade.wptName(mXmlPullParser.getAttributeValue(null, "id"));
}
}
public boolean text(String mFullPath, String text) throws IOException {
if (mFullPath.equals(XPATH_WPTNAME))
mCachePersisterFacade.groundspeakName(text.trim());
return true;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.database.CacheWriter;
/**
* @author sng
*/
public class CacheTagSqlWriter {
private final CacheTypeFactory mCacheTypeFactory;
private CacheType mCacheType;
private final CacheWriter mCacheWriter;
private int mContainer;
private int mDifficulty;
private boolean mFound;
private String mGpxName;
private CharSequence mId;
private double mLatitude;
private double mLongitude;
private CharSequence mName;
private String mSqlDate;
private int mTerrain;
public CacheTagSqlWriter(CacheWriter cacheWriter,
CacheTypeFactory cacheTypeFactory) {
mCacheWriter = cacheWriter;
mCacheTypeFactory = cacheTypeFactory;
}
public void cacheName(String name) {
mName = name;
}
public void cacheType(String type) {
mCacheType = mCacheTypeFactory.fromTag(type);
}
public void clear() { // TODO: ensure source is not reset
mId = mName = null;
mLatitude = mLongitude = 0;
mFound = false;
mCacheType = CacheType.NULL;
mDifficulty = 0;
mTerrain = 0;
}
public void container(String container) {
mContainer = mCacheTypeFactory.container(container);
}
public void difficulty(String difficulty) {
mDifficulty = mCacheTypeFactory.stars(difficulty);
}
public void end() {
mCacheWriter.clearEarlierLoads();
}
public void gpxName(String gpxName) {
mGpxName = gpxName;
}
/**
* @param gpxTime
* @return true if we should load this gpx; false if the gpx is already
* loaded.
*/
public boolean gpxTime(String gpxTime) {
mSqlDate = isoTimeToSql(gpxTime);
if (mCacheWriter.isGpxAlreadyLoaded(mGpxName, mSqlDate)) {
return false;
}
mCacheWriter.clearCaches(mGpxName);
return true;
}
public void id(CharSequence id) {
mId = id;
}
public String isoTimeToSql(String gpxTime) {
return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19);
}
public void latitudeLongitude(String latitude, String longitude) {
mLatitude = Double.parseDouble(latitude);
mLongitude = Double.parseDouble(longitude);
}
public void startWriting() {
mSqlDate = "2000-01-01T12:00:00";
mCacheWriter.startWriting();
}
public void stopWriting(boolean successfulGpxImport) {
mCacheWriter.stopWriting();
if (successfulGpxImport)
mCacheWriter.writeGpx(mGpxName, mSqlDate);
}
public void symbol(String symbol) {
mFound = symbol.equals("Geocache Found");
}
public void terrain(String terrain) {
mTerrain = mCacheTypeFactory.stars(terrain);
}
public void write(Source source) {
if (!mFound)
mCacheWriter.insertAndUpdateCache(mId, mName, mLatitude, mLongitude, source, mGpxName,
mCacheType, mDifficulty, mTerrain, mContainer);
}
}
| Java |
package com.google.code.geobeagle.xmlimport;
import java.util.HashMap;
public class EventHandlers {
private final HashMap<String, EventHandler> mEventHandlers = new HashMap<String, EventHandler>();
public void add(String extension, EventHandler eventHandler) {
mEventHandlers.put(extension.toLowerCase(), eventHandler);
}
public EventHandler get(String filename) {
int len = filename.length();
String extension = filename.substring(Math.max(0, len - 4), len);
return mEventHandlers.get(extension.toLowerCase());
}
}
| 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 interface Refresher {
public void refresh();
}
| 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 abstract class MenuActionBase implements MenuAction {
private final int mId;
public MenuActionBase(int id) {
mId = id;
}
@Override
public int getId() {
return mId;
}
}
| 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.R;
import com.google.code.geobeagle.activity.searchonline.SearchOnlineActivity;
import android.app.Activity;
import android.content.Intent;
public class MenuActionSearchOnline extends MenuActionBase {
private final Activity mActivity;
public MenuActionSearchOnline(Activity activity) {
super(R.string.menu_search_online);
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, SearchOnlineActivity.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.R;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import android.app.Activity;
import android.content.Intent;
public class MenuActionCacheList extends MenuActionBase {
private Activity mActivity;
public MenuActionCacheList(Activity activity) {
super(R.string.menu_cache_list);
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, CacheListActivity.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.R;
import com.google.code.geobeagle.activity.preferences.EditPreferences;
import android.app.Activity;
import android.content.Intent;
public class MenuActionSettings extends MenuActionBase {
private final Activity mActivity;
public MenuActionSettings(Activity activity) {
super(R.string.menu_settings);
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;
public interface MenuAction {
public void act();
/** Must be the id of a resource string - used to set label */
public int getId();
}
| 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.R;
import com.google.code.geobeagle.activity.EditCacheActivity;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Intent;
public class MenuActionEditGeocache extends MenuActionBase {
private final GeoBeagle mParent;
public MenuActionEditGeocache(GeoBeagle parent) {
super(R.string.menu_edit_geocache);
mParent = parent;
}
@Override
public void act() {
final Intent intent = new Intent(mParent, EditCacheActivity.class);
intent.putExtra("geocache", mParent.getGeocache());
mParent.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 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.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.gpsstatuswidget;
import com.google.code.geobeagle.Time;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.location.Location;
import android.widget.TextView;
import java.util.Formatter;
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);
}
public Lag getLag() {
return mLagImpl;
}
}
static class LastKnownLocationUnavailable implements LastLocation {
private final Lag mLagNull;
public LastKnownLocationUnavailable(LagNull lagNull) {
mLagNull = lagNull;
}
public Lag getLag() {
return mLagNull;
}
}
static interface LastLocation {
Lag getLag();
}
static class LastLocationUnknown implements LastLocation {
private final CombinedLocationManager mCombinedLocationManager;
private final LastKnownLocationUnavailable mLastKnownLocationUnavailable;
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;
TextLagUpdater(LastLocationUnknown lastLocationUnknown, TextView textLag, Time time) {
mLastLocation = lastLocationUnknown;
mTextLag = textLag;
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.formatting.DistanceFormatter;
import android.widget.TextView;
class Meter {
private float mAccuracy;
private final TextView mAccuracyView;
private float mAzimuth;
private final MeterBars mMeterView;
Meter(MeterBars meterBars, TextView accuracyView) {
mAccuracyView = accuracyView;
mMeterView = meterBars;
}
void setAccuracy(float accuracy, DistanceFormatter distanceFormatter) {
mAccuracy = accuracy;
distanceFormatter.formatDistance(accuracy);
mAccuracyView.setText(distanceFormatter.formatDistance(accuracy));
mMeterView.set(accuracy, mAzimuth);
}
void setAzimuth(float azimuth) {
mAzimuth = azimuth;
mMeterView.set(mAccuracy, 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.Time;
import android.view.View;
class MeterFader {
private long mLastUpdateTime;
private final MeterBars mMeterView;
private final View mParent;
private final Time mTime;
MeterFader(View parent, MeterBars meterBars, Time time) {
mLastUpdateTime = -1;
mMeterView = meterBars;
mParent = parent;
mTime = time;
}
void paint() {
final long currentTime = mTime.getCurrentTime();
if (mLastUpdateTime == -1)
mLastUpdateTime = currentTime;
long lastUpdateLag = currentTime - mLastUpdateTime;
mMeterView.setLag(lastUpdateLag);
if (lastUpdateLag < 1000)
mParent.postInvalidateDelayed(100);
// Log.d("GeoBeagle", "painting " + lastUpdateLag);
}
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;
/*
* Displays the accuracy (graphically) and azimuth of the gps.
*/
import android.graphics.Color;
import android.widget.TextView;
class MeterBars {
private final TextView mBarsAndAzimuth;
private final MeterFormatter mMeterFormatter;
MeterBars(TextView textView, MeterFormatter meterFormatter) {
mBarsAndAzimuth = textView;
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.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.presenter.HasDistanceFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.location.CombinedLocationManager;
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 HasDistanceFormatter, LocationListener {
private final CombinedLocationManager mCombinedLocationManager;
private DistanceFormatter mDistanceFormatter;
private final MeterFader mMeterFader;
private final Meter mMeterWrapper;
private final TextView mProvider;
private final Context mContext;
private final TextView mStatus;
private final TextLagUpdater mTextLagUpdater;
public GpsStatusWidgetDelegate(CombinedLocationManager combinedLocationManager,
DistanceFormatter distanceFormatter, Meter meter, MeterFader meterFader,
TextView provider, Context context, TextView status, TextLagUpdater textLagUpdater) {
mCombinedLocationManager = combinedLocationManager;
mDistanceFormatter = distanceFormatter;
mMeterFader = meterFader;
mMeterWrapper = meter;
mProvider = provider;
mContext = context;
mStatus = status;
mTextLagUpdater = textLagUpdater;
}
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "GpsStatusWidget onLocationChanged " + location);
if (location == null)
return;
if (!mCombinedLocationManager.isProviderEnabled()) {
mMeterWrapper.setDisabled();
mTextLagUpdater.setDisabled();
return;
}
mProvider.setText(location.getProvider());
mMeterWrapper.setAccuracy(location.getAccuracy(), mDistanceFormatter);
mMeterFader.reset();
mTextLagUpdater.reset(location.getTime());
}
public void onProviderDisabled(String provider) {
mStatus.setText(provider + " DISABLED");
}
public void onProviderEnabled(String provider) {
mStatus.setText(provider + " ENABLED");
}
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();
}
public void setDistanceFormatter(DistanceFormatter distanceFormatter) {
mDistanceFormatter = distanceFormatter;
}
}
| 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 android.os.Handler;
public class UpdateGpsWidgetRunnable implements Runnable {
private final Handler mHandler;
private final LocationControlBuffered mLocationControlBuffered;
private final Meter mMeterWrapper;
private final TextLagUpdater mTextLagUpdater;
UpdateGpsWidgetRunnable(Handler handler, LocationControlBuffered locationControlBuffered,
Meter meter, TextLagUpdater textLagUpdater) {
mMeterWrapper = meter;
mLocationControlBuffered = locationControlBuffered;
mTextLagUpdater = textLagUpdater;
mHandler = handler;
}
public void run() {
// Update the lag time and the orientation.
mTextLagUpdater.updateTextLag();
mMeterWrapper.setAzimuth(mLocationControlBuffered.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.code.geobeagle.R;
import android.content.Context;
class MeterFormatter {
private static String mMeterLeft;
private static String mMeterRight;
private static String mDegreesSymbol;
private static StringBuilder mStringBuilder;
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;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceSortStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.NullSortStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.SortStrategy;
import com.google.code.geobeagle.location.LocationControl;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public class LocationControlBuffered implements LocationListener {
public static class GpsDisabledLocation implements IGpsLocation {
public float distanceTo(IGpsLocation dest) {
return Float.MAX_VALUE;
}
public float distanceToGpsDisabledLocation(GpsDisabledLocation gpsLocation) {
return Float.MAX_VALUE;
}
public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) {
return Float.MAX_VALUE;
}
}
public static class GpsEnabledLocation implements IGpsLocation {
private final float mLatitude;
private final float mLongitude;
public GpsEnabledLocation(float latitude, float longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
public float distanceTo(IGpsLocation gpsLocation) {
return gpsLocation.distanceToGpsEnabledLocation(this);
}
public float distanceToGpsDisabledLocation(GpsDisabledLocation gpsLocation) {
return Float.MAX_VALUE;
}
public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) {
final float calculateDistanceFast = GeocacheVector.calculateDistanceFast(mLatitude,
mLongitude, gpsEnabledLocation.mLatitude, gpsEnabledLocation.mLongitude);
return calculateDistanceFast;
}
}
public static interface IGpsLocation {
public float distanceTo(IGpsLocation dest);
float distanceToGpsDisabledLocation(GpsDisabledLocation gpsLocation);
float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation);
}
private final DistanceSortStrategy mDistanceSortStrategy;
private GpsDisabledLocation mGpsDisabledLocation;
private IGpsLocation mGpsLocation;
private Location mLocation;
private LocationControl mLocationControl;
private final NullSortStrategy mNullSortStrategy;
private float mAzimuth;
public LocationControlBuffered(LocationControl locationControl,
DistanceSortStrategy distanceSortStrategy, NullSortStrategy nullSortStrategy,
GpsDisabledLocation gpsDisabledLocation, IGpsLocation lastGpsLocation,
Location lastLocation) {
mLocationControl = locationControl;
mDistanceSortStrategy = distanceSortStrategy;
mNullSortStrategy = nullSortStrategy;
mGpsDisabledLocation = gpsDisabledLocation;
mGpsLocation = lastGpsLocation;
mLocation = lastLocation;
}
public IGpsLocation getGpsLocation() {
return mGpsLocation;
}
public Location getLocation() {
return mLocation;
}
public SortStrategy getSortStrategy() {
if (mLocation == null)
return mNullSortStrategy;
return mDistanceSortStrategy;
}
public void onLocationChanged(Location location) {
mLocation = mLocationControl.getLocation();
if (location == null) {
mGpsLocation = mGpsDisabledLocation;
} else {
mGpsLocation = new GpsEnabledLocation((float)location.getLatitude(), (float)location
.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void setAzimuth(float azimuth) {
mAzimuth = azimuth;
}
public float getAzimuth() {
return mAzimuth;
}
}
| 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));
return mGeocacheFactory.create(mCursor.getString(2), mCursor.getString(3), mCursor
.getDouble(0), mCursor.getDouble(1), mDbToGeocacheAdapter
.sourceNameToSourceType(sourceName), sourceName, cacheType, difficulty, terrain,
container);
}
public int count() {
return mCursor.getCount();
}
public boolean moveToNext() {
return mCursor.moveToNext();
}
}
| Java |
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 android.database.Cursor;
public interface ISQLiteDatabase {
void beginTransaction();
void close();
int countResults(String table, String sql, String... args);
void endTransaction();
void execSQL(String s, Object... bindArg1);
Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs);
Cursor rawQuery(String string, String[] object);
void setTransactionSuccessful();
boolean isOpen();
} | 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 WhereFactoryWithinRange implements WhereFactory {
private double mSpanLat;
private double mSpanLon;
public WhereFactoryWithinRange(double spanLat, double spanLon) {
mSpanLat = spanLat;
mSpanLon = spanLon;
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
double latLow = latitude - mSpanLat/2.0;
double latHigh = latitude + mSpanLat/2.0;
double lonLow = longitude - mSpanLon/2.0;
double lonHigh = longitude + mSpanLon/2.0;
return "Latitude > " + latLow + " AND Latitude < " + latHigh +
" AND Longitude > " + lonLow + " AND Longitude < " + lonHigh;
}
} | 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.database.DatabaseDI.CacheReaderCursorFactory;
import android.database.Cursor;
public class CacheReader {
public static final String[] READER_COLUMNS = new String[] {
"Latitude", "Longitude", "Id", "Description", "Source", "CacheType", "Difficulty",
"Terrain", "Container"
};
public static final String SQL_QUERY_LIMIT = "1000";
private final CacheReaderCursorFactory mCacheReaderCursorFactory;
private final ISQLiteDatabase mSqliteWrapper;
CacheReader(ISQLiteDatabase sqliteWrapper, CacheReaderCursorFactory cacheReaderCursorFactory) {
mSqliteWrapper = sqliteWrapper;
mCacheReaderCursorFactory = cacheReaderCursorFactory;
}
public int getTotalCount() {
Cursor cursor = mSqliteWrapper
.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) {
String where = whereFactory.getWhere(mSqliteWrapper, latitude, longitude);
Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, CacheReader.READER_COLUMNS,
where, null, null, null, limit);
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.CacheType;
import com.google.code.geobeagle.GeocacheFactory.Source;
/**
* @author sng
*/
public class CacheWriter {
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 mDbToGeocacheAdapter;
private final ISQLiteDatabase mSqlite;
CacheWriter(ISQLiteDatabase sqlite, DbToGeocacheAdapter dbToGeocacheAdapter) {
mSqlite = sqlite;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
public void clearCaches(String source) {
mSqlite.execSQL(Database.SQL_CLEAR_CACHES, source);
}
/**
* Deletes any cache/gpx entries marked delete_me, then marks all remaining
* gpx-based caches, and gpx entries with delete_me = 1.
*/
public void clearEarlierLoads() {
for (String sql : CacheWriter.SQLS_CLEAR_EARLIER_LOADS) {
mSqlite.execSQL(sql);
}
}
public void deleteCache(CharSequence id) {
mSqlite.execSQL(Database.SQL_DELETE_CACHE, id);
}
public void insertAndUpdateCache(CharSequence id, CharSequence name, double latitude,
double longitude, Source sourceType, String sourceName, CacheType cacheType,
int difficulty, int terrain, int container) {
mSqlite.execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude), new Double(
longitude), mDbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName),
cacheType.toInt(), difficulty, terrain, container);
}
/**
* 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 gpxTime
* @return
*/
public boolean isGpxAlreadyLoaded(String gpxName, String gpxTime) {
// TODO:countResults is slow; replace with a query, and moveToFirst.
boolean gpxAlreadyLoaded = mSqlite.countResults(Database.TBL_GPX,
Database.SQL_MATCH_NAME_AND_EXPORTED_LATER, gpxName, gpxTime) > 0;
if (gpxAlreadyLoaded) {
mSqlite.execSQL(Database.SQL_CACHES_DONT_DELETE_ME, gpxName);
mSqlite.execSQL(Database.SQL_GPX_DONT_DELETE_ME, gpxName);
}
return gpxAlreadyLoaded;
}
public void startWriting() {
mSqlite.beginTransaction();
}
public void stopWriting() {
// TODO: abort if no writes--otherwise sqlite is unhappy.
mSqlite.setTransactionSuccessful();
mSqlite.endTransaction();
}
public void writeGpx(String gpxName, String pocketQueryExportTime) {
mSqlite.execSQL(Database.SQL_REPLACE_GPX, gpxName, pocketQueryExportTime);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.Geocache;
//TODO: Merge into Geocache class
public class LocationSaver {
private final DbFrontend mDbFrontend;
public LocationSaver(DbFrontend dbFrontend) {
mDbFrontend = dbFrontend;
}
public void saveLocation(Geocache geocache) {
final CharSequence id = geocache.getId();
CacheWriter cacheWriter = mDbFrontend.getCacheWriter();
cacheWriter.startWriting();
cacheWriter.insertAndUpdateCache(id, geocache.getName(), geocache.getLatitude(), geocache
.getLongitude(), geocache.getSourceType(), geocache.getSourceName(), geocache
.getCacheType(), 0, 0, 0);
cacheWriter.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;
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 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 com.google.code.geobeagle.R;
public class FilterNearestCaches {
private boolean mIsFiltered = true;
private final WhereFactory mWhereFactories[];
public FilterNearestCaches(WhereFactoryAllCaches whereFactoryAllCaches,
WhereFactory 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;
public class OpenHelperDelegate {
public void onCreate(ISQLiteDatabase db) {
db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V11);
db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10);
db.execSQL(Database.SQL_CREATE_IDX_LATITUDE);
db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE);
db.execSQL(Database.SQL_CREATE_IDX_SOURCE);
}
public void onUpgrade(ISQLiteDatabase db, int oldVersion) {
if (oldVersion < 9) {
db.execSQL(Database.SQL_DROP_CACHE_TABLE);
db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V08);
db.execSQL(Database.SQL_CREATE_IDX_LATITUDE);
db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE);
db.execSQL(Database.SQL_CREATE_IDX_SOURCE);
}
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\"");
}
}
}
| 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.SearchFactory;
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;
BoundingBox(double latitude, double longitude, ISQLiteDatabase sqliteWrapper,
WhereStringFactory whereStringFactory) {
mLatitude = latitude;
mLongitude = longitude;
mSqliteWrapper = sqliteWrapper;
mWhereStringFactory = whereStringFactory;
}
int getCount(float degreesDelta, int maxCount) {
String where = mWhereStringFactory.getWhereString(mLatitude, mLongitude, degreesDelta);
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 = 30;
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 "Latitude > " + latLow + " AND Latitude < " + latHigh + " AND Longitude > "
+ lonLow + " AND Longitude < " + lonHigh;
}
}
private float mLastGuess = 0.1f;
private final SearchFactory mSearchFactory;
private final WhereStringFactory mWhereStringFactory;
public WhereFactoryNearestCaches(SearchFactory searchFactory,
WhereStringFactory whereStringFactory) {
mSearchFactory = searchFactory;
mWhereStringFactory = whereStringFactory;
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
mLastGuess = mSearchFactory.createSearch(latitude, longitude, GUESS_MIN, GUESS_MAX,
sqliteWrapper).search(mLastGuess, MAX_NUMBER_OF_CACHES);
return mWhereStringFactory.getWhereString(latitude, longitude, mLastGuess);
}
}
| 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) {
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.code.geobeagle.GeocacheFactory.Source;
public class DbToGeocacheAdapter {
public Source sourceNameToSourceType(String sourceName) {
if (sourceName.equals("intent"))
return Source.WEB_URL;
else if (sourceName.equals("mylocation"))
return Source.MY_LOCATION;
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.database;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.database.DatabaseDI;
import com.google.code.geobeagle.database.DatabaseDI.GeoBeagleSqliteOpenHelper;
/**
* Will develop to represent the front-end to access a database. It takes
* responsibility to open and close the actual database connection without
* involving the clients of this class.
*/
public class DbFrontend {
CacheReader mCacheReader;
Context mContext;
GeoBeagleSqliteOpenHelper open;
boolean mIsDatabaseOpen;
CacheWriter mCacheWriter;
ISQLiteDatabase mDatabase;
public DbFrontend(Context context) {
mContext = context;
mIsDatabaseOpen = false;
}
public void openDatabase() {
if (mIsDatabaseOpen)
return;
Log.d("GeoBeagle", "DbFrontend.openDatabase()");
mIsDatabaseOpen = true;
open = new GeoBeagleSqliteOpenHelper(mContext);
final SQLiteDatabase sqDb = open.getReadableDatabase();
mDatabase = new DatabaseDI.SQLiteWrapper(sqDb);
mCacheReader = DatabaseDI.createCacheReader(mDatabase);
}
public void closeDatabase() {
if (!mIsDatabaseOpen)
return;
Log.d("GeoBeagle", "DbFrontend.closeDatabase()");
mIsDatabaseOpen = false;
open.close();
mCacheWriter = null;
mDatabase = null;
}
public ArrayList<Geocache> loadCaches(double latitude, double longitude,
WhereFactory whereFactory) {
Log.d("GeoBeagle", "DbFrontend.loadCaches");
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 CacheWriter getCacheWriter() {
if (mCacheWriter != null)
return mCacheWriter;
openDatabase();
mCacheWriter = DatabaseDI.createCacheWriter(mDatabase);
return mCacheWriter;
}
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", "DbFrontEnd.count:" + count);
return count;
}
/*
* public void onPause() { closeDatabase(); }
*/
/*
* public void onResume() { //Lazy evaluation - open 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.location;
import com.google.code.geobeagle.activity.main.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;
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onPause()
*/
public void onPause(Editor editor) {
mLocationManager.removeUpdates(mLocationListener);
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onResume()
*/
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.location;
import com.google.code.geobeagle.LocationControlBuffered;
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;
public CombinedLocationListener(LocationControlBuffered locationControlBuffered,
LocationListener locationListener) {
mLocationListener = locationListener;
mLocationControlBuffered = locationControlBuffered;
}
public void onLocationChanged(Location location) {
// 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);
}
public void onProviderDisabled(String provider) {
mLocationListener.onProviderDisabled(provider);
}
public void onProviderEnabled(String provider) {
mLocationListener.onProviderEnabled(provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
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.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import java.util.ArrayList;
public class CombinedLocationManager {
private final ArrayList<LocationListener> mLocationListeners;
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();
}
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 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 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;
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;
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.main.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 {
public CharSequence formatAttributes(int difficulty, int terrain) {
return (difficulty / 2.0) + " / " + (terrain / 2.0);
}
}
static class AttributeFormatterNull implements AttributeFormatter {
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";
private final AttributeFormatter mAttributeFormatter;
private final CacheType mCacheType;
private final int mContainer;
private final int mDifficulty;
private float[] mDistanceAndBearing = new float[2];
private GeoPoint mGeoPoint;
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;
Geocache(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container, AttributeFormatter attributeFormatter) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
mSourceType = sourceType;
mSourceName = sourceName;
mCacheType = cacheType;
mDifficulty = difficulty;
mTerrain = terrain;
mContainer = container;
mAttributeFormatter = attributeFormatter;
}
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;
}
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() {
if (mGeoPoint == null) {
int latE6 = (int)(mLatitude * GeoUtils.MILLION);
int lonE6 = (int)(mLongitude * GeoUtils.MILLION);
mGeoPoint = new GeoPoint(latE6, lonE6);
}
return mGeoPoint;
}
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);
}
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);
}
}
| Java |
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 yards = (int)(miles * (5280 / 3));
return String.format("%1$1dyd", yards);
}
}
| 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 interface DistanceFormatter {
public abstract CharSequence formatDistance(float distance);
}
| 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 DistanceFormatterMetric implements DistanceFormatter {
public CharSequence formatDistance(float distance) {
if (distance == -1) {
return "";
}
if (distance >= 1000) {
return String.format("%1$1.2fkm", distance / 1000.0);
}
return String.format("%1$dm", (int)distance);
}
}
| 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.SensorListener;
@SuppressWarnings("deprecation")
public class CompassListener implements SensorListener {
private final Refresher mRefresher;
private final LocationControlBuffered mLocationControlBuffered;
private float mLastAzimuth;
public CompassListener(Refresher refresher,
LocationControlBuffered locationControlBuffered, float lastAzimuth) {
mRefresher = refresher;
mLocationControlBuffered = locationControlBuffered;
mLastAzimuth = lastAzimuth;
}
// public void onAccuracyChanged(Sensor sensor, int accuracy) {
// }
// public void onSensorChanged(SensorEvent event) {
// onSensorChanged(SensorManager.SENSOR_ORIENTATION, event.values);
// }
public void onAccuracyChanged(int sensor, int accuracy) {
}
public void onSensorChanged(int sensor, float[] values) {
final float currentAzimuth = values[0];
if (Math.abs(currentAzimuth - mLastAzimuth) > 5) {
// Log.d("GeoBeagle", "azimuth now " + sensor +", " +
// currentAzimuth);
mLocationControlBuffered.setAzimuth(((int)currentAzimuth / 5) * 5);
mRefresher.refresh();
mLastAzimuth = 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.cachedetails;
import com.google.code.geobeagle.R;
import android.app.Activity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CacheDetailsLoader {
static interface Details {
String getString();
}
static class DetailsError implements Details {
private final Activity mActivity;
private final String mPath;
private final int mResourceId;
DetailsError(Activity activity, int resourceId, String path) {
mActivity = activity;
mResourceId = resourceId;
mPath = path;
}
public String getString() {
return mActivity.getString(mResourceId, mPath);
}
}
static class DetailsImpl implements Details {
private final byte[] mBuffer;
DetailsImpl(byte[] buffer) {
mBuffer = buffer;
}
public String getString() {
return new String(mBuffer);
}
}
public static class DetailsOpener {
private final Activity mActivity;
public DetailsOpener(Activity activity) {
mActivity = activity;
}
DetailsReader open(File file) {
FileInputStream fileInputStream;
String absolutePath = file.getAbsolutePath();
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
return new DetailsReaderFileNotFound(mActivity, e.getMessage());
}
byte[] buffer = new byte[(int)file.length()];
return new DetailsReaderImpl(mActivity, absolutePath, fileInputStream, buffer);
}
}
interface DetailsReader {
Details read();
}
static class DetailsReaderFileNotFound implements DetailsReader {
private final Activity mActivity;
private final String mPath;
DetailsReaderFileNotFound(Activity activity, String path) {
mActivity = activity;
mPath = path;
}
public Details read() {
return new DetailsError(mActivity, R.string.error_opening_details_file, mPath);
}
}
static class DetailsReaderImpl implements DetailsReader {
private final Activity mActivity;
private final byte[] mBuffer;
private final FileInputStream mFileInputStream;
private final String mPath;
DetailsReaderImpl(Activity activity, String path, FileInputStream fileInputStream,
byte[] buffer) {
mActivity = activity;
mFileInputStream = fileInputStream;
mPath = path;
mBuffer = buffer;
}
public Details read() {
try {
mFileInputStream.read(mBuffer);
mFileInputStream.close();
return new DetailsImpl(mBuffer);
} catch (IOException e) {
return new DetailsError(mActivity, R.string.error_reading_details_file, mPath);
}
}
}
public static final String DETAILS_DIR = "/sdcard/GeoBeagle/";
private final DetailsOpener mDetailsOpener;
public CacheDetailsLoader(DetailsOpener detailsOpener) {
mDetailsOpener = detailsOpener;
}
public String load(CharSequence cacheId) {
final String sanitized = CacheDetailsWriter.replaceIllegalFileChars(cacheId.toString());
String path = DETAILS_DIR + sanitized + ".html";
File file = new File(path);
DetailsReader detailsReader = mDetailsOpener.open(file);
Details details = detailsReader.read();
return details.getString();
}
}
| 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 class HtmlWriter {
private final WriterWrapper mWriter;
public HtmlWriter(WriterWrapper writerWrapper) {
mWriter = writerWrapper;
}
public void close() throws IOException {
mWriter.close();
}
public void open(String path) throws IOException {
mWriter.open(path);
}
public void write(String text) throws IOException {
mWriter.write(text + "<br/>\n");
}
public void writeFooter() throws IOException {
mWriter.write(" </body>\n");
mWriter.write("</html>\n");
}
public void writeHeader() throws IOException {
mWriter.write("<html>\n");
mWriter.write(" <body>\n");
}
public void writeSeparator() throws IOException {
mWriter.write("<hr/>\n");
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.cachedetails;
import java.io.IOException;
public class CacheDetailsWriter {
public static final String GEOBEAGLE_DIR = "/sdcard/GeoBeagle";
private final HtmlWriter mHtmlWriter;
private String mLatitude;
private String mLongitude;
public CacheDetailsWriter(HtmlWriter htmlWriter) {
mHtmlWriter = htmlWriter;
}
public void close() throws IOException {
mHtmlWriter.writeFooter();
mHtmlWriter.close();
}
public void latitudeLongitude(String latitude, String longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
public void open(String wpt) throws IOException {
final String sanitized = replaceIllegalFileChars(wpt);
mHtmlWriter.open(CacheDetailsWriter.GEOBEAGLE_DIR + "/" + sanitized + ".html");
}
public static String replaceIllegalFileChars(String wpt) {
return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_");
}
public void writeHint(String text) throws IOException {
mHtmlWriter.write("<br />Hint: <font color=gray>" + text + "</font>");
}
public void writeLine(String text) throws IOException {
mHtmlWriter.write(text);
}
public void writeLogDate(String text) throws IOException {
mHtmlWriter.writeSeparator();
mHtmlWriter.write(text);
}
public void writeWptName(String wpt) throws IOException {
mHtmlWriter.writeHeader();
mHtmlWriter.write(wpt);
mHtmlWriter.write(mLatitude + ", " + mLongitude);
mLatitude = mLongitude = null;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*
* maps.jar doesn't include all its dependencies; fake them out here for testing.
*/
package android.widget;
public class ZoomButtonsController {
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import android.text.Editable;
import android.text.InputFilter;
class StubEditable implements Editable {
private final String mString;
public StubEditable(String s) {
mString = s;
}
public Editable append(char arg0) {
return null;
}
public Editable append(CharSequence arg0) {
return null;
}
public Editable append(CharSequence arg0, int arg1, int arg2) {
return null;
}
public char charAt(int index) {
return mString.charAt(index);
}
public void clear() {
}
public void clearSpans() {
}
public Editable delete(int arg0, int arg1) {
return null;
}
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
mString.getChars(srcBegin, srcEnd, dst, dstBegin);
}
public InputFilter[] getFilters() {
return null;
}
public int getSpanEnd(Object arg0) {
return 0;
}
public int getSpanFlags(Object arg0) {
return 0;
}
public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) {
return null;
}
public int getSpanStart(Object arg0) {
return 0;
}
public Editable insert(int arg0, CharSequence arg1) {
return null;
}
public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) {
return null;
}
public int length() {
return mString.length();
}
@SuppressWarnings("unchecked")
public int nextSpanTransition(int arg0, int arg1, Class arg2) {
return 0;
}
public void removeSpan(Object arg0) {
}
public Editable replace(int arg0, int arg1, CharSequence arg2) {
return null;
}
public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) {
return null;
}
public void setFilters(InputFilter[] arg0) {
}
public void setSpan(Object arg0, int arg1, int arg2, int arg3) {
}
public CharSequence subSequence(int start, int end) {
return mString.subSequence(start, end);
}
@Override
public String toString() {
return mString;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.app.Activity;
public class GpxLoaderDI {
public static GpxLoader create(Activity activity, Database database,
SQLiteWrapper sqliteWrapper, MessageHandler messageHandler,
ErrorDisplayer errorDisplayer) {
final CachePersisterFacade cachePersisterFacade = CachePersisterFacadeDI.create(activity,
messageHandler, database, sqliteWrapper);
final GpxToCache gpxToCache = GpxToCacheDI.create(activity, cachePersisterFacade);
return new GpxLoader(gpxToCache, cachePersisterFacade, errorDisplayer);
}
}
| Java |
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import android.app.Activity;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock; /*
** 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.
*//*
** 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.
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class CachePersisterFacadeDI {
public static class FileFactory {
public File createFile(String path) {
return new File(path);
}
}
public static class WriterWrapper {
Writer mWriter;
public void close() throws IOException {
mWriter.close();
}
public void open(String path) throws IOException {
mWriter = new BufferedWriter(new FileWriter(path), 4000);
}
public void write(String str) throws IOException {
mWriter.write(str);
}
}
public static CachePersisterFacade create(Activity activity, MessageHandler messageHandler,
Database database, SQLiteWrapper sqliteWrapper) {
final CacheWriter cacheWriter = DatabaseDI.createCacheWriter(sqliteWrapper);
final CacheTagWriter cacheTagWriter = new CacheTagWriter(cacheWriter);
final FileFactory fileFactory = new FileFactory();
final WriterWrapper writerWrapper = new WriterWrapper();
final HtmlWriter htmlWriter = new HtmlWriter(writerWrapper);
final CacheDetailsWriter cacheDetailsWriter = new CacheDetailsWriter(htmlWriter);
final PowerManager powerManager = (PowerManager)activity
.getSystemService(Context.POWER_SERVICE);
final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"Importing");
return new CachePersisterFacade(cacheTagWriter, fileFactory, cacheDetailsWriter,
messageHandler, wakeLock);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
public class EventHelperDI {
public static EventHelper create(GpxToCacheDI.XmlPullParserWrapper xmlPullParser,
CachePersisterFacade cachePersisterFacade) {
final GpxEventHandler gpxEventHandler = new GpxEventHandler(cachePersisterFacade);
final EventHelper.XmlPathBuilder xmlPathBuilder = new EventHelper.XmlPathBuilder();
return new EventHelper(xmlPathBuilder, gpxEventHandler, xmlPullParser);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GpxToCacheDI {
public static class XmlPullParserWrapper {
private String mSource;
private XmlPullParser mXmlPullParser;
public String getAttributeValue(String namespace, String name) {
return mXmlPullParser.getAttributeValue(namespace, name);
}
public int getEventType() throws XmlPullParserException {
return mXmlPullParser.getEventType();
}
public String getName() {
return mXmlPullParser.getName();
}
public String getSource() {
return mSource;
}
public String getText() {
return mXmlPullParser.getText();
}
public int next() throws XmlPullParserException, IOException {
return mXmlPullParser.next();
}
public void open(String path, Reader reader) throws XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
newPullParser.setInput(reader);
mSource = path;
mXmlPullParser = newPullParser;
}
}
public static GpxToCache create(Activity activity, CachePersisterFacade cachePersisterFacade) {
final GpxToCacheDI.XmlPullParserWrapper xmlPullParserWrapper = new GpxToCacheDI.XmlPullParserWrapper();
final EventHelper eventHelper = EventHelperDI.create(xmlPullParserWrapper,
cachePersisterFacade);
return new GpxToCache(xmlPullParserWrapper, eventHelper);
}
public static XmlPullParser createPullParser(String path) throws FileNotFoundException,
XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
final Reader reader = new BufferedReader(new FileReader(path));
newPullParser.setInput(reader);
return newPullParser;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.gpx.GpxAndZipFiles.GpxAndZipFilesIterFactory;
import com.google.code.geobeagle.gpx.GpxAndZipFiles.GpxAndZipFilenameFilter;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.ImportThreadDelegate.ImportThreadHelper;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import java.io.FilenameFilter;
public class GpxImporterDI {
// Can't test this due to final methods in base.
public static class ImportThread extends Thread {
static ImportThread create(MessageHandler messageHandler, GpxLoader gpxLoader,
ErrorDisplayer errorDisplayer) {
final FilenameFilter filenameFilter = new GpxAndZipFilenameFilter();
final GpxAndZipFilesIterFactory gpxAndZipFilesIterFactory = new GpxAndZipFilesIterFactory();
final GpxAndZipFiles gpxAndZipFiles = new GpxAndZipFiles(filenameFilter,
gpxAndZipFilesIterFactory);
final ImportThreadHelper importThreadHelper = new ImportThreadHelper(gpxLoader,
messageHandler, errorDisplayer);
return new ImportThread(gpxAndZipFiles, importThreadHelper, errorDisplayer);
}
private final ImportThreadDelegate mImportThreadDelegate;
public ImportThread(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper,
ErrorDisplayer errorDisplayer) {
mImportThreadDelegate = new ImportThreadDelegate(gpxAndZipFiles, importThreadHelper,
errorDisplayer);
}
@Override
public void run() {
mImportThreadDelegate.run();
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ImportThreadWrapper {
private ImportThread mImportThread;
private final MessageHandler mMessageHandler;
public ImportThreadWrapper(MessageHandler messageHandler) {
mMessageHandler = messageHandler;
}
public boolean isAlive() {
if (mImportThread != null)
return mImportThread.isAlive();
return false;
}
public void join() throws InterruptedException {
if (mImportThread != null)
mImportThread.join();
}
public void open(CacheListDelegate cacheListDelegate, GpxLoader gpxLoader,
ErrorDisplayer mErrorDisplayer) {
mMessageHandler.start(cacheListDelegate);
mImportThread = ImportThread.create(mMessageHandler, gpxLoader, mErrorDisplayer);
}
public void start() {
if (mImportThread != null)
mImportThread.start();
}
}
// Too hard to test this class due to final methods in base.
public static class MessageHandler extends Handler {
static final int MSG_DONE = 1;
static final int MSG_PROGRESS = 0;
public static MessageHandler create(ListActivity listActivity) {
final ProgressDialogWrapper progressDialogWrapper = new ProgressDialogWrapper(
listActivity);
return new MessageHandler(progressDialogWrapper);
}
private int mCacheCount;
private CacheListDelegate mCacheListDelegate;
private boolean mLoadAborted;
private final ProgressDialogWrapper mProgressDialogWrapper;
private String mSource;
private String mStatus;
private String mWaypointId;
public MessageHandler(ProgressDialogWrapper progressDialogWrapper) {
mProgressDialogWrapper = progressDialogWrapper;
}
public void abortLoad() {
mLoadAborted = true;
mProgressDialogWrapper.dismiss();
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessageHandler.MSG_PROGRESS:
mProgressDialogWrapper.setMessage(mStatus);
break;
case MessageHandler.MSG_DONE:
if (!mLoadAborted) {
mProgressDialogWrapper.dismiss();
mCacheListDelegate.onResume();
}
break;
default:
break;
}
}
public void loadComplete() {
sendEmptyMessage(MessageHandler.MSG_DONE);
}
public void start(CacheListDelegate cacheListDelegate) {
mCacheCount = 0;
mLoadAborted = false;
mCacheListDelegate = cacheListDelegate;
mProgressDialogWrapper.show("Importing caches", "Please wait...");
}
public void updateName(String name) {
mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name;
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateSource(String text) {
mSource = text;
}
public void updateWaypointId(String wpt) {
mWaypointId = wpt;
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ProgressDialogWrapper {
private final Context mContext;
private ProgressDialog mProgressDialog;
public ProgressDialogWrapper(Context context) {
mContext = context;
}
public void dismiss() {
if (mProgressDialog != null)
mProgressDialog.dismiss();
}
public void setMessage(CharSequence message) {
mProgressDialog.setMessage(message);
}
public void show(String title, String msg) {
mProgressDialog = ProgressDialog.show(mContext, title, msg);
}
}
public static class ToastFactory {
public void showToast(Context context, int resId, int duration) {
Toast.makeText(context, resId, duration).show();
}
}
public static GpxImporter create(Database database, SQLiteWrapper sqliteWrapper,
ErrorDisplayer errorDisplayer, ListActivity listActivity) {
final MessageHandler messageHandler = MessageHandler.create(listActivity);
final GpxLoader gpxLoader = GpxLoaderDI.create(listActivity, database, sqliteWrapper,
messageHandler, errorDisplayer);
final ToastFactory toastFactory = new ToastFactory();
final ImportThreadWrapper importThreadWrapper = new ImportThreadWrapper(messageHandler);
return new GpxImporter(gpxLoader, database, sqliteWrapper, listActivity,
importThreadWrapper, messageHandler, errorDisplayer, toastFactory);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.data.Geocaches;
import com.google.code.geobeagle.io.CacheReader;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DbToGeocacheAdapter;
import com.google.code.geobeagle.io.GeocachesSql;
import com.google.code.geobeagle.io.CacheReader.CacheReaderCursor;
import com.google.code.geobeagle.io.CacheReader.WhereFactory;
import com.google.code.geobeagle.io.Database.ISQLiteDatabase;
import com.google.code.geobeagle.io.Database.OpenHelperDelegate;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseDI {
public static class CacheReaderCursorFactory {
public CacheReaderCursor create(Cursor cursor) {
GeocacheFactory geocacheFactory = new GeocacheFactory();
DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheReaderCursor(cursor, geocacheFactory, dbToGeocacheAdapter);
}
}
public static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper {
private final Database.OpenHelperDelegate mOpenHelperDelegate;
public GeoBeagleSqliteOpenHelper(Context context,
Database.OpenHelperDelegate openHelperDelegate) {
super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
mOpenHelperDelegate = openHelperDelegate;
}
@Override
public void onCreate(SQLiteDatabase db) {
mOpenHelperDelegate.onCreate(new SQLiteWrapper(db));
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
mOpenHelperDelegate.onUpgrade(new SQLiteWrapper(db), oldVersion, newVersion);
}
}
public static class SQLiteWrapper implements ISQLiteDatabase {
private SQLiteDatabase mSQLiteDatabase;
public SQLiteWrapper(SQLiteDatabase db) {
mSQLiteDatabase = db;
}
public void beginTransaction() {
mSQLiteDatabase.beginTransaction();
}
public void close() {
mSQLiteDatabase.close();
}
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();
cursor.close();
return count;
}
public void endTransaction() {
mSQLiteDatabase.endTransaction();
}
public void execSQL(String sql) {
mSQLiteDatabase.execSQL(sql);
}
public void execSQL(String sql, Object... bindArgs) {
mSQLiteDatabase.execSQL(sql, bindArgs);
}
public void openReadableDatabase(Database database) {
mSQLiteDatabase = database.getReadableDatabase();
}
public void openWritableDatabase(Database database) {
mSQLiteDatabase = database.getWritableDatabase();
}
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
return mSQLiteDatabase.query(table, columns, selection, selectionArgs, groupBy,
orderBy, having, limit);
}
public Cursor rawQuery(String sql, String[] selectionArgs) {
return mSQLiteDatabase.rawQuery(sql, selectionArgs);
}
public void setTransactionSuccessful() {
mSQLiteDatabase.setTransactionSuccessful();
}
}
public static Database create(Context context) {
final OpenHelperDelegate openHelperDelegate = new Database.OpenHelperDelegate();
final GeoBeagleSqliteOpenHelper sqliteOpenHelper = new GeoBeagleSqliteOpenHelper(context,
openHelperDelegate);
return new Database(sqliteOpenHelper);
}
public static GeocachesSql create(LocationControl locationControl, Database database) {
final Geocaches geocaches = new Geocaches();
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final CacheReader cacheReader = createCacheReader(sqliteWrapper);
return new GeocachesSql(cacheReader, geocaches, database, sqliteWrapper, locationControl);
}
public static CacheReader createCacheReader(SQLiteWrapper sqliteWrapper) {
final WhereFactory whereFactory = new CacheReader.WhereFactory();
final CacheReaderCursorFactory cacheReaderCursorFactory = new CacheReaderCursorFactory();
return new CacheReader(sqliteWrapper, whereFactory, cacheReaderCursorFactory);
}
public static CacheWriter createCacheWriter(SQLiteWrapper sqliteWrapper) {
DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheWriter(sqliteWrapper, dbToGeocacheAdapter);
}
}
| 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.data;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFromParcelFactory;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.data.Geocache.Source.SourceFactory;
import android.os.Parcel;
import android.os.Parcelable;
public class GeocacheFactory {
private static SourceFactory mSourceFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
}
public static class CreateGeocacheFromParcel implements Parcelable.Creator<Geocache> {
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory = new GeocacheFromParcelFactory(
new GeocacheFactory());
public Geocache createFromParcel(Parcel in) {
return mGeocacheFromParcelFactory.create(in);
}
public Geocache[] newArray(int size) {
return new Geocache[size];
}
}
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
return new Geocache(id, name, latitude, longitude, sourceType, sourceName);
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.DistanceFormatter;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.data.GeocacheVector;
import com.google.code.geobeagle.data.IGeocacheVector;
import com.google.code.geobeagle.io.LocationSaver;
import android.location.Location;
public class GeocacheVectorFactory {
private final DistanceFormatter mDistanceFormatter;
private final ResourceProvider mResourceProvider;
private final GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory;
private final LocationSaver mLocationSaver;
public GeocacheVectorFactory(GeocacheFromMyLocationFactory geocacheFromMyLocationFactory,
LocationSaver locationSaver, DistanceFormatter distanceFormatter,
ResourceProvider resourceProvider) {
mDistanceFormatter = distanceFormatter;
mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory;
mResourceProvider = resourceProvider;
mLocationSaver = locationSaver;
}
private float calculateDistance(Location here, Geocache geocache) {
if (here != null) {
float[] results = new float[1];
Location.distanceBetween(here.getLatitude(), here.getLongitude(), geocache
.getLatitude(), geocache.getLongitude(), results);
return results[0];
}
return -1;
}
public GeocacheVector create(Geocache location, Location here) {
return new GeocacheVector(location, calculateDistance(here, location), mDistanceFormatter);
}
public IGeocacheVector createMyLocation() {
return new GeocacheVector.MyLocation(mResourceProvider, mGeocacheFromMyLocationFactory,
mLocationSaver);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.zip;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipInputStream;
public class ZipInputStreamFactory {
public GpxZipInputStream create(String filename) throws IOException {
return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream(
new FileInputStream(filename))));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.code.geobeagle.LocationControl.LocationChooser;
import android.location.LocationManager;
public class LocationControlDi {
public static LocationControl create(LocationManager locationManager) {
final LocationChooser locationChooser = new LocationChooser();
return new LocationControl(locationManager, locationChooser);
}
}
| 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.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.ui.WebPageAndDetailsButtonEnabler;
import android.view.View;
public class Misc {
public static class Time {
public long getCurrentTime() {
return System.currentTimeMillis();
}
}
public static WebPageAndDetailsButtonEnabler create(GeoBeagle geoBeagle, View cachePageButton,
View detailsButton) {
return new WebPageAndDetailsButtonEnabler(geoBeagle, cachePageButton, detailsButton);
}
}
| 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.ui;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI;
import com.google.code.geobeagle.io.LocationSaver;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.ui.EditCacheActivityDelegate;
import com.google.code.geobeagle.ui.EditCacheActivityDelegate.CancelButtonOnClickListener;
import android.app.Activity;
import android.os.Bundle;
public class EditCacheActivity extends Activity {
private final EditCacheActivityDelegate mEditCacheActivityDelegate;
public EditCacheActivity() {
super();
final Database database = DatabaseDI.create(this);
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final CacheWriter cacheWriter = DatabaseDI.createCacheWriter(sqliteWrapper);
final LocationSaver locationSaver = new LocationSaver(database, sqliteWrapper, cacheWriter);
final CancelButtonOnClickListener cancelButtonOnClickListener = new CancelButtonOnClickListener(
this);
mEditCacheActivityDelegate = new EditCacheActivityDelegate(this,
cancelButtonOnClickListener, locationSaver);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditCacheActivityDelegate.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
mEditCacheActivityDelegate.onResume();
}
}
| 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.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.CacheListData;
import com.google.code.geobeagle.data.DistanceFormatter;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.data.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.data.GeocacheVectorFactory;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.data.GeocacheVector.LocationComparator;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI;
import com.google.code.geobeagle.io.GeocachesSql;
import com.google.code.geobeagle.io.GpxImporter;
import com.google.code.geobeagle.io.GpxImporterDI;
import com.google.code.geobeagle.io.LocationSaver;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import com.google.code.geobeagle.ui.GeocacheListAdapter;
import com.google.code.geobeagle.ui.GeocacheRowInflater;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.view.LayoutInflater;
public class CacheListDelegateDI {
public static CacheListDelegate create(ListActivity parent, LayoutInflater layoutInflater) {
final ErrorDisplayer errorDisplayer = new ErrorDisplayer(parent);
final Database database = DatabaseDI.create(parent);
final ResourceProvider resourceProvider = new ResourceProvider(parent);
final LocationManager locationManager = (LocationManager)parent
.getSystemService(Context.LOCATION_SERVICE);
final LocationControl locationControl = LocationControlDi.create(locationManager);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final GeocacheFromMyLocationFactory geocacheFromMyLocationFactory = new GeocacheFromMyLocationFactory(
geocacheFactory, locationControl, errorDisplayer);
final GeocachesSql locationBookmarks = DatabaseDI.create(locationControl, database);
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final CacheWriter cacheWriter = DatabaseDI.createCacheWriter(sqliteWrapper);
final DistanceFormatter distanceFormatter = new DistanceFormatter();
final LocationSaver locationSaver = new LocationSaver(database, sqliteWrapper, cacheWriter);
final GeocacheVectorFactory geocacheVectorFactory = new GeocacheVectorFactory(
geocacheFromMyLocationFactory, locationSaver, distanceFormatter, resourceProvider);
final LocationComparator locationComparator = new LocationComparator();
final GeocacheVectors geocacheVectors = new GeocacheVectors(locationComparator,
geocacheVectorFactory);
final CacheListData cacheListData = new CacheListData(geocacheVectors,
geocacheVectorFactory);
final Action actions[] = CacheListDelegateDI.create(parent, database, sqliteWrapper,
cacheListData, cacheWriter, geocacheVectors, errorDisplayer);
final CacheListDelegate.CacheListOnCreateContextMenuListener.Factory factory = new CacheListDelegate.CacheListOnCreateContextMenuListener.Factory();
final GpxImporter gpxImporter = GpxImporterDI.create(database, sqliteWrapper,
errorDisplayer, parent);
final GeocacheRowInflater geocacheRowInflater = new GeocacheRowInflater(layoutInflater);
final GeocacheListAdapter geocacheListAdapter = new GeocacheListAdapter(geocacheVectors,
geocacheRowInflater);
return new CacheListDelegate(parent, locationBookmarks, locationControl, cacheListData,
geocacheVectors, geocacheListAdapter, errorDisplayer, actions, factory, gpxImporter);
}
public static Action[] create(ListActivity parent, Database database,
SQLiteWrapper sqliteWrapper, CacheListData cacheListData, CacheWriter cacheWriter,
GeocacheVectors geocacheVectors, ErrorDisplayer errorDisplayer) {
final Intent intent = new Intent(parent, GeoBeagle.class);
final ViewAction viewAction = new ViewAction(geocacheVectors, parent, intent);
final DeleteAction deleteAction = new DeleteAction(database, sqliteWrapper, cacheWriter,
geocacheVectors, errorDisplayer);
return new Action[] {
deleteAction, viewAction
};
}
}
| 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.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;
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onPause()
*/
public void onPause(Editor editor) {
mLocationManager.removeUpdates(mLocationListener);
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onResume()
*/
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;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.CacheListDelegateDI;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheList extends ListActivity {
private CacheListDelegate delegate;
@Override
public boolean onContextItemSelected(MenuItem item) {
return delegate.onContextItemSelected(item) || super.onContextItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate = CacheListDelegateDI.create(this, this.getLayoutInflater());
delegate.onCreate();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return delegate.onCreateOptionsMenu(menu);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
delegate.onListItemClick(l, v, position, id);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return delegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
delegate.onPause();
}
@Override
protected void onResume() {
super.onResume();
delegate.onResume();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.io.GpxToCache.CancelException;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import org.xmlpull.v1.XmlPullParserException;
import android.database.sqlite.SQLiteException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
public class GpxLoader {
private final CachePersisterFacade mCachePersisterFacade;
private final ErrorDisplayer mErrorDisplayer;
private final GpxToCache mGpxToCache;
GpxLoader(GpxToCache gpxToCache, CachePersisterFacade cachePersisterFacade,
ErrorDisplayer errorDisplayer) {
mGpxToCache = gpxToCache;
mCachePersisterFacade = cachePersisterFacade;
mErrorDisplayer = errorDisplayer;
}
public void abort() {
mGpxToCache.abort();
}
public void end() {
mCachePersisterFacade.end();
}
/**
* @return true if we should continue loading more files, false if we should
* terminate.
*/
public boolean load() {
boolean markLoadAsComplete = false;
boolean continueLoading = false;
try {
boolean alreadyLoaded = mGpxToCache.load();
markLoadAsComplete = !alreadyLoaded;
continueLoading = true;
} catch (final SQLiteException e) {
mErrorDisplayer.displayError(R.string.error_writing_cache, e.getMessage());
} catch (XmlPullParserException e) {
mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage());
} catch (IOException e) {
mErrorDisplayer.displayError(R.string.error_reading_file, mGpxToCache.getSource());
} catch (CancelException e) {
}
mCachePersisterFacade.close(markLoadAsComplete);
return continueLoading;
}
public void open(String path, Reader reader) throws FileNotFoundException, XmlPullParserException, IOException {
mGpxToCache.open(path, reader);
mCachePersisterFacade.open(path);
}
public void start() {
mCachePersisterFacade.start();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import android.database.Cursor;
import android.location.Location;
public class CacheReader {
public static class CacheReaderCursor {
private final Cursor mCursor;
private final GeocacheFactory mGeocacheFactory;
private final DbToGeocacheAdapter mDbToGeocacheAdapter;
public CacheReaderCursor(Cursor cursor, GeocacheFactory geocacheFactory,
DbToGeocacheAdapter dbToGeocacheAdapter) {
mCursor = cursor;
mGeocacheFactory = geocacheFactory;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
void close() {
mCursor.close();
}
public Geocache getCache() {
String sourceName = mCursor.getString(4);
return mGeocacheFactory.create(mCursor.getString(2), mCursor.getString(3), mCursor
.getDouble(0), mCursor.getDouble(1), mDbToGeocacheAdapter
.sourceNameToSourceType(sourceName), sourceName);
}
boolean moveToNext() {
return mCursor.moveToNext();
}
}
public static class WhereFactory {
// 1 degree ~= 111km
public static final double DEGREES_DELTA = 0.08;
public String getWhere(Location location) {
if (location == null)
return null;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
double latLow = latitude - WhereFactory.DEGREES_DELTA;
double latHigh = latitude + WhereFactory.DEGREES_DELTA;
double lat_radians = Math.toRadians(latitude);
double cos_lat = Math.cos(lat_radians);
double lonLow = Math.max(-180, longitude - WhereFactory.DEGREES_DELTA / cos_lat);
double lonHigh = Math.min(180, longitude + WhereFactory.DEGREES_DELTA / cos_lat);
return "Latitude > " + latLow + " AND Latitude < " + latHigh + " AND Longitude > "
+ lonLow + " AND Longitude < " + lonHigh;
}
}
public static final String SQL_QUERY_LIMIT = "1000";
private final DatabaseDI.CacheReaderCursorFactory mCacheReaderCursorFactory;
private final SQLiteWrapper mSqliteWrapper;
private final WhereFactory mWhereFactory;
// TODO: rename to CacheSqlReader / CacheSqlWriter
CacheReader(DatabaseDI.SQLiteWrapper sqliteWrapper, WhereFactory whereFactory,
DatabaseDI.CacheReaderCursorFactory cacheReaderCursorFactory) {
mSqliteWrapper = sqliteWrapper;
mWhereFactory = whereFactory;
mCacheReaderCursorFactory = cacheReaderCursorFactory;
}
public int getTotalCount() {
return mSqliteWrapper.countResults(Database.TBL_CACHES, null);
}
public CacheReaderCursor open(Location location) {
String where = mWhereFactory.getWhere(location);
Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, Database.READER_COLUMNS, where,
null, null, null, SQL_QUERY_LIMIT);
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return mCacheReaderCursorFactory.create(cursor);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.