code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.TabsUtil; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.util.UserUtils; import android.app.Activity; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Window; import android.widget.FrameLayout; import android.widget.TabHost; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MainActivity extends TabActivity { public static final String TAG = "MainActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private TabHost mTabHost; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); // Don't start the main activity if we don't have credentials if (!((Foursquared) getApplication()).isReady()) { if (DEBUG) Log.d(TAG, "Not ready for user."); redirectToLoginActivity(); } if (DEBUG) Log.d(TAG, "Setting up main activity layout."); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main_activity); initTabHost(); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } private void initTabHost() { if (mTabHost != null) { throw new IllegalStateException("Trying to intialize already initializd TabHost"); } mTabHost = getTabHost(); // We may want to show the friends tab first, or the places tab first, depending on // the user preferences. SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); // We can add more tabs here eventually, but if "Friends" isn't the startup tab, then // we are left with "Places" being the startup tab instead. String[] startupTabValues = getResources().getStringArray(R.array.startup_tabs_values); String startupTab = settings.getString( Preferences.PREFERENCE_STARTUP_TAB, startupTabValues[0]); Intent intent = new Intent(this, NearbyVenuesActivity.class); if (startupTab.equals(startupTabValues[0])) { TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_friends), R.drawable.tab_main_nav_friends_selector, 1, new Intent(this, FriendsActivity.class)); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector, 2, intent); } else { intent.putExtra(NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 4000L); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector, 1, intent); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_friends), R.drawable.tab_main_nav_friends_selector, 2, new Intent(this, FriendsActivity.class)); } TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_tips), R.drawable.tab_main_nav_tips_selector, 3, new Intent(this, TipsActivity.class)); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_todos), R.drawable.tab_main_nav_todos_selector, 4, new Intent(this, TodosActivity.class)); // 'Me' tab, just shows our own info. At this point we should have a // stored user id, and a user gender to control the image which is // displayed on the tab. String userId = ((Foursquared) getApplication()).getUserId(); String userGender = ((Foursquared) getApplication()).getUserGender(); Intent intentTabMe = new Intent(this, UserDetailsActivity.class); intentTabMe.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId == null ? "unknown" : userId); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_me), UserUtils.getDrawableForMeTabByGender(userGender), 5, intentTabMe); // Fix layout for 1.5. if (UiUtil.sdkVersion() < 4) { FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent); flTabContent.setPadding(0, 0, 0, 0); } } private void redirectToLoginActivity() { setVisible(false); Intent intent = new Intent(this, LoginActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.setFlags( Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }
1031868817-hws
main/src/com/joelapenna/foursquared/MainActivity.java
Java
asf20
5,576
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LocationException extends FoursquaredException { public LocationException() { super("Unable to determine your location."); } public LocationException(String message) { super(message); } private static final long serialVersionUID = 1L; }
1031868817-hws
main/src/com/joelapenna/foursquared/error/LocationException.java
Java
asf20
424
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ class FoursquaredException extends Exception { private static final long serialVersionUID = 1L; public FoursquaredException(String message) { super(message); } }
1031868817-hws
main/src/com/joelapenna/foursquared/error/FoursquaredException.java
Java
asf20
318
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import java.io.IOException; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApiWithBasicAuth extends AbstractHttpApi { private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; public HttpApiWithBasicAuth(DefaultHttpClient httpClient, String clientVersion) { super(httpClient, clientVersion); httpClient.addRequestInterceptor(preemptiveAuth, 0); } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { return executeHttpRequest(httpRequest, parser); } }
1031868817-hws
main/src/com/joelapenna/foursquare/http/HttpApiWithBasicAuth.java
Java
asf20
2,833
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface HttpApi { abstract public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException; abstract public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException; abstract public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs); abstract public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs); abstract public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException; }
1031868817-hws
main/src/com/joelapenna/foursquare/http/HttpApi.java
Java
asf20
1,501
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.util.JSONUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class AbstractHttpApi implements HttpApi { protected static final Logger LOG = Logger.getLogger(AbstractHttpApi.class.getCanonicalName()); protected static final boolean DEBUG = Foursquare.DEBUG; private static final String DEFAULT_CLIENT_VERSION = "com.joelapenna.foursquare"; private static final String CLIENT_VERSION_HEADER = "User-Agent"; private static final int TIMEOUT = 60; private final DefaultHttpClient mHttpClient; private final String mClientVersion; public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) { mHttpClient = httpClient; if (clientVersion != null) { mClientVersion = clientVersion; } else { mClientVersion = DEFAULT_CLIENT_VERSION; } } public FoursquareType executeHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI()); HttpResponse response = executeHttpRequest(httpRequest); if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpRequest.getURI().toString()); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 200: String content = EntityUtils.toString(response.getEntity()); return JSONUtils.consume(parser, content); case 400: if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 400"); throw new FoursquareException( response.getStatusLine().toString(), EntityUtils.toString(response.getEntity())); case 401: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 401"); throw new FoursquareCredentialsException(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 404"); throw new FoursquareException(response.getStatusLine().toString()); case 500: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 500"); throw new FoursquareException("Foursquare is down. Try again later."); default: if (DEBUG) LOG.log(Level.FINE, "Default case for status code reached: " + response.getStatusLine().toString()); response.getEntity().consumeContent(); throw new FoursquareException("Error connecting to Foursquare: " + statusCode + ". Try again later."); } } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpPost: " + url); HttpPost httpPost = createHttpPost(url, nameValuePairs); HttpResponse response = executeHttpRequest(httpPost); if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpPost.getURI().toString()); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new FoursquareParseException(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new FoursquareCredentialsException(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); } } /** * execute() an httpRequest catching exceptions and returning null instead. * * @param httpRequest * @return * @throws IOException */ public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException { if (DEBUG) LOG.log(Level.FINE, "executing HttpRequest for: " + httpRequest.getURI().toString()); try { mHttpClient.getConnectionManager().closeExpiredConnections(); return mHttpClient.execute(httpRequest); } catch (IOException e) { httpRequest.abort(); throw e; } } public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url); String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8); HttpGet httpGet = new HttpGet(url + "?" + query); httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI()); return httpGet; } public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpPost for: " + url); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion); try { httpPost.setEntity(new UrlEncodedFormEntity(stripNulls(nameValuePairs), HTTP.UTF_8)); } catch (UnsupportedEncodingException e1) { throw new IllegalArgumentException("Unable to encode http parameters."); } if (DEBUG) LOG.log(Level.FINE, "Created: " + httpPost); return httpPost; } public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(TIMEOUT * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); return conn; } private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (int i = 0; i < nameValuePairs.length; i++) { NameValuePair param = nameValuePairs[i]; if (param.getValue() != null) { if (DEBUG) LOG.log(Level.FINE, "Param: " + param); params.add(param); } } return params; } /** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); } /** * Create the default HTTP protocol parameters. */ private static final HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); return params; } }
1031868817-hws
main/src/com/joelapenna/foursquare/http/AbstractHttpApi.java
Java
asf20
10,639
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.signature.SignatureMethod; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApiWithOAuth extends AbstractHttpApi { protected static final Logger LOG = Logger.getLogger(HttpApiWithOAuth.class.getCanonicalName()); protected static final boolean DEBUG = Foursquare.DEBUG; private OAuthConsumer mConsumer; public HttpApiWithOAuth(DefaultHttpClient httpClient, String clientVersion) { super(httpClient, clientVersion); } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI()); try { if (DEBUG) LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI()); if (DEBUG) LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", " + mConsumer.getConsumerSecret()); if (DEBUG) LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", " + mConsumer.getTokenSecret()); mConsumer.sign(httpRequest); } catch (OAuthMessageSignerException e) { if (DEBUG) LOG.log(Level.FINE, "OAuthMessageSignerException", e); throw new RuntimeException(e); } catch (OAuthExpectationFailedException e) { if (DEBUG) LOG.log(Level.FINE, "OAuthExpectationFailedException", e); throw new RuntimeException(e); } return executeHttpRequest(httpRequest, parser); } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareError, FoursquareParseException, IOException, FoursquareCredentialsException { throw new RuntimeException("Haven't written this method yet."); } public void setOAuthConsumerCredentials(String key, String secret) { mConsumer = new CommonsHttpOAuthConsumer(key, secret, SignatureMethod.HMAC_SHA1); } public void setOAuthTokenWithSecret(String token, String tokenSecret) { verifyConsumer(); if (token == null && tokenSecret == null) { if (DEBUG) LOG.log(Level.FINE, "Resetting consumer due to null token/secret."); String consumerKey = mConsumer.getConsumerKey(); String consumerSecret = mConsumer.getConsumerSecret(); mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1); } else { mConsumer.setTokenWithSecret(token, tokenSecret); } } public boolean hasOAuthTokenWithSecret() { verifyConsumer(); return (mConsumer.getToken() != null) && (mConsumer.getTokenSecret() != null); } private void verifyConsumer() { if (mConsumer == null) { throw new IllegalStateException( "Cannot call method without setting consumer credentials."); } } }
1031868817-hws
main/src/com/joelapenna/foursquare/http/HttpApiWithOAuth.java
Java
asf20
4,071
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; /** * This is not ideal. * * @date July 1, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class IconUtils { private static IconUtils mInstance; private boolean mRequestHighDensityIcons; private IconUtils() { mRequestHighDensityIcons = false; } public static IconUtils get() { if (mInstance == null) { mInstance = new IconUtils(); } return mInstance; } public boolean getRequestHighDensityIcons() { return mRequestHighDensityIcons; } public void setRequestHighDensityIcons(boolean requestHighDensityIcons) { mRequestHighDensityIcons = requestHighDensityIcons; } }
1031868817-hws
main/src/com/joelapenna/foursquare/util/IconUtils.java
Java
asf20
791
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.util; import com.joelapenna.foursquare.types.Venue; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueUtils { public static final boolean isValid(Venue venue) { return !(venue == null || venue.getId() == null || venue.getId().length() == 0); } public static final boolean hasValidLocation(Venue venue) { boolean valid = false; if (venue != null) { String geoLat = venue.getGeolat(); String geoLong = venue.getGeolong(); if (!(geoLat == null || geoLat.length() == 0 || geoLong == null || geoLong.length() == 0)) { if (geoLat != "0" || geoLong != "0") { valid = true; } } } return valid; } }
1031868817-hws
main/src/com/joelapenna/foursquare/util/VenueUtils.java
Java
asf20
843
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; import android.os.Parcel; /** * @date March 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ParcelUtils { public static void writeStringToParcel(Parcel out, String str) { if (str != null) { out.writeInt(1); out.writeString(str); } else { out.writeInt(0); } } public static String readStringFromParcel(Parcel in) { int flag = in.readInt(); if (flag == 1) { return in.readString(); } else { return null; } } }
1031868817-hws
main/src/com/joelapenna/foursquare/util/ParcelUtils.java
Java
asf20
659
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.parsers.json.TipParser; import com.joelapenna.foursquare.types.FoursquareType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class JSONUtils { private static final boolean DEBUG = Foursquare.DEBUG; private static final Logger LOG = Logger.getLogger(TipParser.class.getCanonicalName()); /** * Takes a parser, a json string, and returns a foursquare type. */ public static FoursquareType consume(Parser<? extends FoursquareType> parser, String content) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) { LOG.log(Level.FINE, "http response: " + content); } try { // The v1 API returns the response raw with no wrapper. Depending on the // type of API call, the content might be a JSONObject or a JSONArray. // Since JSONArray does not derive from JSONObject, we need to check for // either of these cases to parse correctly. JSONObject json = new JSONObject(content); Iterator<String> it = (Iterator<String>)json.keys(); if (it.hasNext()) { String key = (String)it.next(); if (key.equals("error")) { throw new FoursquareException(json.getString(key)); } else { Object obj = json.get(key); if (obj instanceof JSONArray) { return parser.parse((JSONArray)obj); } else { return parser.parse((JSONObject)obj); } } } else { throw new FoursquareException("Error parsing JSON response, object had no single child key."); } } catch (JSONException ex) { throw new FoursquareException("Error parsing JSON response: " + ex.getMessage()); } } }
1031868817-hws
main/src/com/joelapenna/foursquare/util/JSONUtils.java
Java
asf20
2,556
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.util; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MayorUtils { public static final String TYPE_NOCHANGE = "nochange"; public static final String TYPE_NEW = "new"; public static final String TYPE_STOLEN = "stolen"; }
1031868817-hws
main/src/com/joelapenna/foursquare/util/MayorUtils.java
Java
asf20
325
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface FoursquareType { }
1031868817-hws
main/src/com/joelapenna/foursquare/types/FoursquareType.java
Java
asf20
169
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; /** * @date April 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Response implements FoursquareType { private String mValue; public Response() { } public String getValue() { return mValue; } public void setValue(String value) { mValue = value; } }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Response.java
Java
asf20
411
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * @date March 6, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Category implements FoursquareType, Parcelable { /** The category's id. */ private String mId; /** Full category path name, like Nightlife:Bars. */ private String mFullPathName; /** Simple name of the category. */ private String mNodeName; /** Url of the icon associated with this category. */ private String mIconUrl; /** Categories can be nested within one another too. */ private Group<Category> mChildCategories; public Category() { mChildCategories = new Group<Category>(); } private Category(Parcel in) { mChildCategories = new Group<Category>(); mId = ParcelUtils.readStringFromParcel(in); mFullPathName = ParcelUtils.readStringFromParcel(in); mNodeName = ParcelUtils.readStringFromParcel(in); mIconUrl = ParcelUtils.readStringFromParcel(in); int numCategories = in.readInt(); for (int i = 0; i < numCategories; i++) { Category category = in.readParcelable(Category.class.getClassLoader()); mChildCategories.add(category); } } public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { public Category createFromParcel(Parcel in) { return new Category(in); } @Override public Category[] newArray(int size) { return new Category[size]; } }; public String getId() { return mId; } public void setId(String id) { mId = id; } public String getFullPathName() { return mFullPathName; } public void setFullPathName(String fullPathName) { mFullPathName = fullPathName; } public String getNodeName() { return mNodeName; } public void setNodeName(String nodeName) { mNodeName = nodeName; } public String getIconUrl() { return mIconUrl; } public void setIconUrl(String iconUrl) { mIconUrl = iconUrl; } public Group<Category> getChildCategories() { return mChildCategories; } public void setChildCategories(Group<Category> categories) { mChildCategories = categories; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mId); ParcelUtils.writeStringToParcel(out, mFullPathName); ParcelUtils.writeStringToParcel(out, mNodeName); ParcelUtils.writeStringToParcel(out, mIconUrl); out.writeInt(mChildCategories.size()); for (Category it : mChildCategories) { out.writeParcelable(it, flags); } } @Override public int describeContents() { return 0; } }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Category.java
Java
asf20
3,059
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; /** * @date 2010-05-05 * @author Mark Wyszomierski (markww@gmail.com) */ public class FriendInvitesResult implements FoursquareType { /** * Users that are in our contact book by email or phone, are already on foursquare, * but are not our friends. */ private Group<User> mContactsOnFoursquare; /** * Users not on foursquare, but in our contact book by email or phone. These are * users we have not already sent an email invite to. */ private Emails mContactEmailsNotOnFoursquare; /** * A list of email addresses we've already sent email invites to. */ private Emails mContactEmailsNotOnFoursquareAlreadyInvited; public FriendInvitesResult() { mContactsOnFoursquare = new Group<User>(); mContactEmailsNotOnFoursquare = new Emails(); mContactEmailsNotOnFoursquareAlreadyInvited = new Emails(); } public Group<User> getContactsOnFoursquare() { return mContactsOnFoursquare; } public void setContactsOnFoursquare(Group<User> contactsOnFoursquare) { mContactsOnFoursquare = contactsOnFoursquare; } public Emails getContactEmailsNotOnFoursquare() { return mContactEmailsNotOnFoursquare; } public void setContactEmailsOnNotOnFoursquare(Emails emails) { mContactEmailsNotOnFoursquare = emails; } public Emails getContactEmailsNotOnFoursquareAlreadyInvited() { return mContactEmailsNotOnFoursquareAlreadyInvited; } public void setContactEmailsOnNotOnFoursquareAlreadyInvited(Emails emails) { mContactEmailsNotOnFoursquareAlreadyInvited = emails; } }
1031868817-hws
main/src/com/joelapenna/foursquare/types/FriendInvitesResult.java
Java
asf20
1,757
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Todo implements FoursquareType, Parcelable { private String mCreated; private String mId; private Tip mTip; public Todo() { } private Todo(Parcel in) { mCreated = ParcelUtils.readStringFromParcel(in); mId = ParcelUtils.readStringFromParcel(in); if (in.readInt() == 1) { mTip = in.readParcelable(Tip.class.getClassLoader()); } } public static final Parcelable.Creator<Todo> CREATOR = new Parcelable.Creator<Todo>() { public Todo createFromParcel(Parcel in) { return new Todo(in); } @Override public Todo[] newArray(int size) { return new Todo[size]; } }; public String getCreated() { return mCreated; } public void setCreated(String created) { mCreated = created; } public String getId() { return mId; } public void setId(String id) { mId = id; } public Tip getTip() { return mTip; } public void setTip(Tip tip) { mTip = tip; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mCreated); ParcelUtils.writeStringToParcel(out, mId); if (mTip != null) { out.writeInt(1); out.writeParcelable(mTip, flags); } else { out.writeInt(0); } } @Override public int describeContents() { return 0; } }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Todo.java
Java
asf20
1,818
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; /** * @date April 14, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Types extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Types.java
Java
asf20
319
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; import java.util.Collection; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Group<T extends FoursquareType> extends ArrayList<T> implements FoursquareType { private static final long serialVersionUID = 1L; private String mType; public Group() { super(); } public Group(Collection<T> collection) { super(collection); } public void setType(String type) { mType = type; } public String getType() { return mType; } }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Group.java
Java
asf20
627
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import java.util.ArrayList; /** * @date 2010-05-05 * @author Mark Wyszomierski (markww@gmail.com) */ public class Emails extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Emails.java
Java
asf20
322
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; import java.util.List; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Tags extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; public Tags() { super(); } public Tags(List<String> values) { super(); addAll(values); } }
1031868817-hws
main/src/com/joelapenna/foursquare/types/Tags.java
Java
asf20
452
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import android.net.Uri; import android.text.TextUtils; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Foursquare { private static final Logger LOG = Logger.getLogger("com.joelapenna.foursquare"); public static final boolean DEBUG = false; public static final boolean PARSER_DEBUG = false; public static final String FOURSQUARE_API_DOMAIN = "api.foursquare.com"; public static final String FOURSQUARE_MOBILE_ADDFRIENDS = "http://m.foursquare.com/addfriends"; public static final String FOURSQUARE_MOBILE_FRIENDS = "http://m.foursquare.com/friends"; public static final String FOURSQUARE_MOBILE_SIGNUP = "http://m.foursquare.com/signup"; public static final String FOURSQUARE_PREFERENCES = "http://foursquare.com/settings"; public static final String MALE = "male"; public static final String FEMALE = "female"; private String mPhone; private String mPassword; private FoursquareHttpApiV1 mFoursquareV1; @V1 public Foursquare(FoursquareHttpApiV1 httpApi) { mFoursquareV1 = httpApi; } public void setCredentials(String phone, String password) { mPhone = phone; mPassword = password; mFoursquareV1.setCredentials(phone, password); } @V1 public void setOAuthToken(String token, String secret) { mFoursquareV1.setOAuthTokenWithSecret(token, secret); } @V1 public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { mFoursquareV1.setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void clearAllCredentials() { setCredentials(null, null); setOAuthToken(null, null); } @V1 public boolean hasCredentials() { return mFoursquareV1.hasCredentials() && mFoursquareV1.hasOAuthTokenWithSecret(); } @V1 public boolean hasLoginAndPassword() { return mFoursquareV1.hasCredentials(); } @V1 public Credentials authExchange() throws FoursquareException, FoursquareError, FoursquareCredentialsException, IOException { if (mFoursquareV1 == null) { throw new NoSuchMethodError( "authExchange is unavailable without a consumer key/secret."); } return mFoursquareV1.authExchange(mPhone, mPassword); } @V1 public Tip addTip(String vid, String text, String type, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addtip(vid, text, type, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Tip tipDetail(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tipDetail(tid); } @V1 @LocationRequired public Venue addVenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addvenue(name, address, crossstreet, city, state, zip, phone, categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public CheckinResult checkin(String venueId, String venueName, Location location, String shout, boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkin(venueId, venueName, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, shout, isPrivate, tellFollowers, twitter, facebook); } @V1 public Group<Checkin> checkins(Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkins(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friends(String userId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friends(userId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friendRequests(); } @V1 public User friendApprove(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendApprove(userId); } @V1 public User friendDeny(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendDeny(userId); } @V1 public User friendSendrequest(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendSendrequest(userId); } @V1 public Group<Tip> tips(Location location, String uid, String filter, String sort, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tips(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, uid, filter, sort, limit); } @V1 public Group<Todo> todos(Location location, String uid, boolean recent, boolean nearby, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.todos(uid, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, recent, nearby, limit); } @V1 public User user(String user, boolean mayor, boolean badges, boolean stats, Location location) throws FoursquareException, FoursquareError, IOException { if (location != null) { return mFoursquareV1.user(user, mayor, badges, stats, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } else { return mFoursquareV1.user(user, mayor, badges, stats, null, null, null, null, null); } } @V1 public Venue venue(String id, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venue(id, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 @LocationRequired public Group<Group<Venue>> venues(Location location, String query, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venues(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, query, limit); } @V1 public Group<User> findFriendsByName(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByName(text); } @V1 public Group<User> findFriendsByPhone(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByPhone(text); } @V1 public Group<User> findFriendsByFacebook(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByFacebook(text); } @V1 public Group<User> findFriendsByTwitter(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByTwitter(text); } @V1 public Group<Category> categories() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.categories(); } @V1 public Group<Checkin> history(String limit, String sinceid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.history(limit, sinceid); } @V1 public Todo markTodo(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markTodo(tid); } @V1 public Todo markTodoVenue(String vid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markTodoVenue(vid); } @V1 public Tip markIgnore(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markIgnore(tid); } @V1 public Tip markDone(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markDone(tid); } @V1 public Tip unmarkTodo(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.unmarkTodo(tid); } @V1 public Tip unmarkDone(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.unmarkDone(tid); } @V1 public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.findFriendsByPhoneOrEmail(phones, emails); } @V1 public Response inviteByEmail(String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.inviteByEmail(emails); } @V1 public Settings setpings(boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.setpings(on); } @V1 public Settings setpings(String userid, boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.setpings(userid, on); } @V1 public Response flagclosed(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagclosed(venueid); } @V1 public Response flagmislocated(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagmislocated(venueid); } @V1 public Response flagduplicate(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagduplicate(venueid); } @V1 public Response proposeedit(String venueId, String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, Location location) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.proposeedit(venueId, name, address, crossstreet, city, state, zip, phone, categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public User userUpdate(String imagePathToJpg, String username, String password) throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException { return mFoursquareV1.userUpdate(imagePathToJpg, username, password); } public static final FoursquareHttpApiV1 createHttpApi(String domain, String clientVersion, boolean useOAuth) { LOG.log(Level.INFO, "Using foursquare.com for requests."); return new FoursquareHttpApiV1(domain, clientVersion, useOAuth); } public static final FoursquareHttpApiV1 createHttpApi(String clientVersion, boolean useOAuth) { return createHttpApi(FOURSQUARE_API_DOMAIN, clientVersion, useOAuth); } public static final String createLeaderboardUrl(String userId, Location location) { Uri.Builder builder = new Uri.Builder() // .scheme("http") // .authority("foursquare.com") // .appendEncodedPath("/iphone/me") // .appendQueryParameter("view", "all") // .appendQueryParameter("scope", "friends") // .appendQueryParameter("uid", userId); if (!TextUtils.isEmpty(location.geolat)) { builder.appendQueryParameter("geolat", location.geolat); } if (!TextUtils.isEmpty(location.geolong)) { builder.appendQueryParameter("geolong", location.geolong); } if (!TextUtils.isEmpty(location.geohacc)) { builder.appendQueryParameter("geohacc", location.geohacc); } if (!TextUtils.isEmpty(location.geovacc)) { builder.appendQueryParameter("geovacc", location.geovacc); } return builder.build().toString(); } /** * This api is supported in the V1 API documented at: * http://groups.google.com/group/foursquare-api/web/api-documentation */ @interface V1 { } /** * This api call requires a location. */ @interface LocationRequired { } public static class Location { String geolat = null; String geolong = null; String geohacc = null; String geovacc = null; String geoalt = null; public Location() { } public Location(final String geolat, final String geolong, final String geohacc, final String geovacc, final String geoalt) { this.geolat = geolat; this.geolong = geolong; this.geohacc = geohacc; this.geovacc = geovacc; this.geoalt = geovacc; } public Location(final String geolat, final String geolong) { this(geolat, geolong, null, null, null); } } }
1031868817-hws
main/src/com/joelapenna/foursquare/Foursquare.java
Java
asf20
15,243
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Checkin; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CheckinParser extends AbstractParser<Checkin> { @Override public Checkin parse(JSONObject json) throws JSONException { Checkin obj = new Checkin(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("display")) { obj.setDisplay(json.getString("display")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("ismayor")) { obj.setIsmayor(json.getBoolean("ismayor")); } if (json.has("ping")) { obj.setPing(json.getBoolean("ping")); } if (json.has("shout")) { obj.setShout(json.getString("shout")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/CheckinParser.java
Java
asf20
1,432
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Special; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SpecialParser extends AbstractParser<Special> { @Override public Special parse(JSONObject json) throws JSONException { Special obj = new Special(); if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("type")) { obj.setType(json.getString("type")); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/SpecialParser.java
Java
asf20
910
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Emails; import com.joelapenna.foursquare.types.FriendInvitesResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class FriendInvitesResultParser extends AbstractParser<FriendInvitesResult> { @Override public FriendInvitesResult parse(JSONObject json) throws JSONException { FriendInvitesResult obj = new FriendInvitesResult(); if (json.has("users")) { obj.setContactsOnFoursquare( new GroupParser( new UserParser()).parse(json.getJSONArray("users"))); } if (json.has("emails")) { Emails emails = new Emails(); if (json.optJSONObject("emails") != null) { JSONObject emailsAsObject = json.getJSONObject("emails"); emails.add(emailsAsObject.getString("email")); } else if (json.optJSONArray("emails") != null) { JSONArray emailsAsArray = json.getJSONArray("emails"); for (int i = 0; i < emailsAsArray.length(); i++) { emails.add(emailsAsArray.getString(i)); } } obj.setContactEmailsOnNotOnFoursquare(emails); } if (json.has("invited")) { Emails emails = new Emails(); JSONArray array = json.getJSONArray("invited"); for (int i = 0; i < array.length(); i++) { emails.add(array.getString(i)); } obj.setContactEmailsOnNotOnFoursquareAlreadyInvited(emails); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/FriendInvitesResultParser.java
Java
asf20
1,808
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Todo; import org.json.JSONException; import org.json.JSONObject; /** * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TodoParser extends AbstractParser<Todo> { @Override public Todo parse(JSONObject json) throws JSONException { Todo obj = new Todo(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("tip")) { obj.setTip(new TipParser().parse(json.getJSONObject("tip"))); } if (json.has("todoid")) { obj.setId(json.getString("todoid")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/TodoParser.java
Java
asf20
796
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public interface Parser<T extends FoursquareType> { public abstract T parse(JSONObject json) throws JSONException; public Group parse(JSONArray array) throws JSONException; }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/Parser.java
Java
asf20
546
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class StringArrayParser { public static List<String> parse(JSONArray json) throws JSONException { List<String> array = new ArrayList<String>(); for (int i = 0, m = json.length(); i < m; i++) { array.add(json.getString(i)); } return array; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/StringArrayParser.java
Java
asf20
599
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Stats; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class StatsParser extends AbstractParser<Stats> { @Override public Stats parse(JSONObject json) throws JSONException { Stats obj = new Stats(); if (json.has("beenhere")) { obj.setBeenhere(new BeenhereParser().parse(json.getJSONObject("beenhere"))); } if (json.has("checkins")) { obj.setCheckins(json.getString("checkins")); } if (json.has("herenow")) { obj.setHereNow(json.getString("herenow")); } if (json.has("mayor")) { obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/StatsParser.java
Java
asf20
956
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Settings; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SettingsParser extends AbstractParser<Settings> { @Override public Settings parse(JSONObject json) throws JSONException { Settings obj = new Settings(); if (json.has("feeds_key")) { obj.setFeedsKey(json.getString("feeds_key")); } if (json.has("get_pings")) { obj.setGetPings(json.getBoolean("get_pings")); } if (json.has("pings")) { obj.setPings(json.getString("pings")); } if (json.has("sendtofacebook")) { obj.setSendtofacebook(json.getBoolean("sendtofacebook")); } if (json.has("sendtotwitter")) { obj.setSendtotwitter(json.getBoolean("sendtotwitter")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/SettingsParser.java
Java
asf20
1,059
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Badge; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class BadgeParser extends AbstractParser<Badge> { @Override public Badge parse(JSONObject json) throws JSONException { Badge obj = new Badge(); if (json.has("description")) { obj.setDescription(json.getString("description")); } if (json.has("icon")) { obj.setIcon(json.getString("icon")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/BadgeParser.java
Java
asf20
878
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Beenhere; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class BeenhereParser extends AbstractParser<Beenhere> { @Override public Beenhere parse(JSONObject json) throws JSONException { Beenhere obj = new Beenhere(); if (json.has("friends")) { obj.setFriends(json.getBoolean("friends")); } if (json.has("me")) { obj.setMe(json.getBoolean("me")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/BeenhereParser.java
Java
asf20
697
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Response; import org.json.JSONException; import org.json.JSONObject; /** * @date April 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ResponseParser extends AbstractParser<Response> { @Override public Response parse(JSONObject json) throws JSONException { Response response = new Response(); response.setValue(json.getString("response")); return response; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/ResponseParser.java
Java
asf20
559
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public abstract class AbstractParser<T extends FoursquareType> implements Parser<T> { /** * All derived parsers must implement parsing a JSONObject instance of themselves. */ public abstract T parse(JSONObject json) throws JSONException; /** * Only the GroupParser needs to implement this. */ public Group parse(JSONArray array) throws JSONException { throw new JSONException("Unexpected JSONArray parse type encountered."); } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/AbstractParser.java
Java
asf20
903
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Tip; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TipParser extends AbstractParser<Tip> { @Override public Tip parse(JSONObject json) throws JSONException { Tip obj = new Tip(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("stats")) { obj.setStats(new TipParser.StatsParser().parse(json.getJSONObject("stats"))); } if (json.has("status")) { obj.setStatus(json.getString("status")); } if (json.has("text")) { obj.setText(json.getString("text")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } public static class StatsParser extends AbstractParser<Tip.Stats> { @Override public Tip.Stats parse(JSONObject json) throws JSONException { Tip.Stats stats = new Tip.Stats(); if (json.has("donecount")) { stats.setDoneCount(json.getInt("donecount")); } if (json.has("todocount")) { stats.setTodoCount(json.getInt("todocount")); } return stats; } } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/TipParser.java
Java
asf20
1,857
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Credentials; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CredentialsParser extends AbstractParser<Credentials> { @Override public Credentials parse(JSONObject json) throws JSONException { Credentials obj = new Credentials(); if (json.has("oauth_token")) { obj.setOauthToken(json.getString("oauth_token")); } if (json.has("oauth_token_secret")) { obj.setOauthTokenSecret(json.getString("oauth_token_secret")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/CredentialsParser.java
Java
asf20
771
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Data; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class DataParser extends AbstractParser<Data> { @Override public Data parse(JSONObject json) throws JSONException { Data obj = new Data(); if (json.has("cityid")) { obj.setCityid(json.getString("cityid")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("status")) { obj.setStatus("1".equals(json.getString("status"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/DataParser.java
Java
asf20
793
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.City; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CityParser extends AbstractParser<City> { @Override public City parse(JSONObject json) throws JSONException { City obj = new City(); if (json.has("geolat")) { obj.setGeolat(json.getString("geolat")); } if (json.has("geolong")) { obj.setGeolong(json.getString("geolong")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } if (json.has("shortname")) { obj.setShortname(json.getString("shortname")); } if (json.has("timezone")) { obj.setTimezone(json.getString("timezone")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/CityParser.java
Java
asf20
1,077
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Score; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class ScoreParser extends AbstractParser<Score> { @Override public Score parse(JSONObject json) throws JSONException { Score obj = new Score(); if (json.has("icon")) { obj.setIcon(json.getString("icon")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("points")) { obj.setPoints(json.getString("points")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/ScoreParser.java
Java
asf20
781
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; import java.util.logging.Level; /** * Reference: * http://www.json.org/javadoc/org/json/JSONObject.html * http://www.json.org/javadoc/org/json/JSONArray.html * * @author Mark Wyszomierski (markww@gmail.com) * @param <T> */ public class GroupParser extends AbstractParser<Group> { private Parser<? extends FoursquareType> mSubParser; public GroupParser(Parser<? extends FoursquareType> subParser) { mSubParser = subParser; } /** * When we encounter a JSONObject in a GroupParser, we expect one attribute * named 'type', and then another JSONArray attribute. */ public Group<FoursquareType> parse(JSONObject json) throws JSONException { Group<FoursquareType> group = new Group<FoursquareType>(); Iterator<String> it = (Iterator<String>)json.keys(); while (it.hasNext()) { String key = it.next(); if (key.equals("type")) { group.setType(json.getString(key)); } else { Object obj = json.get(key); if (obj instanceof JSONArray) { parse(group, (JSONArray)obj); } else { throw new JSONException("Could not parse data."); } } } return group; } /** * Here we are getting a straight JSONArray and do not expect the 'type' attribute. */ @Override public Group parse(JSONArray array) throws JSONException { Group<FoursquareType> group = new Group<FoursquareType>(); parse(group, array); return group; } private void parse(Group group, JSONArray array) throws JSONException { for (int i = 0, m = array.length(); i < m; i++) { Object element = array.get(i); FoursquareType item = null; if (element instanceof JSONArray) { item = mSubParser.parse((JSONArray)element); } else { item = mSubParser.parse((JSONObject)element); } group.add(item); } } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/GroupParser.java
Java
asf20
2,439
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Types; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TypesParser extends AbstractParser<Types> { @Override public Types parse(JSONObject json) throws JSONException { Types obj = new Types(); if (json.has("type")) { obj.add(json.getString("type")); } return obj; } public Types parseAsJSONArray(JSONArray array) throws JSONException { Types obj = new Types(); for (int i = 0, m = array.length(); i < m; i++) { obj.add(array.getString(i)); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/TypesParser.java
Java
asf20
858
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.User; import org.json.JSONException; import org.json.JSONObject; import java.util.logging.Level; import java.util.logging.Logger; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserParser extends AbstractParser<User> { @Override public User parse(JSONObject json) throws JSONException { User user = new User(); if (json.has("badges")) { user.setBadges( new GroupParser( new BadgeParser()).parse(json.getJSONArray("badges"))); } if (json.has("badgecount")) { user.setBadgeCount(json.getInt("badgecount")); } if (json.has("checkin")) { user.setCheckin(new CheckinParser().parse(json.getJSONObject("checkin"))); } if (json.has("checkincount")) { user.setCheckinCount(json.getInt("checkincount")); } if (json.has("created")) { user.setCreated(json.getString("created")); } if (json.has("email")) { user.setEmail(json.getString("email")); } if (json.has("facebook")) { user.setFacebook(json.getString("facebook")); } if (json.has("firstname")) { user.setFirstname(json.getString("firstname")); } if (json.has("followercount")) { user.setFollowerCount(json.getInt("followercount")); } if (json.has("friendcount")) { user.setFriendCount(json.getInt("friendcount")); } if (json.has("friendsincommon")) { user.setFriendsInCommon( new GroupParser( new UserParser()).parse(json.getJSONArray("friendsincommon"))); } if (json.has("friendstatus")) { user.setFriendstatus(json.getString("friendstatus")); } if (json.has("gender")) { user.setGender(json.getString("gender")); } if (json.has("hometown")) { user.setHometown(json.getString("hometown")); } if (json.has("id")) { user.setId(json.getString("id")); } if (json.has("lastname")) { user.setLastname(json.getString("lastname")); } if (json.has("mayor")) { user.setMayorships( new GroupParser( new VenueParser()).parse(json.getJSONArray("mayor"))); } if (json.has("mayorcount")) { user.setMayorCount(json.getInt("mayorcount")); } if (json.has("phone")) { user.setPhone(json.getString("phone")); } if (json.has("photo")) { user.setPhoto(json.getString("photo")); } if (json.has("settings")) { user.setSettings(new SettingsParser().parse(json.getJSONObject("settings"))); } if (json.has("tipcount")) { user.setTipCount(json.getInt("tipcount")); } if (json.has("todocount")) { user.setTodoCount(json.getInt("todocount")); } if (json.has("twitter")) { user.setTwitter(json.getString("twitter")); } if (json.has("types")) { user.setTypes(new TypesParser().parseAsJSONArray(json.getJSONArray("types"))); } return user; } //@Override //public String getObjectName() { // return "user"; //} }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/UserParser.java
Java
asf20
3,621
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Rank; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class RankParser extends AbstractParser<Rank> { @Override public Rank parse(JSONObject json) throws JSONException { Rank obj = new Rank(); if (json.has("city")) { obj.setCity(json.getString("city")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("position")) { obj.setPosition(json.getString("position")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/RankParser.java
Java
asf20
790
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Mayor; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class MayorParser extends AbstractParser<Mayor> { @Override public Mayor parse(JSONObject json) throws JSONException { Mayor obj = new Mayor(); if (json.has("checkins")) { obj.setCheckins(json.getString("checkins")); } if (json.has("count")) { obj.setCount(json.getString("count")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("type")) { obj.setType(json.getString("type")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/MayorParser.java
Java
asf20
1,023
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Tags; import com.joelapenna.foursquare.types.Venue; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class VenueParser extends AbstractParser<Venue> { @Override public Venue parse(JSONObject json) throws JSONException { Venue obj = new Venue(); if (json.has("address")) { obj.setAddress(json.getString("address")); } if (json.has("checkins")) { obj.setCheckins( new GroupParser( new CheckinParser()).parse(json.getJSONArray("checkins"))); } if (json.has("city")) { obj.setCity(json.getString("city")); } if (json.has("cityid")) { obj.setCityid(json.getString("cityid")); } if (json.has("crossstreet")) { obj.setCrossstreet(json.getString("crossstreet")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("geolat")) { obj.setGeolat(json.getString("geolat")); } if (json.has("geolong")) { obj.setGeolong(json.getString("geolong")); } if (json.has("hasTodo")) { obj.setHasTodo(json.getBoolean("hasTodo")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } if (json.has("phone")) { obj.setPhone(json.getString("phone")); } if (json.has("primarycategory")) { obj.setCategory(new CategoryParser().parse(json.getJSONObject("primarycategory"))); } if (json.has("specials")) { obj.setSpecials( new GroupParser( new SpecialParser()).parse(json.getJSONArray("specials"))); } if (json.has("state")) { obj.setState(json.getString("state")); } if (json.has("stats")) { obj.setStats(new StatsParser().parse(json.getJSONObject("stats"))); } if (json.has("tags")) { obj.setTags( new Tags(StringArrayParser.parse(json.getJSONArray("tags")))); } if (json.has("tips")) { obj.setTips( new GroupParser( new TipParser()).parse(json.getJSONArray("tips"))); } if (json.has("todos")) { obj.setTodos( new GroupParser( new TodoParser()).parse(json.getJSONArray("todos"))); } if (json.has("twitter")) { obj.setTwitter(json.getString("twitter")); } if (json.has("zip")) { obj.setZip(json.getString("zip")); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/VenueParser.java
Java
asf20
3,034
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.CheckinResult; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CheckinResultParser extends AbstractParser<CheckinResult> { @Override public CheckinResult parse(JSONObject json) throws JSONException { CheckinResult obj = new CheckinResult(); if (json.has("badges")) { obj.setBadges( new GroupParser( new BadgeParser()).parse(json.getJSONArray("badges"))); } if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("markup")) { obj.setMarkup(json.getString("markup")); } if (json.has("mayor")) { obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor"))); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("scores")) { obj.setScoring( new GroupParser( new ScoreParser()).parse(json.getJSONArray("scores"))); } if (json.has("specials")) { obj.setSpecials( new GroupParser( new SpecialParser()).parse(json.getJSONArray("specials"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/CheckinResultParser.java
Java
asf20
1,728
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.parsers.json.CategoryParser; import com.joelapenna.foursquare.parsers.json.GroupParser; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.util.IconUtils; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CategoryParser extends AbstractParser<Category> { @Override public Category parse(JSONObject json) throws JSONException { Category obj = new Category(); if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("fullpathname")) { obj.setFullPathName(json.getString("fullpathname")); } if (json.has("nodename")) { obj.setNodeName(json.getString("nodename")); } if (json.has("iconurl")) { // TODO: Remove this once api v2 allows icon request. String iconUrl = json.getString("iconurl"); if (IconUtils.get().getRequestHighDensityIcons()) { iconUrl = iconUrl.replace(".png", "_64.png"); } obj.setIconUrl(iconUrl); } if (json.has("categories")) { obj.setChildCategories( new GroupParser( new CategoryParser()).parse(json.getJSONArray("categories"))); } return obj; } }
1031868817-hws
main/src/com/joelapenna/foursquare/parsers/json/CategoryParser.java
Java
asf20
1,530
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.http.AbstractHttpApi; import com.joelapenna.foursquare.http.HttpApi; import com.joelapenna.foursquare.http.HttpApiWithBasicAuth; import com.joelapenna.foursquare.http.HttpApiWithOAuth; import com.joelapenna.foursquare.parsers.json.CategoryParser; import com.joelapenna.foursquare.parsers.json.CheckinParser; import com.joelapenna.foursquare.parsers.json.CheckinResultParser; import com.joelapenna.foursquare.parsers.json.CityParser; import com.joelapenna.foursquare.parsers.json.CredentialsParser; import com.joelapenna.foursquare.parsers.json.FriendInvitesResultParser; import com.joelapenna.foursquare.parsers.json.GroupParser; import com.joelapenna.foursquare.parsers.json.ResponseParser; import com.joelapenna.foursquare.parsers.json.SettingsParser; import com.joelapenna.foursquare.parsers.json.TipParser; import com.joelapenna.foursquare.parsers.json.TodoParser; import com.joelapenna.foursquare.parsers.json.UserParser; import com.joelapenna.foursquare.parsers.json.VenueParser; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.City; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.JSONUtils; import com.joelapenna.foursquared.util.Base64Coder; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ class FoursquareHttpApiV1 { private static final Logger LOG = Logger .getLogger(FoursquareHttpApiV1.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.DEBUG; private static final String DATATYPE = ".json"; private static final String URL_API_AUTHEXCHANGE = "/authexchange"; private static final String URL_API_ADDVENUE = "/addvenue"; private static final String URL_API_ADDTIP = "/addtip"; private static final String URL_API_CITIES = "/cities"; private static final String URL_API_CHECKINS = "/checkins"; private static final String URL_API_CHECKIN = "/checkin"; private static final String URL_API_USER = "/user"; private static final String URL_API_VENUE = "/venue"; private static final String URL_API_VENUES = "/venues"; private static final String URL_API_TIPS = "/tips"; private static final String URL_API_TODOS = "/todos"; private static final String URL_API_FRIEND_REQUESTS = "/friend/requests"; private static final String URL_API_FRIEND_APPROVE = "/friend/approve"; private static final String URL_API_FRIEND_DENY = "/friend/deny"; private static final String URL_API_FRIEND_SENDREQUEST = "/friend/sendrequest"; private static final String URL_API_FRIENDS = "/friends"; private static final String URL_API_FIND_FRIENDS_BY_NAME = "/findfriends/byname"; private static final String URL_API_FIND_FRIENDS_BY_PHONE = "/findfriends/byphone"; private static final String URL_API_FIND_FRIENDS_BY_FACEBOOK = "/findfriends/byfacebook"; private static final String URL_API_FIND_FRIENDS_BY_TWITTER = "/findfriends/bytwitter"; private static final String URL_API_CATEGORIES = "/categories"; private static final String URL_API_HISTORY = "/history"; private static final String URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL = "/findfriends/byphoneoremail"; private static final String URL_API_INVITE_BY_EMAIL = "/invite/byemail"; private static final String URL_API_SETPINGS = "/settings/setpings"; private static final String URL_API_VENUE_FLAG_CLOSED = "/venue/flagclosed"; private static final String URL_API_VENUE_FLAG_MISLOCATED = "/venue/flagmislocated"; private static final String URL_API_VENUE_FLAG_DUPLICATE = "/venue/flagduplicate"; private static final String URL_API_VENUE_PROPOSE_EDIT = "/venue/proposeedit"; private static final String URL_API_USER_UPDATE = "/user/update"; private static final String URL_API_MARK_TODO = "/mark/todo"; private static final String URL_API_MARK_IGNORE = "/mark/ignore"; private static final String URL_API_MARK_DONE = "/mark/done"; private static final String URL_API_UNMARK_TODO = "/unmark/todo"; private static final String URL_API_UNMARK_DONE = "/unmark/done"; private static final String URL_API_TIP_DETAIL = "/tip/detail"; private final DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient(); private HttpApi mHttpApi; private final String mApiBaseUrl; private final AuthScope mAuthScope; public FoursquareHttpApiV1(String domain, String clientVersion, boolean useOAuth) { mApiBaseUrl = "https://" + domain + "/v1"; mAuthScope = new AuthScope(domain, 80); if (useOAuth) { mHttpApi = new HttpApiWithOAuth(mHttpClient, clientVersion); } else { mHttpApi = new HttpApiWithBasicAuth(mHttpClient, clientVersion); } } void setCredentials(String phone, String password) { if (phone == null || phone.length() == 0 || password == null || password.length() == 0) { if (DEBUG) LOG.log(Level.FINE, "Clearing Credentials"); mHttpClient.getCredentialsProvider().clear(); } else { if (DEBUG) LOG.log(Level.FINE, "Setting Phone/Password: " + phone + "/******"); mHttpClient.getCredentialsProvider().setCredentials(mAuthScope, new UsernamePasswordCredentials(phone, password)); } } public boolean hasCredentials() { return mHttpClient.getCredentialsProvider().getCredentials(mAuthScope) != null; } public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { if (DEBUG) { LOG.log(Level.FINE, "Setting consumer key/secret: " + oAuthConsumerKey + " " + oAuthConsumerSecret); } ((HttpApiWithOAuth) mHttpApi).setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void setOAuthTokenWithSecret(String token, String secret) { if (DEBUG) LOG.log(Level.FINE, "Setting oauth token/secret: " + token + " " + secret); ((HttpApiWithOAuth) mHttpApi).setOAuthTokenWithSecret(token, secret); } public boolean hasOAuthTokenWithSecret() { return ((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret(); } /* * /authexchange?oauth_consumer_key=d123...a1bffb5&oauth_consumer_secret=fec... * 18 */ public Credentials authExchange(String phone, String password) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { if (((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret()) { throw new IllegalStateException("Cannot do authExchange with OAuthToken already set"); } HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_AUTHEXCHANGE), // new BasicNameValuePair("fs_username", phone), // new BasicNameValuePair("fs_password", password)); return (Credentials) mHttpApi.doHttpRequest(httpPost, new CredentialsParser()); } /* * /addtip?vid=1234&text=I%20added%20a%20tip&type=todo (type defaults "tip") */ Tip addtip(String vid, String text, String type, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDTIP), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("text", text), // new BasicNameValuePair("type", type), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * @param name the name of the venue * @param address the address of the venue (e.g., "202 1st Avenue") * @param crossstreet the cross streets (e.g., "btw Grand & Broome") * @param city the city name where this venue is * @param state the state where the city is * @param zip (optional) the ZIP code for the venue * @param phone (optional) the phone number for the venue * @return * @throws FoursquareException * @throws FoursquareCredentialsException * @throws FoursquareError * @throws IOException */ Venue addvenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDVENUE), // new BasicNameValuePair("name", name), // new BasicNameValuePair("address", address), // new BasicNameValuePair("crossstreet", crossstreet), // new BasicNameValuePair("city", city), // new BasicNameValuePair("state", state), // new BasicNameValuePair("zip", zip), // new BasicNameValuePair("phone", phone), // new BasicNameValuePair("primarycategoryid", categoryId), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Venue) mHttpApi.doHttpRequest(httpPost, new VenueParser()); } /* * /cities */ @SuppressWarnings("unchecked") Group<City> cities() throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CITIES)); return (Group<City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser())); } /* * /checkins? */ @SuppressWarnings("unchecked") Group<Checkin> checkins(String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CHECKINS), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt)); return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser())); } /* * /checkin?vid=1234&venue=Noc%20Noc&shout=Come%20here&private=0&twitter=1 */ CheckinResult checkin(String vid, String venue, String geolat, String geolong, String geohacc, String geovacc, String geoalt, String shout, boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_CHECKIN), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("venue", venue), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("shout", shout), // new BasicNameValuePair("private", (isPrivate) ? "1" : "0"), // new BasicNameValuePair("followers", (tellFollowers) ? "1" : "0"), // new BasicNameValuePair("twitter", (twitter) ? "1" : "0"), // new BasicNameValuePair("facebook", (facebook) ? "1" : "0"), // new BasicNameValuePair("markup", "android")); // used only by android for checkin result 'extras'. return (CheckinResult) mHttpApi.doHttpRequest(httpPost, new CheckinResultParser()); } /** * /user?uid=9937 */ User user(String uid, boolean mayor, boolean badges, boolean stats, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_USER), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("mayor", (mayor) ? "1" : "0"), // new BasicNameValuePair("badges", (badges) ? "1" : "0"), // new BasicNameValuePair("stats", (stats) ? "1" : "0"), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (User) mHttpApi.doHttpRequest(httpGet, new UserParser()); } /** * /venues?geolat=37.770900&geolong=-122.43698 */ @SuppressWarnings("unchecked") Group<Group<Venue>> venues(String geolat, String geolong, String geohacc, String geovacc, String geoalt, String query, int limit) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUES), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("q", query), // new BasicNameValuePair("l", String.valueOf(limit))); return (Group<Group<Venue>>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new GroupParser(new VenueParser()))); } /** * /venue?vid=1234 */ Venue venue(String vid, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUE), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Venue) mHttpApi.doHttpRequest(httpGet, new VenueParser()); } /** * /tips?geolat=37.770900&geolong=-122.436987&l=1 */ @SuppressWarnings("unchecked") Group<Tip> tips(String geolat, String geolong, String geohacc, String geovacc, String geoalt, String uid, String filter, String sort, int limit) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIPS), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("filter", filter), // new BasicNameValuePair("sort", sort), // new BasicNameValuePair("l", String.valueOf(limit)) // ); return (Group<Tip>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new TipParser())); } /** * /todos?geolat=37.770900&geolong=-122.436987&l=1&sort=[recent|nearby] */ @SuppressWarnings("unchecked") Group<Todo> todos(String uid, String geolat, String geolong, String geohacc, String geovacc, String geoalt, boolean recent, boolean nearby, int limit) throws FoursquareException, FoursquareError, IOException { String sort = null; if (recent) { sort = "recent"; } else if (nearby) { sort = "nearby"; } HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TODOS), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("sort", sort), // new BasicNameValuePair("l", String.valueOf(limit)) // ); return (Group<Todo>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new TodoParser())); } /* * /friends?uid=9937 */ @SuppressWarnings("unchecked") Group<User> friends(String uid, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIENDS), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /* * /friend/requests */ @SuppressWarnings("unchecked") Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIEND_REQUESTS)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /* * /friend/approve?uid=9937 */ User friendApprove(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_APPROVE), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /* * /friend/deny?uid=9937 */ User friendDeny(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_DENY), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /* * /friend/sendrequest?uid=9937 */ User friendSendrequest(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_SENDREQUEST), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /** * /findfriends/byname?q=john doe, mary smith */ @SuppressWarnings("unchecked") public Group<User> findFriendsByName(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_NAME), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /** * /findfriends/byphone?q=555-5555,555-5556 */ @SuppressWarnings("unchecked") public Group<User> findFriendsByPhone(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser())); } /** * /findfriends/byfacebook?q=friendid,friendid,friendid */ @SuppressWarnings("unchecked") public Group<User> findFriendsByFacebook(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_FACEBOOK), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser())); } /** * /findfriends/bytwitter?q=yourtwittername */ @SuppressWarnings("unchecked") public Group<User> findFriendsByTwitter(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_TWITTER), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /** * /categories */ @SuppressWarnings("unchecked") public Group<Category> categories() throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CATEGORIES)); return (Group<Category>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CategoryParser())); } /** * /history */ @SuppressWarnings("unchecked") public Group<Checkin> history(String limit, String sinceid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_HISTORY), new BasicNameValuePair("l", limit), new BasicNameValuePair("sinceid", sinceid)); return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser())); } /** * /mark/todo */ public Todo markTodo(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), // new BasicNameValuePair("tid", tid)); return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser()); } /** * This is a hacky special case, hopefully the api will be updated in v2 for this. * /mark/todo */ public Todo markTodoVenue(String vid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), // new BasicNameValuePair("vid", vid)); return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser()); } /** * /mark/ignore */ public Tip markIgnore(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_IGNORE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /mark/done */ public Tip markDone(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_DONE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /unmark/todo */ public Tip unmarkTodo(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_TODO), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /unmark/done */ public Tip unmarkDone(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_DONE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /tip/detail?tid=1234 */ public Tip tipDetail(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIP_DETAIL), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpGet, new TipParser()); } /** * /findfriends/byphoneoremail?p=comma-sep-list-of-phones&e=comma-sep-list-of-emails */ public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL), // new BasicNameValuePair("p", phones), new BasicNameValuePair("e", emails)); return (FriendInvitesResult) mHttpApi.doHttpRequest(httpPost, new FriendInvitesResultParser()); } /** * /invite/byemail?q=comma-sep-list-of-emails */ public Response inviteByEmail(String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_INVITE_BY_EMAIL), // new BasicNameValuePair("q", emails)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /settings/setpings?self=[on|off] */ public Settings setpings(boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), // new BasicNameValuePair("self", on ? "on" : "off")); return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser()); } /** * /settings/setpings?uid=userid */ public Settings setpings(String userid, boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), // new BasicNameValuePair(userid, on ? "on" : "off")); return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser()); } /** * /venue/flagclosed?vid=venueid */ public Response flagclosed(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_CLOSED), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/flagmislocated?vid=venueid */ public Response flagmislocated(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_MISLOCATED), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/flagduplicate?vid=venueid */ public Response flagduplicate(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_DUPLICATE), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/prposeedit?vid=venueid&name=... */ public Response proposeedit(String venueId, String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_PROPOSE_EDIT), // new BasicNameValuePair("vid", venueId), // new BasicNameValuePair("name", name), // new BasicNameValuePair("address", address), // new BasicNameValuePair("crossstreet", crossstreet), // new BasicNameValuePair("city", city), // new BasicNameValuePair("state", state), // new BasicNameValuePair("zip", zip), // new BasicNameValuePair("phone", phone), // new BasicNameValuePair("primarycategoryid", categoryId), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } private String fullUrl(String url) { return mApiBaseUrl + url + DATATYPE; } /** * /user/update * Need to bring this method under control like the rest of the api methods. Leaving it * in this state as authorization will probably switch from basic auth in the near future * anyway, will have to be updated. Also unlike the other methods, we're sending up data * which aren't basic name/value pairs. */ public User userUpdate(String imagePathToJpg, String username, String password) throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException { String BOUNDARY = "------------------319831265358979362846"; String lineEnd = "\r\n"; String twoHyphens = "--"; int maxBufferSize = 8192; File file = new File(imagePathToJpg); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(fullUrl(URL_API_USER_UPDATE)); HttpURLConnection conn = mHttpApi.createHttpURLConnectionPost(url, BOUNDARY); conn.setRequestProperty("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password)); // We are always saving the image to a jpg so we can use .jpg as the extension below. DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + BOUNDARY + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"image,jpeg\";filename=\"" + "image.jpeg" +"\"" + lineEnd); dos.writeBytes("Content-Type: " + "image/jpeg" + lineEnd); dos.writeBytes(lineEnd); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); int totalBytesRead = bytesRead; while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); totalBytesRead = totalBytesRead + bytesRead; } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd); fileInputStream.close(); dos.flush(); dos.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String responseLine = ""; while ((responseLine = in.readLine()) != null) { response.append(responseLine); } in.close(); try { return (User)JSONUtils.consume(new UserParser(), response.toString()); } catch (Exception ex) { throw new FoursquareParseException( "Error parsing user photo upload response, invalid json."); } } }
1031868817-hws
main/src/com/joelapenna/foursquare/FoursquareHttpApiV1.java
Java
asf20
35,320
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareParseException extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareParseException(String message) { super(message); } }
1031868817-hws
main/src/com/joelapenna/foursquare/error/FoursquareParseException.java
Java
asf20
341
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareError extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareError(String message) { super(message); } }
1031868817-hws
main/src/com/joelapenna/foursquare/error/FoursquareError.java
Java
asf20
324
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareCredentialsException extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareCredentialsException(String message) { super(message); } }
1031868817-hws
main/src/com/joelapenna/foursquare/error/FoursquareCredentialsException.java
Java
asf20
354
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareException extends Exception { private static final long serialVersionUID = 1L; private String mExtra; public FoursquareException(String message) { super(message); } public FoursquareException(String message, String extra) { super(message); mExtra = extra; } public String getExtra() { return mExtra; } }
1031868817-hws
main/src/com/joelapenna/foursquare/error/FoursquareException.java
Java
asf20
536
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.test; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.VenueActivity; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.SmallTest; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueActivityInstrumentationTestCase extends ActivityInstrumentationTestCase2<VenueActivity> { public VenueActivityInstrumentationTestCase() { super("com.joelapenna.foursquared", VenueActivity.class); } @SmallTest public void testOnCreate() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.putExtra(Foursquared.EXTRA_VENUE_ID, "40450"); setActivityIntent(intent); VenueActivity activity = getActivity(); activity.openOptionsMenu(); activity.closeOptionsMenu(); } }
1031868817-hws
tests/src/com/joelapenna/foursquared/test/VenueActivityInstrumentationTestCase.java
Java
asf20
944
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.test; import com.joelapenna.foursquared.Foursquared; import android.test.ApplicationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> { public FoursquaredAppTestCase() { super(Foursquared.class); } @MediumTest public void testLocationMethods() { createApplication(); getApplication().getLastKnownLocation(); getApplication().getLocationListener(); } @SmallTest public void testPreferences() { createApplication(); } }
1031868817-hws
tests/src/com/joelapenna/foursquared/test/FoursquaredAppTestCase.java
Java
asf20
770
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("WindowsApplication1")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("HP")> <Assembly: AssemblyProduct("WindowsApplication1")> <Assembly: AssemblyCopyright("Copyright © HP 2009")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("6334e458-f521-41fb-a97f-e21da2491033")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
12clip
branches/Clip12/Clip12/Clip12/Clip12/My Project/AssemblyInfo.vb
Visual Basic .NET
lgpl
1,195
Public Class Form1 Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vkey As Long) As Integer Dim clipboard1 As String = "clipboard1" 'strings to store clipboard information in Dim clipboard2 As String = "clipboard2" Dim clipboard3 As String = "clipboard3" Dim clipboard4 As String = "clipboard4" Dim clipboard5 As String = "clipboard5" Dim clipboard6 As String = "clipboard6" Dim clipboard7 As String = "clipboard7" Dim clipboard8 As String = "clipboard8" Dim clipboard9 As String = "clipboard9" Dim clipboard10 As String = "clipboard10" Dim clipboard11 As String = "clipboard11" Dim clipboard12 As String = "clipboard12" Dim vclip1 As Boolean = True 'Booleans to show whether a clipboard is active or not Dim vclip2 As Boolean = False 'Default clipboard is clipboard 1 Dim vclip3 As Boolean = False Dim vclip4 As Boolean = False Dim vclip5 As Boolean = False Dim vclip6 As Boolean = False Dim vclip7 As Boolean = False Dim vclip8 As Boolean = False Dim vclip9 As Boolean = False Dim vclip10 As Boolean = False Dim vclip11 As Boolean = False Dim vclip12 As Boolean = False Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Visible = False 'Hides all textboxes when the program launches TextBox2.Visible = False TextBox3.Visible = False TextBox4.Visible = False TextBox5.Visible = False TextBox6.Visible = False TextBox7.Visible = False TextBox8.Visible = False TextBox9.Visible = False TextBox10.Visible = False TextBox11.Visible = False TextBox12.Visible = False With Timer1 'Enables and sets the interval for the global hotkey timers .Enabled = True .Interval = 1 End With With Timer2 .Enabled = True .Interval = 1 End With With Timer3 .Enabled = True .Interval = 1 End With With Timer4 .Enabled = True .Interval = 1 End With With Timer5 .Enabled = True .Interval = 1 End With With Timer6 .Enabled = True .Interval = 1 End With With Timer7 .Enabled = True .Interval = 1 End With With Timer8 .Enabled = True .Interval = 1 End With With Timer9 .Enabled = True .Interval = 1 End With With Timer10 .Enabled = True .Interval = 1 End With With Timer11 .Enabled = True .Interval = 1 End With With Timer13 .Enabled = True .Interval = 1 End With With Timer14 .Enabled = True .Interval = 1 End With Clipboard.SetDataObject(clipboard1, True) End Sub Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click TextBox1.Visible = True 'Makes textbox unvisible (same to all other 12) End Sub Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem3.Click TextBox2.Visible = True End Sub Private Sub ToolStripMenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem4.Click TextBox3.Visible = True End Sub Private Sub ToolStripMenuItem5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem5.Click TextBox4.Visible = True End Sub Private Sub ToolStripMenuItem6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem6.Click TextBox5.Visible = True End Sub Private Sub ToolStripMenuItem7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem7.Click TextBox6.Visible = True End Sub Private Sub ToolStripMenuItem8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem8.Click TextBox7.Visible = True End Sub Private Sub ToolStripMenuItem9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem9.Click TextBox8.Visible = True End Sub Private Sub ToolStripMenuItem10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem10.Click TextBox9.Visible = True End Sub Private Sub ToolStripMenuItem11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem11.Click TextBox10.Visible = True End Sub Private Sub ToolStripMenuItem12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem12.Click TextBox11.Visible = True End Sub Private Sub ToolStripMenuItem13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem13.Click TextBox12.Visible = True End Sub Private Sub ShowAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowAllToolStripMenuItem.Click TextBox1.Visible = True 'Makes all textboxes visible TextBox2.Visible = True TextBox3.Visible = True TextBox4.Visible = True TextBox5.Visible = True TextBox6.Visible = True TextBox7.Visible = True TextBox8.Visible = True TextBox9.Visible = True TextBox10.Visible = True TextBox11.Visible = True TextBox12.Visible = True End Sub Private Sub QuitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitToolStripMenuItem.Click Me.Close() 'Closes the application End Sub Private Sub ToolStripMenuItem14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem14.Click TextBox1.Visible = False 'Makes textbox visible End Sub Private Sub ToolStripMenuItem15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem15.Click TextBox2.Visible = False End Sub Private Sub ToolStripMenuItem16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem16.Click TextBox3.Visible = False End Sub Private Sub ToolStripMenuItem17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem17.Click TextBox4.Visible = False End Sub Private Sub ToolStripMenuItem18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem18.Click TextBox5.Visible = False End Sub Private Sub ToolStripMenuItem19_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem19.Click TextBox6.Visible = False End Sub Private Sub ToolStripMenuItem20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem20.Click TextBox7.Visible = False End Sub Private Sub ToolStripMenuItem21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem21.Click TextBox8.Visible = False End Sub Private Sub ToolStripMenuItem22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem22.Click TextBox9.Visible = False End Sub Private Sub ToolStripMenuItem23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem23.Click TextBox10.Visible = False End Sub Private Sub ToolStripMenuItem24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem24.Click TextBox11.Visible = False End Sub Private Sub ToolStripMenuItem25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem25.Click TextBox12.Visible = False End Sub Private Sub HideAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HideAllToolStripMenuItem.Click TextBox1.Visible = False ' Makes all textboxes visible TextBox2.Visible = False TextBox3.Visible = False TextBox4.Visible = False TextBox5.Visible = False TextBox6.Visible = False TextBox7.Visible = False TextBox8.Visible = False TextBox9.Visible = False TextBox10.Visible = False TextBox11.Visible = False TextBox12.Visible = False End Sub Private Sub HideToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HideToolStripMenuItem.Click Me.Hide() 'This hides the window NotifyIcon1.Visible = True 'This makes the icon visible in the system tray End Sub Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick Me.Show() 'This shows the program when the tray icon is double clicked NotifyIcon1.Visible = False 'This removes the icon from the tray, this is optional as you may want to to stay in the tray End Sub Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click MsgBox("Info") 'Opens a messagebox End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 'Copy hotkey Dim ctrlkey As Boolean Dim c As Boolean ctrlkey = GetAsyncKeyState(Keys.ControlKey) c = GetAsyncKeyState(Keys.C) If ctrlkey And c = True Then Select Case vclip1 Case True 'code for when control + c is pushed TextBox1.Show() 'Show textbox1 clipboard1 = GetClipboardText() 'Goto GetClipboardText and save it as a string TextBox1.Text = clipboard1 'Cast string into TextBox1 Case False End Select Select Case vclip2 Case True 'code for when control + c is pushed TextBox2.Show() 'Show textbox2 to show it has a value clipboard2 = GetClipboardText() 'Goto GetClipboardText and save it as a string TextBox2.Text = clipboard2 'Cast string into TextBox2 Case False End Select Select Case vclip3 Case True TextBox3.Show() clipboard3 = GetClipboardText() Case False End Select Select Case vclip4 Case True TextBox4.Show() clipboard4 = GetClipboardText() Case False End Select Select Case vclip5 Case True TextBox5.Show() clipboard5 = GetClipboardText() Case False End Select Select Case vclip6 Case True TextBox6.Show() clipboard6 = GetClipboardText() Case False End Select Select Case vclip7 Case True TextBox7.Show() clipboard7 = GetClipboardText() Case False End Select Select Case vclip8 Case True TextBox8.Show() clipboard8 = GetClipboardText() Case False End Select Select Case vclip9 Case True TextBox9.Show() clipboard9 = GetClipboardText() Case False End Select Select Case vclip10 Case True TextBox10.Show() clipboard10 = GetClipboardText() Case False End Select Select Case vclip11 Case True TextBox11.Show() clipboard11 = GetClipboardText() Case False End Select Select Case vclip12 Case True TextBox12.Show() clipboard12 = GetClipboardText() Case False End Select End If End Sub Public Function GetClipboardText() As String 'Read clipboard and return clipboard as string Dim objClipboard As IDataObject = Clipboard.GetDataObject() With objClipboard If .GetDataPresent(DataFormats.Text) Then Return _ .GetData(DataFormats.Text) End With End Function Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 'Paste hotkey Dim ctrlkey As Boolean Dim v As Boolean ctrlkey = GetAsyncKeyState(Keys.ControlKey) v = GetAsyncKeyState(Keys.V) If ctrlkey And v = True Then Select Case vclip1 Case True 'If clipboard 1 is active, execute below code TextBox1.Show() 'Show textbox1 Clipboard.SetDataObject(clipboard1, True) 'Put the data stored in clipboard1 on the clipboard TextBox1.Text = clipboard1 'Cast string into TextBox1 Case False 'If clipboard 1 is not active, do nothing End Select Select Case vclip2 'If clipboard 2 is active, execute below code Case True TextBox2.Show() 'Show textbox2 Clipboard.SetDataObject(clipboard2, True) 'Put the data stored in clipboard1 on the clipboard TextBox2.Text = clipboard2 'Cast string into TextBox2 Case False 'If clipboard 2 is not active, do nothing End Select Select Case vclip3 Case True TextBox3.Show() Clipboard.SetDataObject(clipboard3, True) TextBox3.Text = clipboard3 Case False End Select Select Case vclip4 Case True TextBox4.Show() Clipboard.SetDataObject(clipboard4, True) TextBox4.Text = clipboard4 Case False End Select Select Case vclip5 Case True TextBox5.Show() Clipboard.SetDataObject(clipboard5, True) TextBox5.Text = clipboard5 Case False End Select Select Case vclip6 Case True TextBox6.Show() Clipboard.SetDataObject(clipboard6, True) TextBox6.Text = clipboard6 Case False End Select Select Case vclip7 Case True TextBox7.Show() Clipboard.SetDataObject(clipboard7, True) TextBox7.Text = clipboard7 Case False End Select Select Case vclip8 Case True TextBox8.Show() Clipboard.SetDataObject(clipboard8, True) TextBox8.Text = clipboard8 Case False End Select Select Case vclip9 Case True TextBox9.Show() Clipboard.SetDataObject(clipboard9, True) TextBox9.Text = clipboard9 Case False End Select Select Case vclip10 Case True TextBox10.Show() Clipboard.SetDataObject(clipboard10, True) TextBox10.Text = clipboard10 Case False End Select Select Case vclip11 Case True TextBox11.Show() Clipboard.SetDataObject(clipboard11, True) TextBox11.Text = clipboard11 Case False End Select Select Case vclip12 Case True TextBox12.Show() Clipboard.SetDataObject(clipboard12, True) TextBox12.Text = clipboard12 Case False End Select End If End Sub Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Dim altkey As Boolean Dim f1 As Boolean altkey = GetAsyncKeyState(Keys.Alt) f1 = GetAsyncKeyState(Keys.F1) If altkey And f1 = True Then vclip1 = True vclip2 = False vclip3 = False vclip4 = False vclip5 = False vclip6 = False vclip7 = False vclip8 = False vclip9 = False vclip10 = False vclip11 = False vclip12 = False End If End Sub Private Sub Timer4_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Dim altkey As Boolean Dim f2 As Boolean altkey = GetAsyncKeyState(Keys.Alt) f2 = GetAsyncKeyState(Keys.F2) If altkey And f2 = True Then vclip1 = False vclip2 = True vclip3 = False vclip4 = False vclip5 = False vclip6 = False vclip7 = False vclip8 = False vclip9 = False vclip10 = False vclip11 = False vclip12 = False End If End Sub End Class
12clip
branches/Clip12/Clip12/Clip12/Clip12/Form1.vb
Visual Basic .NET
lgpl
18,721
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("WindowsApplication1")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("HP")> <Assembly: AssemblyProduct("WindowsApplication1")> <Assembly: AssemblyCopyright("Copyright © HP 2009")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("6334e458-f521-41fb-a97f-e21da2491033")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
12clip
trunk/Clip12/Clip12/Clip12/My Project/AssemblyInfo.vb
Visual Basic .NET
lgpl
1,195
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Visible = False 'Hides all textboxes when the program launches TextBox2.Visible = False TextBox3.Visible = False TextBox4.Visible = False TextBox5.Visible = False TextBox6.Visible = False TextBox7.Visible = False TextBox8.Visible = False TextBox9.Visible = False TextBox10.Visible = False TextBox11.Visible = False TextBox12.Visible = False End Sub Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click TextBox1.Visible = True 'Makes textbox unvisible (same to all other 12) End Sub Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem3.Click TextBox2.Visible = True End Sub Private Sub ToolStripMenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem4.Click TextBox3.Visible = True End Sub Private Sub ToolStripMenuItem5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem5.Click TextBox4.Visible = True End Sub Private Sub ToolStripMenuItem6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem6.Click TextBox5.Visible = True End Sub Private Sub ToolStripMenuItem7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem7.Click TextBox6.Visible = True End Sub Private Sub ToolStripMenuItem8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem8.Click TextBox7.Visible = True End Sub Private Sub ToolStripMenuItem9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem9.Click TextBox8.Visible = True End Sub Private Sub ToolStripMenuItem10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem10.Click TextBox9.Visible = True End Sub Private Sub ToolStripMenuItem11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem11.Click TextBox10.Visible = True End Sub Private Sub ToolStripMenuItem12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem12.Click TextBox11.Visible = True End Sub Private Sub ToolStripMenuItem13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem13.Click TextBox12.Visible = True End Sub Private Sub ShowAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowAllToolStripMenuItem.Click TextBox1.Visible = True 'Makes all textboxes visible TextBox2.Visible = True TextBox3.Visible = True TextBox4.Visible = True TextBox5.Visible = True TextBox6.Visible = True TextBox7.Visible = True TextBox8.Visible = True TextBox9.Visible = True TextBox10.Visible = True TextBox11.Visible = True TextBox12.Visible = True End Sub Private Sub QuitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitToolStripMenuItem.Click Me.Close() 'Closes the application End Sub Private Sub ToolStripMenuItem14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem14.Click TextBox1.Visible = False 'Makes textbox visible End Sub Private Sub ToolStripMenuItem15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem15.Click TextBox2.Visible = False End Sub Private Sub ToolStripMenuItem16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem16.Click TextBox3.Visible = False End Sub Private Sub ToolStripMenuItem17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem17.Click TextBox4.Visible = False End Sub Private Sub ToolStripMenuItem18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem18.Click TextBox5.Visible = False End Sub Private Sub ToolStripMenuItem19_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem19.Click TextBox6.Visible = False End Sub Private Sub ToolStripMenuItem20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem20.Click TextBox7.Visible = False End Sub Private Sub ToolStripMenuItem21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem21.Click TextBox8.Visible = False End Sub Private Sub ToolStripMenuItem22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem22.Click TextBox9.Visible = False End Sub Private Sub ToolStripMenuItem23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem23.Click TextBox10.Visible = False End Sub Private Sub ToolStripMenuItem24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem24.Click TextBox11.Visible = False End Sub Private Sub ToolStripMenuItem25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem25.Click TextBox12.Visible = False End Sub Private Sub HideAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HideAllToolStripMenuItem.Click TextBox1.Visible = False ' Makes all textboxes visible TextBox2.Visible = False TextBox3.Visible = False TextBox4.Visible = False TextBox5.Visible = False TextBox6.Visible = False TextBox7.Visible = False TextBox8.Visible = False TextBox9.Visible = False TextBox10.Visible = False TextBox11.Visible = False TextBox12.Visible = False End Sub Private Sub HideToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HideToolStripMenuItem.Click Me.Hide() 'This hides the window NotifyIcon1.Visible = True 'This makes the icon visible in the system tray End Sub Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick Me.Show() 'This shows the program when the tray icon is double clicked NotifyIcon1.Visible = False 'This removes the icon from the tray, this is optional as you may want to to stay in the tray End Sub Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click MsgBox("Info") 'Opens a messagebox End Sub End Class
12clip
trunk/Clip12/Clip12/Clip12/Form1.vb
Visual Basic .NET
lgpl
7,403
// For an introduction to the Blank template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232509 (function () { "use strict"; WinJS.Binding.optimizeBindingReferences = true; var app = WinJS.Application; var activation = Windows.ApplicationModel.Activation; app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); } }; app.oncheckpoint = function (args) { // TODO: This application is about to be suspended. Save any state // that needs to persist across suspensions here. You might use the // WinJS.Application.sessionState object, which is automatically // saved and restored across suspension. If you need to complete an // asynchronous operation before your application is suspended, call // args.setPromise(). }; app.start(); })();
1000-km-test
trunk/hahahaaaaaa/js/default.js
JavaScript
asf20
1,394
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>hahahaaaaaa</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" /> <script src="//Microsoft.WinJS.1.0/js/base.js"></script> <script src="//Microsoft.WinJS.1.0/js/ui.js"></script> <!-- hahahaaaaaa references --> <link href="/css/default.css" rel="stylesheet" /> <script src="/js/default.js"></script> </head> <body> <p>Nong Ball have fan!1234dkjfdfdsfdsfakjdasf</p> </body> </html>
1000-km-test
trunk/hahahaaaaaa/default.html
HTML
asf20
557
body { } @media screen and (-ms-view-state: fullscreen-landscape) { } @media screen and (-ms-view-state: filled) { } @media screen and (-ms-view-state: snapped) { } @media screen and (-ms-view-state: fullscreen-portrait) { }
1000-km-test
trunk/hahahaaaaaa/css/default.css
CSS
asf20
246
AJAX_SUCCESS = false; var httpRequest = function( options ){ var default_options = { type : "GET", host : "", port : 80, uri : "/", useragent : "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US)", headers : "", getdata : "", postdata : "", resolveTimeout : 10000, connectTimeout : 10000, sendTimeout : 10000, receiveTimeout : 10000 } for( var key in options ){ if( options.hasOwnProperty(key) && ( key in default_options ) ){ default_options[key] = options[key]; } } return document.getElementById("simplehttpobj").http( default_options.type ,default_options.host ,default_options.port ,default_options.uri ,default_options.useragent ,default_options.headers ,default_options.getdata ,default_options.postdata ,default_options.resolveTimeout ,default_options.connectTimeout ,default_options.sendTimeout ,default_options.receiveTimeout ); } var ajax = function( url,handler ){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = handler; xhr.open("GET", url, true); xhr.send(null); ajax.abort = function(){xhr.abort();}; }; chrome.extension.onRequest.addListener(function( request,sender,sendResponse ){ if( request.action != "geturl" || !request.urloption ){ sendResponse({code:-1,message:"无效请求",data:null}); }else{ var response; var localHttpFailed = false; try{ console.log( "local request -> " + "http://"+request.urloption.host+request.urloption.uri+request.urloption.getdata ) response = httpRequest( request.urloption ); console.log( response ); }catch( err ){//dll出错 localHttpFailed = true; } if(/^\d+$/.test(response)){ localHttpFailed = true; } if(!localHttpFailed){//本地加载数据成功 try{ var jsonData = JSON.parse(response); sendResponse({code:0,message:"成功",data:jsonData}); }catch( err ){ sendResponse({code:-3,message:"数据解析失败",data:_this.status}); } }else{//从网络加载 var proxy = "http://hellohtml5.com/simple", url = "http://"+request.urloption.host+request.urloption.uri+request.urloption.getdata; request_url = proxy + "/" + url; console.log("ajax->"+request_url); ajax(request_url,function(){ var _this = this; if( _this.readyState == 4 && _this.status==200 ){ AJAX_SUCCESS = true; var responseText = _this.responseText.replace(/^[^\{]+/,'').replace(/[^\}]+$/,''); console.log(responseText); try{ var jsonData = JSON.parse(responseText); sendResponse({code:0,message:"成功",data:jsonData}); }catch( err ){ sendResponse({code:-3,message:"数据解析失败",data:_this.status}); } }else if( _this.readyState == 4 && _this.status != 200 ){ AJAX_SUCCESS = true; sendResponse({code:-2,message:"http状态错误",data:_this.status}); } }); setTimeout(function(){//20秒后发送超时消息 if(!AJAX_SUCCESS){ ajax.abort(); sendResponse({code:-5,message:"超时,请重试"}); } },20*1000); } } });
115jailbreak
trunk/scripts/background.js
JavaScript
asf20
4,622
(function(){ var downloadlinks = document.querySelector(".download-box > .btn-wrap"), hasdownloadlink = downloadlinks && downloadlinks.length > 0, pickcode = /https?:\/\/115\.com\/file\/([a-zA-Z0-9]+)/.exec(document.location.href), pickcode = pickcode ? pickcode[1] : null, CRLF = "\r\n"; if(/*!hasdownloadlink && */pickcode){ var mainWrapper = document.createElement("div"); var main = document.createElement("div"); var loading = document.createElement("div"); var loadingTitle = document.createElement("div"); var loadingStatus = document.createElement("div"); var loadingPicURL = chrome.extension.getURL("imgs/loading.gif"); var successPicURL = chrome.extension.getURL("imgs/success.png"); var failPicURL = chrome.extension.getURL("imgs/error.png"); var warningPicURL = chrome.extension.getURL("imgs/warning.png"); var closePicURL = chrome.extension.getURL("imgs/close.png"); //越狱相关函数 var jailbreakMessage = function( title,result ){ loadingTitle.innerHTML = title; loadingStatus.innerHTML = result; } var jailbreakSuccess = function( result ){ jailbreakMessage("越狱成功",result); loading.style.backgroundImage="url(\""+successPicURL+"\")"; showCloseBtn(); } var jailbreakFail = function( result ){ jailbreakMessage("越狱失败",result); loading.style.backgroundImage="url(\""+failPicURL+"\")"; showCloseBtn(); } var jailbreakWarning = function( result ){ jailbreakMessage("仍在进行",result); loading.style.backgroundImage="url(\""+warningPicURL+"\")"; showCloseBtn(); } var jailbreaking = function( status ){ jailbreakMessage("越狱中",status); } var showCloseBtn = function(){ var close = mydialog.getCloseBtn(); close.style.display="block"; close.style.opacity="0"; setTimeout(function(){ close.style.opacity="1"; },0); } var initCloseBtn = function(){ mydialog.getCloseBtn().style.backgroundImage="url(\""+closePicURL+"\")"; } mainWrapper.setAttribute( "style", "width:276px;height:132px;-webkit-border-radius:8px;background:-webkit-gradient(linear,left top,left bottom,from(#dfe1e7),to(#babfcb));border-top:1px solid #6b6b6b;border-left:1px solid #585858;border-bottom:1px solid #424242;border-right:1px solid #595959;-webkit-box-shadow:1px 1px 6px #000;"); main.setAttribute( "style", "width:270px;height:126px;position:relative;top:3px;left:3px;-webkit-border-radius:8px;background:#1c2c54;" ); main.setAttribute("class","dialogmain"); loading.setAttribute( "style", "width:100%;height:100%;font-family:'Microsoft YaHei';text-align:center;background:url('"+loadingPicURL+"') no-repeat 50% 75%" ); loadingTitle.setAttribute( "style", "width:100%;height:48px;line-height:48px;font-size:16px;color:#fff;" ); loadingStatus.setAttribute( "style", "width:100%;height:16px;line-height:16px;font-size:12px;color:#999;position:relative;top:-5px;" ); loading.appendChild(loadingTitle); loading.appendChild(loadingStatus); main.appendChild(loading); mainWrapper.appendChild(main); mydialog = new dialog(document.body,{contentdom:mainWrapper,modal:true}); mydialog.show(); initCloseBtn(); window.addEventListener("resize",function(){ mydialog.update(); },false); //获取实际下载链接地址 jailbreaking("请稍候..."); var responseReceived = false; // setTimeout(function(){//5秒正常时间超时提示 if(!responseReceived){ jailbreakWarning("超过正常需要的时间..."); } },5*1000); // chrome.extension.sendRequest({action:"geturl",urloption:{ host:"u.115.com", uri :"/?", headers : "Cookie: "+ "OOFL=115jailbreak; OOFA=%250D%250ETV_V%2508%250C%2506%2506%250D%2508W%250BZP%2540%255D%2507%250F%2503%2506%2507Q%2507TV%255CZXxBD%2519%2502%2509%250BX%2500%2505%2507%2505%2508Z%250FR%2506%2503%2508%250A%255E%255C%2509VUQ%2501%2504T%255D%2502%2504%250D%250B%2500%2504W%2505VWTTTS%2509U%2506%2507%2506%2506P" + CRLF + CRLF, getdata:"ct=upload_api&ac=get_pick_code_info&pickcode="+pickcode+"&version=1176", host: "uapi.115.com", useragent: "115UDownClient 2.1.11.126" }},function(response){ responseReceived = true; //开始处理 if( response.code != 0 ){ //插件内部错误 responseReceived = true; var errormessage = response.message || ""; errormessage += !!errormessage?",":""; errormessage += "请尝试<a href=\"https://chrome.google.com/extensions/detail/aiiloiffkhndoefjpciepoldngggnblb\">更新插件</a>或<a href=\"http://t.qq.com/mmplayer\">联系作者</a>解决"; jailbreakFail(errormessage); return; } //end if var response = response.data; var state = response.State || response.state; var message = response.Message || response.message; var urls = response.DownloadUrl; if( state && urls ){//成功 var download_html = "<div class=\"downloadlinks\">"; var ISPlist = ["电信下载","网通下载","备份下载"] for(var i=0,l=urls.length;i<l;i++){ download_html +="<a href=\""; download_html +=urls[i].Url; download_html +="\">"; download_html +=ISPlist[i]?ISPlist[i]:"其它下载"; download_html +="</a>"; } download_html+="</div>"; jailbreakSuccess(download_html); }else{//失败 jailbreakFail(message); } }); }//end if })();
115jailbreak
trunk/scripts/115file.js
JavaScript
asf20
6,277
/********************************************************** * Dialog Module * **********************************************************/ (function(){ var uid = 0;//dialog uid /******************Paper******************/ var paper = function( wrapper ){ var _this = this; _this.mask = document.createElement("div"); _this.wrapper = wrapper; //遮罩样式 _this.mask.setAttribute( "style","position:absolute;" + "width:100%;"+ "height:100%;"+ "left:0;"+ "top:0;"+ "z-index:99999;"+ "opacity:0;"+ "-webkit-user-select:none;"+ "background:black;"+ "-webkit-transition-property:opacity;"+ "-webkit-transition-duration:800ms;"); wrapper.appendChild(_this.mask); } paper.prototype = { show : function(){ this.mask.style.opacity = '.8'; }, hide : function(){ this.mask.style.opacity = '0'; }, remove : function(){ this.wrapper.removeChild(this.mask); }, setBackground : function( v ){ this.mask.style.background = v; }, setWidth : function( v ){ this.mask.style.width = v + 'px'; }, setHeight : function( v ){ this.mask.style.height = v + 'px'; }, addEventListener : function( eventname,handler,capture ){ this.mask.addEventListener(eventname,handler,capture); }, removeEventListener : function( eventname,handler,capture ){ this.mask.removeEventListener(eventname,handler,capture); } } /******************Content******************/ var content = function( wrapper ){ var _this = this; _this.container = document.createElement('div'); _this.wrapper = wrapper; _this.container.setAttribute( "style","position:absolute;"+ "background:white;"+ "opacity:1;"+ "z-index:100000;"+ //"-webkit-box-shadow:0px 0px 8px #333;"+ "-webkit-border-radius:15px;"+/*最大边角*/ "-webkit-transform:scale(0);"+ "-webkit-transform-origin:50% 50%;"+ "-webkit-transition-property:-webkit-transform,width,height;"+ "-webkit-transition-duration:300ms,700ms,700ms;"+ "-webkit-transition-delay:0ms,800ms,800ms;"+ "-webkit-user-select:none;"); var close = document.createElement("a"); close.setAttribute('style',"z-index:999999;display:block;position:absolute;width:29px;height:29px;overflow:hidden;display:none;-webkit-transition-property:opacity;-webkit-transition-duration:800ms;") close.setAttribute('href','javascirpt:;'); _this.close = close; _this.container.appendChild(_this.close); _this.wrapper.appendChild(_this.container); } content.prototype = { show : function(){ this.container.style.webkitTransform = "scale(1)"; }, hide : function(){ this.container.style.opacity = "0"; }, remove : function(){ this.wrapper.removeChild(this.container); }, setX : function(v){ this.container.style.left = v+"px"; }, setY : function(v){ this.container.style.top = v+"px"; }, setWidth : function(v){ this.container.style.width = v+"px"; }, setHeight : function(v){ this.container.style.height = v+"px"; }, addEventListener : function( eventname,handler,capture ){ this.container.addEventListener(eventname,handler,capture); }, getCloseBtn:function(){ return this.close; }, setContent: function(v){ if( v && v.nodeName ){ this.container.appendChild(v); }else{ alert('set dialog content failed.'); } } }; /******************Dialog******************/ var dialog = function( el,opts ){ var _this = this; el = el || document.body; _this.uid = ++uid; _this.baseElement = ( typeof el == 'object' && el.nodeName ) ? el : document.getElementById(el); _this.options = { modal : false, contentdom : document.createElement("div"), } if( "modal" in opts ){ _this.options.modal = opts.modal; } if( "contentdom" in opts ){ _this.options.contentdom = opts.contentdom; } _this.dPaper = new paper(_this.baseElement); _this.dContent = new content(_this.baseElement); _this.dContent.setContent(_this.options.contentdom); _this.update(); _this.dContent.getCloseBtn().onclick = function(){ _this.dispose(); } _this.dPaper.addEventListener("mouseup",_this,false); } dialog.prototype = { handleEvent : function(e){ switch(e.type){ case "mouseup": e.stopPropagation(); if(!!!this.options.modal){ this.dispose(); } break; } }, getCloseBtn : function(){ return this.dContent.getCloseBtn(); }, update : function(){ //content相对paper居中 var paperWidth = this.dPaper.mask.clientWidth, paperHeight = this.dPaper.mask.clientHeight, contentWidth = this.dContent.container.clientWidth, contentHeight = this.dContent.container.clientHeight; var r1 = paperWidth - 200; this.dPaper.setBackground("-webkit-gradient(radial, center center, "+ 0 +",center center, "+ r1 +", from(rgba(0,0,0,0)),color-stop(25%,rgba(0,0,0,.3)),to(rgba(0,0,0,1)))"); this.dContent.getCloseBtn().style.left=contentWidth-32/2+"px"; this.dContent.getCloseBtn().style.top=-24/2+"px"; this.dContent.setX((paperWidth-contentWidth)/2); this.dContent.setY((paperHeight-contentHeight)/2); }, show : function(){ var _this = this; setTimeout(function(){//动画效果必须放在timeout中,原因未知 _this.dPaper.show(); _this.dContent.show(); },0); }, dispose : function(){ var _this = this; this.dPaper.hide(); this.dContent.hide(); this.dPaper.addEventListener("webkitTransitionEnd",function(e){ _this.dPaper.remove(); _this.dPaper.removeEventListener("mouseup",_this,false); },false); this.dContent.addEventListener("webkitTransitionEnd",function(e){ _this.dContent.remove(); },false); } } window.dialog = dialog; })();
115jailbreak
trunk/scripts/lib/dialog.js
JavaScript
asf20
7,510
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="scripts/background.js"></script> </head> <body> <embed id="simplehttpobj" type="application/x-simplehttp"/> </body> </html>
115jailbreak
trunk/background.html
HTML
asf20
201
.dialogmain a{color:skyblue;} .dialogmain .downloadlinks a{display:inline-block;margin-left:8px;}
115jailbreak
trunk/css/115file.css
CSS
asf20
100
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.GraphCanvas; import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator; import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.TrackList; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentResolver; import android.content.Intent; import android.database.ContentObserver; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.ViewFlipper; /** * Display some calulations based on a track * * @version $Id$ * @author rene (c) Oct 19, 2009, Sogeti B.V. */ public class Statistics extends Activity implements StatisticsDelegate { private static final int DIALOG_GRAPHTYPE = 3; private static final int MENU_GRAPHTYPE = 11; private static final int MENU_TRACKLIST = 12; private static final int MENU_SHARE = 41; private static final String TRACKURI = "TRACKURI"; private static final String TAG = "OGT.Statistics"; private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private Uri mTrackUri = null; private boolean calculating; private TextView overallavgSpeedView; private TextView avgSpeedView; private TextView distanceView; private TextView endtimeView; private TextView starttimeView; private TextView maxSpeedView; private TextView waypointsView; private TextView mAscensionView; private TextView mElapsedTimeView; private UnitsI18n mUnits; private GraphCanvas mGraphTimeSpeed; private ViewFlipper mViewFlipper; private Animation mSlideLeftIn; private Animation mSlideLeftOut; private Animation mSlideRightIn; private Animation mSlideRightOut; private GestureDetector mGestureDetector; private GraphCanvas mGraphDistanceSpeed; private GraphCanvas mGraphTimeAltitude; private GraphCanvas mGraphDistanceAltitude; private final ContentObserver mTrackObserver = new ContentObserver( new Handler() ) { @Override public void onChange( boolean selfUpdate ) { if( !calculating ) { Statistics.this.drawTrackingStatistics(); } } }; private OnClickListener mGraphControlListener = new View.OnClickListener() { @Override public void onClick( View v ) { int id = v.getId(); switch( id ) { case R.id.graphtype_timespeed: mViewFlipper.setDisplayedChild( 0 ); break; case R.id.graphtype_distancespeed: mViewFlipper.setDisplayedChild( 1 ); break; case R.id.graphtype_timealtitude: mViewFlipper.setDisplayedChild( 2 ); break; case R.id.graphtype_distancealtitude: mViewFlipper.setDisplayedChild( 3 ); break; default: break; } dismissDialog( DIALOG_GRAPHTYPE ); } }; class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) { if( Math.abs( e1.getY() - e2.getY() ) > SWIPE_MAX_OFF_PATH ) return false; // right to left swipe if( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) { mViewFlipper.setInAnimation( mSlideLeftIn ); mViewFlipper.setOutAnimation( mSlideLeftOut ); mViewFlipper.showNext(); } else if( e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) { mViewFlipper.setInAnimation( mSlideRightIn ); mViewFlipper.setOutAnimation( mSlideRightOut ); mViewFlipper.showPrevious(); } return false; } } /** * Called when the activity is first created. */ @Override protected void onCreate( Bundle load ) { super.onCreate( load ); mUnits = new UnitsI18n( this, new UnitsI18n.UnitsChangeListener() { @Override public void onUnitsChange() { drawTrackingStatistics(); } } ); setContentView( R.layout.statistics ); mViewFlipper = (ViewFlipper) findViewById( R.id.flipper ); mViewFlipper.setDrawingCacheEnabled(true); mSlideLeftIn = AnimationUtils.loadAnimation( this, R.anim.slide_left_in ); mSlideLeftOut = AnimationUtils.loadAnimation( this, R.anim.slide_left_out ); mSlideRightIn = AnimationUtils.loadAnimation( this, R.anim.slide_right_in ); mSlideRightOut = AnimationUtils.loadAnimation( this, R.anim.slide_right_out ); mGraphTimeSpeed = (GraphCanvas) mViewFlipper.getChildAt( 0 ); mGraphDistanceSpeed = (GraphCanvas) mViewFlipper.getChildAt( 1 ); mGraphTimeAltitude = (GraphCanvas) mViewFlipper.getChildAt( 2 ); mGraphDistanceAltitude = (GraphCanvas) mViewFlipper.getChildAt( 3 ); mGraphTimeSpeed.setType( GraphCanvas.TIMESPEEDGRAPH ); mGraphDistanceSpeed.setType( GraphCanvas.DISTANCESPEEDGRAPH ); mGraphTimeAltitude.setType( GraphCanvas.TIMEALTITUDEGRAPH ); mGraphDistanceAltitude.setType( GraphCanvas.DISTANCEALTITUDEGRAPH ); mGestureDetector = new GestureDetector( new MyGestureDetector() ); maxSpeedView = (TextView) findViewById( R.id.stat_maximumspeed ); mAscensionView = (TextView) findViewById( R.id.stat_ascension ); mElapsedTimeView = (TextView) findViewById( R.id.stat_elapsedtime ); overallavgSpeedView = (TextView) findViewById( R.id.stat_overallaveragespeed ); avgSpeedView = (TextView) findViewById( R.id.stat_averagespeed ); distanceView = (TextView) findViewById( R.id.stat_distance ); starttimeView = (TextView) findViewById( R.id.stat_starttime ); endtimeView = (TextView) findViewById( R.id.stat_endtime ); waypointsView = (TextView) findViewById( R.id.stat_waypoints ); if( load != null && load.containsKey( TRACKURI ) ) { mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) ); } else { mTrackUri = this.getIntent().getData(); } } @Override protected void onRestoreInstanceState( Bundle load ) { if( load != null ) { super.onRestoreInstanceState( load ); } if( load != null && load.containsKey( TRACKURI ) ) { mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) ); } if( load != null && load.containsKey( "FLIP" ) ) { mViewFlipper.setDisplayedChild( load.getInt( "FLIP" ) ); } } @Override protected void onSaveInstanceState( Bundle save ) { super.onSaveInstanceState( save ); save.putString( TRACKURI, mTrackUri.getLastPathSegment() ); save.putInt( "FLIP" , mViewFlipper.getDisplayedChild() ); } /* * (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); mViewFlipper.stopFlipping(); mGraphTimeSpeed.clearData(); mGraphDistanceSpeed.clearData(); mGraphTimeAltitude.clearData(); mGraphDistanceAltitude.clearData(); ContentResolver resolver = this.getContentResolver(); resolver.unregisterContentObserver( this.mTrackObserver ); } /* * (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); drawTrackingStatistics(); ContentResolver resolver = this.getContentResolver(); resolver.registerContentObserver( mTrackUri, true, this.mTrackObserver ); } @Override public boolean onCreateOptionsMenu( Menu menu ) { boolean result = super.onCreateOptionsMenu( menu ); menu.add( ContextMenu.NONE, MENU_GRAPHTYPE, ContextMenu.NONE, R.string.menu_graphtype ).setIcon( R.drawable.ic_menu_picture ).setAlphabeticShortcut( 't' ); menu.add( ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist ).setIcon( R.drawable.ic_menu_show_list ).setAlphabeticShortcut( 'l' ); menu.add( ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack ).setIcon( R.drawable.ic_menu_share ).setAlphabeticShortcut( 's' ); return result; } @Override public boolean onOptionsItemSelected( MenuItem item ) { boolean handled = false; Intent intent; switch( item.getItemId() ) { case MENU_GRAPHTYPE: showDialog( DIALOG_GRAPHTYPE ); handled = true; break; case MENU_TRACKLIST: intent = new Intent( this, TrackList.class ); intent.putExtra( Tracks._ID, mTrackUri.getLastPathSegment() ); startActivityForResult( intent, MENU_TRACKLIST ); break; case MENU_SHARE: intent = new Intent( Intent.ACTION_RUN ); intent.setDataAndType( mTrackUri, Tracks.CONTENT_ITEM_TYPE ); intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION ); Bitmap bm = mViewFlipper.getDrawingCache(); Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm); intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri); startActivityForResult(Intent.createChooser( intent, getString( R.string.share_track ) ), MENU_SHARE); handled = true; break; default: handled = super.onOptionsItemSelected( item ); } return handled; } @Override public boolean onTouchEvent( MotionEvent event ) { if( mGestureDetector.onTouchEvent( event ) ) return true; else return false; } /* * (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult( int requestCode, int resultCode, Intent intent ) { super.onActivityResult( requestCode, resultCode, intent ); switch( requestCode ) { case MENU_TRACKLIST: if( resultCode == RESULT_OK ) { mTrackUri = intent.getData(); drawTrackingStatistics(); } break; case MENU_SHARE: ShareTrack.clearScreenBitmap(); break; default: Log.w( TAG, "Unknown activity result request code" ); } } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch( id ) { case DIALOG_GRAPHTYPE: builder = new AlertDialog.Builder( this ); factory = LayoutInflater.from( this ); view = factory.inflate( R.layout.graphtype, null ); builder.setTitle( R.string.dialog_graphtype_title ).setIcon( android.R.drawable.ic_dialog_alert ).setNegativeButton( R.string.btn_cancel, null ).setView( view ); dialog = builder.create(); return dialog; default: return super.onCreateDialog( id ); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog( int id, Dialog dialog ) { switch( id ) { case DIALOG_GRAPHTYPE: Button speedtime = (Button) dialog.findViewById( R.id.graphtype_timespeed ); Button speeddistance = (Button) dialog.findViewById( R.id.graphtype_distancespeed ); Button altitudetime = (Button) dialog.findViewById( R.id.graphtype_timealtitude ); Button altitudedistance = (Button) dialog.findViewById( R.id.graphtype_distancealtitude ); speedtime.setOnClickListener( mGraphControlListener ); speeddistance.setOnClickListener( mGraphControlListener ); altitudetime.setOnClickListener( mGraphControlListener ); altitudedistance.setOnClickListener( mGraphControlListener ); default: break; } super.onPrepareDialog( id, dialog ); } private void drawTrackingStatistics() { calculating = true; StatisticsCalulator calculator = new StatisticsCalulator( this, mUnits, this ); calculator.execute(mTrackUri); } @Override public void finishedCalculations(StatisticsCalulator calculated) { mGraphTimeSpeed.setData ( mTrackUri, calculated ); mGraphDistanceSpeed.setData ( mTrackUri, calculated ); mGraphTimeAltitude.setData ( mTrackUri, calculated ); mGraphDistanceAltitude.setData( mTrackUri, calculated ); mViewFlipper.postInvalidate(); maxSpeedView.setText( calculated.getMaxSpeedText() ); mElapsedTimeView.setText( calculated.getDurationText() ); mAscensionView.setText( calculated.getAscensionText() ); overallavgSpeedView.setText( calculated.getOverallavgSpeedText() ); avgSpeedView.setText( calculated.getAvgSpeedText() ); distanceView.setText( calculated.getDistanceText() ); starttimeView.setText( Long.toString( calculated.getStarttime() ) ); endtimeView.setText( Long.toString( calculated.getEndtime() ) ); String titleFormat = getString( R.string.stat_title ); setTitle( String.format( titleFormat, calculated.getTracknameText() ) ); waypointsView.setText( calculated.getWaypointsText() ); calculating = false; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/Statistics.java
Java
gpl3
16,232
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.util.Calendar; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; /** * Empty Activity that pops up the dialog to name the track * * @version $Id$ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class NameTrack extends Activity { private static final int DIALOG_TRACKNAME = 23; protected static final String TAG = "OGT.NameTrack"; private EditText mTrackNameView; private boolean paused; Uri mTrackUri; private final DialogInterface.OnClickListener mTrackNameDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { String trackName = null; switch( which ) { case DialogInterface.BUTTON_POSITIVE: trackName = mTrackNameView.getText().toString(); ContentValues values = new ContentValues(); values.put( Tracks.NAME, trackName ); getContentResolver().update( mTrackUri, values, null, null ); clearNotification(); break; case DialogInterface.BUTTON_NEUTRAL: startDelayNotification(); break; case DialogInterface.BUTTON_NEGATIVE: clearNotification(); break; default: Log.e( TAG, "Unknown option ending dialog:"+which ); break; } finish(); } }; private void clearNotification() { NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );; noticationManager.cancel( R.layout.namedialog ); } private void startDelayNotification() { int resId = R.string.dialog_routename_title; int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString( resId ); long when = System.currentTimeMillis(); Notification nameNotification = new Notification( icon, tickerText, when ); nameNotification.flags |= Notification.FLAG_AUTO_CANCEL; CharSequence contentTitle = getResources().getString( R.string.app_name ); CharSequence contentText = getResources().getString( resId ); Intent notificationIntent = new Intent( this, NameTrack.class ); notificationIntent.setData( mTrackUri ); PendingIntent contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK ); nameNotification.setLatestEventInfo( this, contentTitle, contentText, contentIntent ); NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE ); noticationManager.notify( R.layout.namedialog, nameNotification ); } @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.setVisible( false ); paused = false; mTrackUri = this.getIntent().getData(); } @Override protected void onPause() { super.onPause(); paused = true; } /* * (non-Javadoc) * @see com.google.android.maps.MapActivity#onPause() */ @Override protected void onResume() { super.onResume(); if( mTrackUri != null ) { showDialog( DIALOG_TRACKNAME ); } else { Log.e(TAG, "Naming track without a track URI supplied." ); finish(); } } @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_TRACKNAME: builder = new AlertDialog.Builder( this ); factory = LayoutInflater.from( this ); view = factory.inflate( R.layout.namedialog, null ); mTrackNameView = (EditText) view.findViewById( R.id.nameField ); builder .setTitle( R.string.dialog_routename_title ) .setMessage( R.string.dialog_routename_message ) .setIcon( android.R.drawable.ic_dialog_alert ) .setPositiveButton( R.string.btn_okay, mTrackNameDialogListener ) .setNeutralButton( R.string.btn_skip, mTrackNameDialogListener ) .setNegativeButton( R.string.btn_cancel, mTrackNameDialogListener ) .setView( view ); dialog = builder.create(); dialog.setOnDismissListener( new OnDismissListener() { @Override public void onDismiss( DialogInterface dialog ) { if( !paused ) { finish(); } } }); return dialog; default: return super.onCreateDialog( id ); } } @Override protected void onPrepareDialog( int id, Dialog dialog ) { switch (id) { case DIALOG_TRACKNAME: String trackName; Calendar c = Calendar.getInstance(); trackName = String.format( getString( R.string.dialog_routename_default ), c, c, c, c, c ); mTrackNameView.setText( trackName ); mTrackNameView.setSelection( 0, trackName.length() ); break; default: super.onPrepareDialog( id, dialog ); break; } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/NameTrack.java
Java
gpl3
7,765
package nl.sogeti.android.gpstracker.actions.utils; public interface StatisticsDelegate { void finishedCalculations(StatisticsCalulator calculated); }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/StatisticsDelegate.java
Java
gpl3
154
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import android.app.Activity; import android.net.Uri; /** * Interface to which a Activity / Context can conform to receive progress * updates from async tasks * * @version $Id:$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public interface ProgressListener { void setIndeterminate(boolean indeterminate); /** * Signifies the start of background task, will be followed by setProgress(int) calls. */ void started(); /** * Set the progress on the scale of 0...10000 * * @param value * * @see Activity.setProgress * @see Window.PROGRESS_END */ void setProgress(int value); /** * Signifies end of background task and the location of the result * * @param result */ void finished(Uri result); void showError(String task, String errorMessage, Exception exception); }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/ProgressListener.java
Java
gpl3
2,432
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; public class StatisticsCalulator extends AsyncTask<Uri, Void, Void> { @SuppressWarnings("unused") private static final String TAG = "OGT.StatisticsCalulator"; private Context mContext; private String overallavgSpeedText = "Unknown"; private String avgSpeedText = "Unknown"; private String maxSpeedText = "Unknown"; private String ascensionText = "Unknown"; private String minSpeedText = "Unknown"; private String tracknameText = "Unknown"; private String waypointsText = "Unknown"; private String distanceText = "Unknown"; private long mStarttime = -1; private long mEndtime = -1; private UnitsI18n mUnits; private double mMaxSpeed; private double mMaxAltitude; private double mMinAltitude; private double mAscension; private double mDistanceTraveled; private long mDuration; private double mAverageActiveSpeed; private StatisticsDelegate mDelegate; public StatisticsCalulator( Context ctx, UnitsI18n units, StatisticsDelegate delegate ) { mContext = ctx; mUnits = units; mDelegate = delegate; } private void updateCalculations( Uri trackUri ) { mStarttime = -1; mEndtime = -1; mMaxSpeed = 0; mAverageActiveSpeed = 0; mMaxAltitude = 0; mMinAltitude = 0; mAscension = 0; mDistanceTraveled = 0f; mDuration = 0; long duration = 1; double ascension = 0; ContentResolver resolver = mContext.getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query( Uri.withAppendedPath( trackUri, "waypoints" ), new String[] { "max (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")" , "max (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")" , "min (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")" , "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null ); if( waypointsCursor.moveToLast() ) { mMaxSpeed = waypointsCursor.getDouble( 0 ); mMaxAltitude = waypointsCursor.getDouble( 1 ); mMinAltitude = waypointsCursor.getDouble( 2 ); long nrWaypoints = waypointsCursor.getLong( 3 ); waypointsText = nrWaypoints + ""; } waypointsCursor.close(); waypointsCursor = resolver.query( Uri.withAppendedPath( trackUri, "waypoints" ), new String[] { "avg (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")" }, Waypoints.TABLE + "." + Waypoints.SPEED +" > ?", new String[] { ""+Constants.MIN_STATISTICS_SPEED }, null ); if( waypointsCursor.moveToLast() ) { mAverageActiveSpeed = waypointsCursor.getDouble( 0 ); } } finally { if( waypointsCursor != null ) { waypointsCursor.close(); } } Cursor trackCursor = null; try { trackCursor = resolver.query( trackUri, new String[] { Tracks.NAME }, null, null, null ); if( trackCursor.moveToLast() ) { tracknameText = trackCursor.getString( 0 ); } } finally { if( trackCursor != null ) { trackCursor.close(); } } Cursor segments = null; Location lastLocation = null; Location lastAltitudeLocation = null; Location currentLocation = null; try { Uri segmentsUri = Uri.withAppendedPath( trackUri, "segments" ); segments = resolver.query( segmentsUri, new String[] { Segments._ID }, null, null, null ); if( segments.moveToFirst() ) { do { long segmentsId = segments.getLong( 0 ); Cursor waypoints = null; try { Uri waypointsUri = Uri.withAppendedPath( segmentsUri, segmentsId + "/waypoints" ); waypoints = resolver.query( waypointsUri, new String[] { Waypoints._ID, Waypoints.TIME, Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null ); if( waypoints.moveToFirst() ) { do { if( mStarttime < 0 ) { mStarttime = waypoints.getLong( 1 ); } currentLocation = new Location( this.getClass().getName() ); currentLocation.setTime( waypoints.getLong( 1 ) ); currentLocation.setLongitude( waypoints.getDouble( 2 ) ); currentLocation.setLatitude( waypoints.getDouble( 3 ) ); currentLocation.setAltitude( waypoints.getDouble( 4 ) ); // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop if( currentLocation.getLatitude() == 0.0d || currentLocation.getLongitude() == 0.0d ) { continue; } if( lastLocation != null ) { float travelPart = lastLocation.distanceTo( currentLocation ); long timePart = currentLocation.getTime() - lastLocation.getTime(); mDistanceTraveled += travelPart; duration += timePart; } if( currentLocation.hasAltitude() ) { if( lastAltitudeLocation != null ) { if( currentLocation.getTime() - lastAltitudeLocation.getTime() > 5*60*1000 ) // more then a 5m of climbing { if( currentLocation.getAltitude() > lastAltitudeLocation.getAltitude()+1 ) // more then 1m climb { ascension += currentLocation.getAltitude() - lastAltitudeLocation.getAltitude(); lastAltitudeLocation = currentLocation; } else { lastAltitudeLocation = currentLocation; } } } else { lastAltitudeLocation = currentLocation; } } lastLocation = currentLocation; mEndtime = lastLocation.getTime(); } while( waypoints.moveToNext() ); mDuration = mEndtime - mStarttime; } } finally { if( waypoints != null ) { waypoints.close(); } } lastLocation = null; } while( segments.moveToNext() ); } } finally { if( segments != null ) { segments.close(); } } double maxSpeed = mUnits.conversionFromMetersPerSecond( mMaxSpeed ); double overallavgSpeedfl = mUnits.conversionFromMeterAndMiliseconds( mDistanceTraveled, mDuration ); double avgSpeedfl = mUnits.conversionFromMeterAndMiliseconds( mDistanceTraveled, duration ); double traveled = mUnits.conversionFromMeter( mDistanceTraveled ); avgSpeedText = mUnits.formatSpeed( avgSpeedfl, true ); overallavgSpeedText = mUnits.formatSpeed( overallavgSpeedfl, true ); maxSpeedText = mUnits.formatSpeed( maxSpeed, true ); distanceText = String.format( "%.2f %s", traveled, mUnits.getDistanceUnit() ); ascensionText = String.format( "%.0f %s", ascension, mUnits.getHeightUnit() ); } /** * Get the overallavgSpeedText. * * @return Returns the overallavgSpeedText as a String. */ public String getOverallavgSpeedText() { return overallavgSpeedText; } /** * Get the avgSpeedText. * * @return Returns the avgSpeedText as a String. */ public String getAvgSpeedText() { return avgSpeedText; } /** * Get the maxSpeedText. * * @return Returns the maxSpeedText as a String. */ public String getMaxSpeedText() { return maxSpeedText; } /** * Get the minSpeedText. * * @return Returns the minSpeedText as a String. */ public String getMinSpeedText() { return minSpeedText; } /** * Get the tracknameText. * * @return Returns the tracknameText as a String. */ public String getTracknameText() { return tracknameText; } /** * Get the waypointsText. * * @return Returns the waypointsText as a String. */ public String getWaypointsText() { return waypointsText; } /** * Get the distanceText. * * @return Returns the distanceText as a String. */ public String getDistanceText() { return distanceText; } /** * Get the starttime. * * @return Returns the starttime as a long. */ public long getStarttime() { return mStarttime; } /** * Get the endtime. * * @return Returns the endtime as a long. */ public long getEndtime() { return mEndtime; } /** * Get the maximum speed. * * @return Returns the maxSpeeddb as m/s in a double. */ public double getMaxSpeed() { return mMaxSpeed; } /** * Get the min speed. * * @return Returns the average speed as m/s in a double. */ public double getAverageStatisicsSpeed() { return mAverageActiveSpeed; } /** * Get the maxAltitude. * * @return Returns the maxAltitude as a double. */ public double getMaxAltitude() { return mMaxAltitude; } /** * Get the minAltitude. * * @return Returns the minAltitude as a double. */ public double getMinAltitude() { return mMinAltitude; } /** * Get the total ascension in m. * * @return Returns the ascension as a double. */ public double getAscension() { return mAscension; } public CharSequence getAscensionText() { return ascensionText; } /** * Get the distanceTraveled. * * @return Returns the distanceTraveled as a float. */ public double getDistanceTraveled() { return mDistanceTraveled; } /** * Get the mUnits. * * @return Returns the mUnits as a UnitsI18n. */ public UnitsI18n getUnits() { return mUnits; } public String getDurationText() { long s = mDuration / 1000; String duration = String.format("%dh:%02dm:%02ds", s/3600, (s%3600)/60, (s%60)); return duration; } @Override protected Void doInBackground(Uri... params) { this.updateCalculations(params[0]); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if( mDelegate != null ) { mDelegate.finishedCalculations(this); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/StatisticsCalulator.java
Java
gpl3
13,828
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import java.text.DateFormat; import java.util.Date; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.CornerPathEffect; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Typeface; import android.location.Location; import android.net.Uri; import android.util.AttributeSet; import android.view.View; /** * Calculate and draw graphs of track data * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class GraphCanvas extends View { @SuppressWarnings("unused") private static final String TAG = "OGT.GraphCanvas"; public static final int TIMESPEEDGRAPH = 0; public static final int DISTANCESPEEDGRAPH = 1; public static final int TIMEALTITUDEGRAPH = 2; public static final int DISTANCEALTITUDEGRAPH = 3; private Uri mUri; private Bitmap mRenderBuffer; private Canvas mRenderCanvas; private Context mContext; private UnitsI18n mUnits; private int mGraphType = -1; private long mEndTime; private long mStartTime; private double mDistance; private int mHeight; private int mWidth; private int mMinAxis; private int mMaxAxis; private double mMinAlititude; private double mMaxAlititude; private double mHighestSpeedNumber; private double mDistanceDrawn; private long mStartTimeDrawn; private long mEndTimeDrawn; float density = Resources.getSystem().getDisplayMetrics().density; private Paint whiteText ; private Paint ltgreyMatrixDashed; private Paint greenGraphLine; private Paint dkgreyMatrixLine; private Paint whiteCenteredText; private Paint dkgrayLargeType; public GraphCanvas( Context context, AttributeSet attrs ) { this(context, attrs, 0); } public GraphCanvas( Context context, AttributeSet attrs, int defStyle ) { super(context, attrs, defStyle); mContext = context; whiteText = new Paint(); whiteText.setColor( Color.WHITE ); whiteText.setAntiAlias( true ); whiteText.setTextSize( (int)(density * 12) ); whiteCenteredText = new Paint(); whiteCenteredText.setColor( Color.WHITE ); whiteCenteredText.setAntiAlias( true ); whiteCenteredText.setTextAlign( Paint.Align.CENTER ); whiteCenteredText.setTextSize( (int)(density * 12) ); ltgreyMatrixDashed = new Paint(); ltgreyMatrixDashed.setColor( Color.LTGRAY ); ltgreyMatrixDashed.setStrokeWidth( 1 ); ltgreyMatrixDashed.setPathEffect( new DashPathEffect( new float[]{2,4}, 0 ) ); greenGraphLine = new Paint(); greenGraphLine.setPathEffect( new CornerPathEffect( 8 ) ); greenGraphLine.setStyle( Paint.Style.STROKE ); greenGraphLine.setStrokeWidth( 4 ); greenGraphLine.setAntiAlias( true ); greenGraphLine.setColor(Color.GREEN); dkgreyMatrixLine = new Paint(); dkgreyMatrixLine.setColor( Color.DKGRAY ); dkgreyMatrixLine.setStrokeWidth( 2 ); dkgrayLargeType = new Paint(); dkgrayLargeType.setColor( Color.LTGRAY ); dkgrayLargeType.setAntiAlias( true ); dkgrayLargeType.setTextAlign( Paint.Align.CENTER ); dkgrayLargeType.setTextSize( (int)(density * 21) ); dkgrayLargeType.setTypeface( Typeface.DEFAULT_BOLD ); } /** * Set the dataset for which to draw data. Also provide hints and helpers. * * @param uri * @param startTime * @param endTime * @param distance * @param minAlititude * @param maxAlititude * @param maxSpeed * @param units */ public void setData( Uri uri, StatisticsCalulator calc ) { boolean rerender = false; if( uri.equals( mUri ) ) { double distanceDrawnPercentage = mDistanceDrawn / mDistance; double duractionDrawnPercentage = (double)((1d+mEndTimeDrawn-mStartTimeDrawn) / (1d+mEndTime-mStartTime)); rerender = distanceDrawnPercentage < 0.99d || duractionDrawnPercentage < 0.99d; } else { if( mRenderBuffer == null && super.getWidth() > 0 && super.getHeight() > 0 ) { initRenderBuffer(super.getWidth(), super.getHeight()); } rerender = true; } mUri = uri; mUnits = calc.getUnits(); mMinAlititude = mUnits.conversionFromMeterToHeight( calc.getMinAltitude() ); mMaxAlititude = mUnits.conversionFromMeterToHeight( calc.getMaxAltitude() ); if( mUnits.isUnitFlipped() ) { mHighestSpeedNumber = 1.5 * mUnits.conversionFromMetersPerSecond( calc.getAverageStatisicsSpeed() ); } else { mHighestSpeedNumber = mUnits.conversionFromMetersPerSecond( calc.getMaxSpeed() ); } mStartTime = calc.getStarttime(); mEndTime = calc.getEndtime(); mDistance = calc.getDistanceTraveled(); if( rerender ) { renderGraph(); } } public synchronized void clearData() { mUri = null; mUnits = null; mRenderBuffer = null; } public void setType( int graphType) { if( mGraphType != graphType ) { mGraphType = graphType; renderGraph(); } } public int getType() { return mGraphType; } @Override protected synchronized void onSizeChanged( int w, int h, int oldw, int oldh ) { super.onSizeChanged( w, h, oldw, oldh ); initRenderBuffer(w, h); renderGraph(); } private void initRenderBuffer(int w, int h) { mRenderBuffer = Bitmap.createBitmap( w, h, Config.ARGB_8888 ); mRenderCanvas = new Canvas( mRenderBuffer ); } @Override protected synchronized void onDraw( Canvas canvas ) { super.onDraw(canvas); if( mRenderBuffer != null ) { canvas.drawBitmap( mRenderBuffer, 0, 0, null ); } } private synchronized void renderGraph() { if( mRenderBuffer != null && mUri != null ) { mRenderBuffer.eraseColor( Color.TRANSPARENT ); switch( mGraphType ) { case( TIMESPEEDGRAPH ): setupSpeedAxis(); drawGraphType(); drawTimeAxisGraphOnCanvas( new String[] { Waypoints.TIME, Waypoints.SPEED }, Constants.MIN_STATISTICS_SPEED ); drawSpeedsTexts(); drawTimeTexts(); break; case( DISTANCESPEEDGRAPH ): setupSpeedAxis(); drawGraphType(); drawDistanceAxisGraphOnCanvas( new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.SPEED }, Constants.MIN_STATISTICS_SPEED ); drawSpeedsTexts(); drawDistanceTexts(); break; case( TIMEALTITUDEGRAPH ): setupAltitudeAxis(); drawGraphType(); drawTimeAxisGraphOnCanvas( new String[] { Waypoints.TIME, Waypoints.ALTITUDE }, -1000d ); drawAltitudesTexts(); drawTimeTexts(); break; case( DISTANCEALTITUDEGRAPH ): setupAltitudeAxis(); drawGraphType(); drawDistanceAxisGraphOnCanvas( new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, -1000d ); drawAltitudesTexts(); drawDistanceTexts(); break; default: break; } mDistanceDrawn = mDistance; mStartTimeDrawn = mStartTime; mEndTimeDrawn = mEndTime; } postInvalidate(); } /** * * @param params * @param minValue Minimum value of params[1] that will be drawn */ private void drawDistanceAxisGraphOnCanvas( String[] params, double minValue ) { ContentResolver resolver = mContext.getContentResolver(); Uri segmentsUri = Uri.withAppendedPath( mUri, "segments" ); Uri waypointsUri = null; Cursor segments = null; Cursor waypoints = null; double[][] values ; int[][] valueDepth; double distance = 1; try { segments = resolver.query( segmentsUri, new String[]{ Segments._ID }, null, null, null ); int segmentCount = segments.getCount(); values = new double[segmentCount][mWidth]; valueDepth = new int[segmentCount][mWidth]; if( segments.moveToFirst() ) { for(int segment=0;segment<segmentCount;segment++) { segments.moveToPosition( segment ); long segmentId = segments.getLong( 0 ); waypointsUri = Uri.withAppendedPath( segmentsUri, segmentId+"/waypoints" ); try { waypoints = resolver.query( waypointsUri, params, null, null, null ); if( waypoints.moveToFirst() ) { Location lastLocation = null; Location currentLocation = null; do { currentLocation = new Location( this.getClass().getName() ); currentLocation.setLongitude( waypoints.getDouble( 0 ) ); currentLocation.setLatitude( waypoints.getDouble( 1 ) ); // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop if( currentLocation.getLatitude() == 0.0d || currentLocation.getLongitude() == 0.0d ) { continue; } if( lastLocation != null ) { distance += lastLocation.distanceTo( currentLocation ); } lastLocation = currentLocation; double value = waypoints.getDouble( 2 ); if( value != 0 && value > minValue && segment < values.length ) { int x = (int) ((distance)*(mWidth-1) / mDistance); if( x > 0 && x < valueDepth[segment].length ) { valueDepth[segment][x]++; values[segment][x] = values[segment][x]+((value-values[segment][x])/valueDepth[segment][x]); } } } while( waypoints.moveToNext() ); } } finally { if( waypoints != null ) { waypoints.close(); } } } } } finally { if( segments != null ) { segments.close(); } } for( int segment=0;segment<values.length;segment++) { for( int x=0;x<values[segment].length;x++) { if( valueDepth[segment][x] > 0 ) { values[segment][x] = translateValue( values[segment][x] ); } } } drawGraph( values, valueDepth ); } private void drawTimeAxisGraphOnCanvas( String[] params, double minValue ) { ContentResolver resolver = mContext.getContentResolver(); Uri segmentsUri = Uri.withAppendedPath( mUri, "segments" ); Uri waypointsUri = null; Cursor segments = null; Cursor waypoints = null; long duration = 1+mEndTime - mStartTime; double[][] values ; int[][] valueDepth; try { segments = resolver.query( segmentsUri, new String[]{ Segments._ID }, null, null, null ); int segmentCount = segments.getCount(); values = new double[segmentCount][mWidth]; valueDepth = new int[segmentCount][mWidth]; if( segments.moveToFirst() ) { for(int segment=0;segment<segmentCount;segment++) { segments.moveToPosition( segment ); long segmentId = segments.getLong( 0 ); waypointsUri = Uri.withAppendedPath( segmentsUri, segmentId+"/waypoints" ); try { waypoints = resolver.query( waypointsUri, params, null, null, null ); if( waypoints.moveToFirst() ) { do { long time = waypoints.getLong( 0 ); double value = waypoints.getDouble( 1 ); if( value != 0 && value > minValue && segment < values.length ) { int x = (int) ((time-mStartTime)*(mWidth-1) / duration); if( x > 0 && x < valueDepth[segment].length ) { valueDepth[segment][x]++; values[segment][x] = values[segment][x]+((value-values[segment][x])/valueDepth[segment][x]); } } } while( waypoints.moveToNext() ); } } finally { if( waypoints != null ) { waypoints.close(); } } } } } finally { if( segments != null ) { segments.close(); } } for( int p=0;p<values.length;p++) { for( int x=0;x<values[p].length;x++) { if( valueDepth[p][x] > 0 ) { values[p][x] = translateValue( values[p][x] ); } } } drawGraph( values, valueDepth ); } private void setupAltitudeAxis() { mMinAxis = -4 + 4 * (int)(mMinAlititude / 4); mMaxAxis = 4 + 4 * (int)(mMaxAlititude / 4); mWidth = mRenderCanvas.getWidth()-5; mHeight = mRenderCanvas.getHeight()-10; } private void setupSpeedAxis() { mMinAxis = 0; mMaxAxis = 4 + 4 * (int)( mHighestSpeedNumber / 4); mWidth = mRenderCanvas.getWidth()-5; mHeight = mRenderCanvas.getHeight()-10; } private void drawAltitudesTexts() { mRenderCanvas.drawText( String.format( "%d %s", mMinAxis, mUnits.getHeightUnit() ) , 8, mHeight, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", (mMaxAxis+mMinAxis)/2, mUnits.getHeightUnit() ) , 8, 5+mHeight/2, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", mMaxAxis, mUnits.getHeightUnit() ), 8, 15, whiteText ); } private void drawSpeedsTexts() { mRenderCanvas.drawText( String.format( "%d %s", mMinAxis, mUnits.getSpeedUnit() ) , 8, mHeight, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", (mMaxAxis+mMinAxis)/2, mUnits.getSpeedUnit() ) , 8, 3+mHeight/2, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", mMaxAxis, mUnits.getSpeedUnit() ) , 8, 7+whiteText.getTextSize(), whiteText ); } private void drawGraphType() { //float density = Resources.getSystem().getDisplayMetrics().density; String text; switch( mGraphType ) { case( TIMESPEEDGRAPH ): text = mContext.getResources().getString( R.string.graphtype_timespeed ); break; case( DISTANCESPEEDGRAPH ): text = mContext.getResources().getString( R.string.graphtype_distancespeed ); break; case( TIMEALTITUDEGRAPH ): text = mContext.getResources().getString( R.string.graphtype_timealtitude ); break; case( DISTANCEALTITUDEGRAPH ): text = mContext.getResources().getString( R.string.graphtype_distancealtitude ); break; default: text = "UNKNOWN GRAPH TYPE"; break; } mRenderCanvas.drawText( text, 5+mWidth/2, 5+mHeight/8, dkgrayLargeType ); } private void drawTimeTexts() { DateFormat timeInstance = android.text.format.DateFormat.getTimeFormat(this.getContext().getApplicationContext()); String start = timeInstance.format( new Date( mStartTime ) ); String half = timeInstance.format( new Date( (mEndTime+mStartTime)/2 ) ); String end = timeInstance.format( new Date( mEndTime ) ); Path yAxis; yAxis = new Path(); yAxis.moveTo( 5, 5+mHeight/2 ); yAxis.lineTo( 5, 5 ); mRenderCanvas.drawTextOnPath( String.format( start ), yAxis, 0, whiteCenteredText.getTextSize(), whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth/2 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth/2 , 5 ); mRenderCanvas.drawTextOnPath( String.format( half ), yAxis, 0, -3, whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth-1 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth-1 , 5 ); mRenderCanvas.drawTextOnPath( String.format( end ), yAxis, 0, -3, whiteCenteredText ); } private void drawDistanceTexts() { String start = String.format( "%.0f %s", mUnits.conversionFromMeter(0), mUnits.getDistanceUnit() ) ; String half = String.format( "%.0f %s", mUnits.conversionFromMeter(mDistance)/2, mUnits.getDistanceUnit() ) ; String end = String.format( "%.0f %s", mUnits.conversionFromMeter(mDistance) , mUnits.getDistanceUnit() ) ; Path yAxis; yAxis = new Path(); yAxis.moveTo( 5, 5+mHeight/2 ); yAxis.lineTo( 5, 5 ); mRenderCanvas.drawTextOnPath( String.format( start ), yAxis, 0, whiteText.getTextSize(), whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth/2 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth/2 , 5 ); mRenderCanvas.drawTextOnPath( String.format( half ), yAxis, 0, -3, whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth-1 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth-1 , 5 ); mRenderCanvas.drawTextOnPath( String.format( end ), yAxis, 0, -3, whiteCenteredText ); } private double translateValue( double val ) { switch( mGraphType ) { case( TIMESPEEDGRAPH ): case( DISTANCESPEEDGRAPH ): val = mUnits.conversionFromMetersPerSecond( val ); break; case( TIMEALTITUDEGRAPH ): case( DISTANCEALTITUDEGRAPH ): val = mUnits.conversionFromMeterToHeight( val ); break; default: break; } return val; } private void drawGraph( double[][] values, int[][] valueDepth ) { // Matrix // Horizontals mRenderCanvas.drawLine( 5, 5 , 5+mWidth, 5 , ltgreyMatrixDashed ); // top mRenderCanvas.drawLine( 5, 5+mHeight/4 , 5+mWidth, 5+mHeight/4 , ltgreyMatrixDashed ); // 2nd mRenderCanvas.drawLine( 5, 5+mHeight/2 , 5+mWidth, 5+mHeight/2 , ltgreyMatrixDashed ); // middle mRenderCanvas.drawLine( 5, 5+mHeight/4*3, 5+mWidth, 5+mHeight/4*3, ltgreyMatrixDashed ); // 3rd // Verticals mRenderCanvas.drawLine( 5+mWidth/4 , 5, 5+mWidth/4 , 5+mHeight, ltgreyMatrixDashed ); // 2nd mRenderCanvas.drawLine( 5+mWidth/2 , 5, 5+mWidth/2 , 5+mHeight, ltgreyMatrixDashed ); // middle mRenderCanvas.drawLine( 5+mWidth/4*3, 5, 5+mWidth/4*3, 5+mHeight, ltgreyMatrixDashed ); // 3rd mRenderCanvas.drawLine( 5+mWidth-1 , 5, 5+mWidth-1 , 5+mHeight, ltgreyMatrixDashed ); // right // The line Path mPath; int emptyValues = 0; mPath = new Path(); for( int p=0;p<values.length;p++) { int start = 0; while( valueDepth[p][start] == 0 && start < values[p].length-1 ) { start++; } mPath.moveTo( (float)start+5, 5f+ (float) ( mHeight - ( ( values[p][start]-mMinAxis )*mHeight ) / ( mMaxAxis-mMinAxis ) ) ); for( int x=start;x<values[p].length;x++) { double y = mHeight - ( ( values[p][x]-mMinAxis )*mHeight ) / ( mMaxAxis-mMinAxis ) ; if( valueDepth[p][x] > 0 ) { if( emptyValues > mWidth/10 ) { mPath.moveTo( (float)x+5, (float) y+5 ); } else { mPath.lineTo( (float)x+5, (float) y+5 ); } emptyValues = 0; } else { emptyValues++; } } } mRenderCanvas.drawPath( mPath, greenGraphLine ); // Axis's mRenderCanvas.drawLine( 5, 5 , 5 , 5+mHeight, dkgreyMatrixLine ); mRenderCanvas.drawLine( 5, 5+mHeight, 5+mWidth, 5+mHeight, dkgreyMatrixLine ); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/GraphCanvas.java
Java
gpl3
23,312
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.util.Log; /** * Work around based on input from the comment section of * <a href="http://code.google.com/p/android/issues/detail?can=2&q=6191&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&id=6191">Issue 6191</a> * * @version $Id$ * @author rene (c) May 8, 2010, Sogeti B.V. */ public class ViewFlipper extends android.widget.ViewFlipper { private static final String TAG = "OGT.ViewFlipper"; public ViewFlipper(Context context) { super( context ); } public ViewFlipper(Context context, AttributeSet attrs) { super( context, attrs ); } /** * On api level 7 unexpected exception occur during orientation switching. * These are java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$id * exceptions. On level 7, 8 and 9 devices these are ignored. */ @Override protected void onDetachedFromWindow() { if( Build.VERSION.SDK_INT > 7 ) { try { super.onDetachedFromWindow(); } catch( IllegalArgumentException e ) { Log.w( TAG, "Android project issue 6191 workaround." ); /* Quick catch and continue on api level 7+, the Eclair 2.1 / 2.2 */ } finally { super.stopFlipping(); } } else { super.onDetachedFromWindow(); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/ViewFlipper.java
Java
gpl3
3,082
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.util.Constants; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.content.Context; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class JogmapSharing extends GpxCreator { private static final String TAG = "OGT.JogmapSharing"; private String jogmapResponseText; public JogmapSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, attachments, listener); } @Override protected Uri doInBackground(Void... params) { Uri result = super.doInBackground(params); sendToJogmap(result); return result; } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); CharSequence text = mContext.getString(R.string.osm_success) + jogmapResponseText; Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); toast.show(); } private void sendToJogmap(Uri fileUri) { String authCode = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.JOGRUNNER_AUTH, ""); File gpxFile = new File(fileUri.getEncodedPath()); HttpClient httpclient = new DefaultHttpClient(); URI jogmap = null; int statusCode = 0; HttpEntity responseEntity = null; try { jogmap = new URI(mContext.getString(R.string.jogmap_post_url)); HttpPost method = new HttpPost(jogmap); MultipartEntity entity = new MultipartEntity(); entity.addPart("id", new StringBody(authCode)); entity.addPart("mFile", new FileBody(gpxFile)); method.setEntity(entity); HttpResponse response = httpclient.execute(method); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); jogmapResponseText = XmlCreator.convertStreamToString(stream); } catch (IOException e) { String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.jogmap_task), e, text); } catch (URISyntaxException e) { String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.jogmap_task), e, text); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode != 200) { Log.e(TAG, "Wrong status code " + statusCode); jogmapResponseText = mContext.getString(R.string.jogmap_failed) + jogmapResponseText; handleError(mContext.getString(R.string.jogmap_task), new HttpException("Unexpected status reported by Jogmap"), jogmapResponseText); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/JogmapSharing.java
Java
gpl3
5,565
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.nio.channels.FileChannel; import java.util.Date; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.util.Log; import android.view.Window; /** * Async XML creation task Execute without parameters (Void) Update posted with * single Integer And result is a filename in a String * * @version $Id$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public abstract class XmlCreator extends AsyncTask<Void, Integer, Uri> { private String TAG = "OGT.XmlCreator"; private String mExportDirectoryPath; private boolean mNeedsBundling; String mChosenName; private ProgressListener mProgressListener; protected Context mContext; protected Uri mTrackUri; String mFileName; private String mErrorText; private Exception mException; private String mTask; public ProgressAdmin mProgressAdmin; XmlCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { mChosenName = chosenFileName; mContext = context; mTrackUri = trackUri; mProgressListener = listener; mProgressAdmin = new ProgressAdmin(); String trackName = extractCleanTrackName(); mFileName = cleanFilename(mChosenName, trackName); } public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } private String extractCleanTrackName() { Cursor trackCursor = null; ContentResolver resolver = mContext.getContentResolver(); String trackName = "Untitled"; try { trackCursor = resolver.query(mTrackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToLast()) { trackName = cleanFilename(trackCursor.getString(0), trackName); } } finally { if (trackCursor != null) { trackCursor.close(); } } return trackName; } /** * Calculated the total progress sum expected from a export to file This is * the sum of the number of waypoints and media entries times 100. The whole * number is doubled when compression is needed. */ public void determineProgressGoal() { if (mProgressListener != null) { Uri allWaypointsUri = Uri.withAppendedPath(mTrackUri, "waypoints"); Uri allMediaUri = Uri.withAppendedPath(mTrackUri, "media"); Cursor cursor = null; ContentResolver resolver = mContext.getContentResolver(); try { cursor = resolver.query(allWaypointsUri, new String[] { "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null); if (cursor.moveToLast()) { mProgressAdmin.setWaypointCount(cursor.getInt(0)); } cursor.close(); cursor = resolver.query(allMediaUri, new String[] { "count(" + Media.TABLE + "." + Media._ID + ")" }, null, null, null); if (cursor.moveToLast()) { mProgressAdmin.setMediaCount(cursor.getInt(0)); } cursor.close(); cursor = resolver.query(allMediaUri, new String[] { "count(" + Tracks._ID + ")" }, Media.URI + " LIKE ? and " + Media.URI + " NOT LIKE ?", new String[] { "file://%", "%txt" }, null); if (cursor.moveToLast()) { mProgressAdmin.setCompress( cursor.getInt(0) > 0 ); } } finally { if (cursor != null) { cursor.close(); } } } else { Log.w(TAG, "Exporting " + mTrackUri + " without progress!"); } } /** * Removes all non-word chars (\W) from the text * * @param fileName * @param defaultName * @return a string larger then 0 with either word chars remaining from the * input or the default provided */ public static String cleanFilename(String fileName, String defaultName) { if (fileName == null || "".equals(fileName)) { fileName = defaultName; } else { fileName = fileName.replaceAll("\\W", ""); fileName = (fileName.length() > 0) ? fileName : defaultName; } return fileName; } /** * Includes media into the export directory and returns the relative path of * the media * * @param inputFilePath * @return file path relative to the export dir * @throws IOException */ protected String includeMediaFile(String inputFilePath) throws IOException { mNeedsBundling = true; File source = new File(inputFilePath); File target = new File(mExportDirectoryPath + "/" + source.getName()); // Log.d( TAG, String.format( "Copy %s to %s", source, target ) ); if (source.exists()) { FileInputStream fileInputStream = new FileInputStream(source); FileChannel inChannel = fileInputStream.getChannel(); FileOutputStream fileOutputStream = new FileOutputStream(target); FileChannel outChannel = fileOutputStream.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (fileInputStream != null) fileInputStream.close(); if (fileOutputStream != null) fileOutputStream.close(); } } else { Log.w( TAG, "Failed to add file to new XML export. Missing: "+inputFilePath ); } mProgressAdmin.addMediaProgress(); return target.getName(); } /** * Just to start failing early * * @throws IOException */ protected void verifySdCardAvailibility() throws IOException { String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { throw new IOException("The ExternalStorage is not mounted, unable to export files for sharing."); } } /** * Create a zip of the export directory based on the given filename * * @param fileName The directory to be replaced by a zipped file of the same * name * @param extension * @return full path of the build zip file * @throws IOException */ protected String bundlingMediaAndXml(String fileName, String extension) throws IOException { String zipFilePath; if (fileName.endsWith(".zip") || fileName.endsWith(extension)) { zipFilePath = Constants.getSdCardDirectory(mContext) + fileName; } else { zipFilePath = Constants.getSdCardDirectory(mContext) + fileName + extension; } String[] filenames = new File(mExportDirectoryPath).list(); byte[] buf = new byte[1024]; ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFilePath)); for (int i = 0; i < filenames.length; i++) { String entryFilePath = mExportDirectoryPath + "/" + filenames[i]; FileInputStream in = new FileInputStream(entryFilePath); zos.putNextEntry(new ZipEntry(filenames[i])); int len; while ((len = in.read(buf)) >= 0) { zos.write(buf, 0, len); } zos.closeEntry(); in.close(); mProgressAdmin.addCompressProgress(); } } finally { if (zos != null) { zos.close(); } } deleteRecursive(new File(mExportDirectoryPath)); return zipFilePath; } public static boolean deleteRecursive(File file) { if (file.isDirectory()) { String[] children = file.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteRecursive(new File(file, children[i])); if (!success) { return false; } } } return file.delete(); } public void setExportDirectoryPath(String exportDirectoryPath) { this.mExportDirectoryPath = exportDirectoryPath; } public String getExportDirectoryPath() { return mExportDirectoryPath; } public void quickTag(XmlSerializer serializer, String ns, String tag, String content) throws IllegalArgumentException, IllegalStateException, IOException { if( tag == null) { tag = ""; } if( content == null) { content = ""; } serializer.text("\n"); serializer.startTag(ns, tag); serializer.text(content); serializer.endTag(ns, tag); } public boolean needsBundling() { return mNeedsBundling; } public static String convertStreamToString(InputStream is) throws IOException { String result = ""; /* * To convert the InputStream to String we use the Reader.read(char[] * buffer) method. We iterate until the Reader return -1 which means * there's no more data to read. We use the StringWriter class to produce * the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[8192]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } result = writer.toString(); } return result; } public static InputStream convertStreamToLoggedStream(String tag, InputStream is) throws IOException { String result = ""; /* * To convert the InputStream to String we use the Reader.read(char[] * buffer) method. We iterate until the Reader return -1 which means * there's no more data to read. We use the StringWriter class to produce * the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[8192]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } result = writer.toString(); } InputStream in = new ByteArrayInputStream(result.getBytes("UTF-8")); return in; } protected abstract String getContentType(); protected void handleError(String task, Exception e, String text) { Log.e(TAG, "Unable to save ", e); mTask = task; mException = e; mErrorText = text; cancel(false); throw new CancellationException(text); } @Override protected void onPreExecute() { if(mProgressListener!= null) { mProgressListener.started(); } } @Override protected void onProgressUpdate(Integer... progress) { if(mProgressListener!= null) { mProgressListener.setProgress(mProgressAdmin.getProgress()); } } @Override protected void onPostExecute(Uri resultFilename) { if(mProgressListener!= null) { mProgressListener.finished(resultFilename); } } @Override protected void onCancelled() { if(mProgressListener!= null) { mProgressListener.finished(null); mProgressListener.showError(mTask, mErrorText, mException); } } public class ProgressAdmin { long lastUpdate; private boolean compressCount; private boolean compressProgress; private boolean uploadCount; private boolean uploadProgress; private int mediaCount; private int mediaProgress; private int waypointCount; private int waypointProgress; private long photoUploadCount ; private long photoUploadProgress ; public void addMediaProgress() { mediaProgress ++; } public void addCompressProgress() { compressProgress = true; } public void addUploadProgress() { uploadProgress = true; } public void addPhotoUploadProgress(long length) { photoUploadProgress += length; } /** * Get the progress on scale 0 ... Window.PROGRESS_END * * @return Returns the progress as a int. */ public int getProgress() { int blocks = 0; if( waypointCount > 0 ){ blocks++; } if( mediaCount > 0 ){ blocks++; } if( compressCount ){ blocks++; } if( uploadCount ){ blocks++; } if( photoUploadCount > 0 ){ blocks++; } int progress; if( blocks > 0 ) { int blockSize = Window.PROGRESS_END / blocks; progress = waypointCount > 0 ? blockSize * waypointProgress / waypointCount : 0; progress += mediaCount > 0 ? blockSize * mediaProgress / mediaCount : 0; progress += compressProgress ? blockSize : 0; progress += uploadProgress ? blockSize : 0; progress += photoUploadCount > 0 ? blockSize * photoUploadProgress / photoUploadCount : 0; } else { progress = 0; } //Log.d( TAG, "Progress updated to "+progress); return progress; } public void setWaypointCount(int waypoint) { waypointCount = waypoint; considerPublishProgress(); } public void setMediaCount(int media) { mediaCount = media; considerPublishProgress(); } public void setCompress( boolean compress) { compressCount = compress; considerPublishProgress(); } public void setUpload( boolean upload) { uploadCount = upload; considerPublishProgress(); } public void setPhotoUpload(long length) { photoUploadCount += length; considerPublishProgress(); } public void addWaypointProgress(int i) { waypointProgress += i; considerPublishProgress(); } public void considerPublishProgress() { long now = new Date().getTime(); if( now - lastUpdate > 1000 ) { lastUpdate = now; publishProgress(); } } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/XmlCreator.java
Java
gpl3
17,459
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.util.Xml; /** * Create a GPX version of a stored track * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class GpxCreator extends XmlCreator { public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"; public static final String NS_GPX_11 = "http://www.topografix.com/GPX/1/1"; public static final String NS_GPX_10 = "http://www.topografix.com/GPX/1/0"; public static final String NS_OGT_10 = "http://gpstracker.android.sogeti.nl/GPX/1/0"; public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true } private String TAG = "OGT.GpxCreator"; private boolean includeAttachments; protected String mName; public GpxCreator(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, listener); includeAttachments = attachments; } @Override protected Uri doInBackground(Void... params) { determineProgressGoal(); Uri resultFilename = exportGpx(); return resultFilename; } protected Uri exportGpx() { String xmlFilePath; if (mFileName.endsWith(".gpx") || mFileName.endsWith(".xml")) { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4)); xmlFilePath = getExportDirectoryPath() + "/" + mFileName; } else { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName); xmlFilePath = getExportDirectoryPath() + "/" + mFileName + ".gpx"; } new File(getExportDirectoryPath()).mkdirs(); String resultFilename = null; FileOutputStream fos = null; BufferedOutputStream buf = null; try { verifySdCardAvailibility(); XmlSerializer serializer = Xml.newSerializer(); File xmlFile = new File(xmlFilePath); fos = new FileOutputStream(xmlFile); buf = new BufferedOutputStream(fos, 8 * 8192); serializer.setOutput(buf, "UTF-8"); serializeTrack(mTrackUri, serializer); buf.close(); buf = null; fos.close(); fos = null; if (needsBundling()) { resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".zip"); } else { File finalFile = new File(Constants.getSdCardDirectory(mContext) + xmlFile.getName()); xmlFile.renameTo(finalFile); resultFilename = finalFile.getAbsolutePath(); XmlCreator.deleteRecursive(xmlFile.getParentFile()); } mFileName = new File(resultFilename).getName(); } catch (FileNotFoundException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filenotfound); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IllegalArgumentException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IllegalStateException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IOException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } finally { if (buf != null) { try { buf.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buf after completion, ignoring.", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { Log.e(TAG, "Failed to close fos after completion, ignoring.", e); } } } return Uri.fromFile(new File(resultFilename)); } private void serializeTrack(Uri trackUri, XmlSerializer serializer) throws IllegalArgumentException, IllegalStateException, IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } serializer.startDocument("UTF-8", true); serializer.setPrefix("xsi", NS_SCHEMA); serializer.setPrefix("gpx10", NS_GPX_10); serializer.setPrefix("ogt10", NS_OGT_10); serializer.text("\n"); serializer.startTag("", "gpx"); serializer.attribute(null, "version", "1.1"); serializer.attribute(null, "creator", "nl.sogeti.android.gpstracker"); serializer.attribute(NS_SCHEMA, "schemaLocation", NS_GPX_11 + " http://www.topografix.com/gpx/1/1/gpx.xsd"); serializer.attribute(null, "xmlns", NS_GPX_11); // <metadata/> Big header of the track serializeTrackHeader(mContext, serializer, trackUri); // <wpt/> [0...] Waypoints if (includeAttachments) { serializeWaypoints(mContext, serializer, Uri.withAppendedPath(trackUri, "/media")); } // <trk/> [0...] Track serializer.text("\n"); serializer.startTag("", "trk"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text(mName); serializer.endTag("", "name"); // The list of segments in the track serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments")); serializer.text("\n"); serializer.endTag("", "trk"); serializer.text("\n"); serializer.endTag("", "gpx"); serializer.endDocument(); } private void serializeTrackHeader(Context context, XmlSerializer serializer, Uri trackUri) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } ContentResolver resolver = context.getContentResolver(); Cursor trackCursor = null; String databaseName = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, null); if (trackCursor.moveToFirst()) { databaseName = trackCursor.getString(1); serializer.text("\n"); serializer.startTag("", "metadata"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(trackCursor.getLong(2)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); serializer.text("\n"); serializer.endTag("", "metadata"); } } finally { if (trackCursor != null) { trackCursor.close(); } } if (mName == null) { mName = "Untitled"; } if (databaseName != null && !databaseName.equals("")) { mName = databaseName; } if (mChosenName != null && !mChosenName.equals("")) { mName = mChosenName; } } private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor segmentCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null); if (segmentCursor.moveToFirst()) { do { Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints"); serializer.text("\n"); serializer.startTag("", "trkseg"); serializeTrackPoints(serializer, waypoints); serializer.text("\n"); serializer.endTag("", "trkseg"); } while (segmentCursor.moveToNext()); } } finally { if (segmentCursor != null) { segmentCursor.close(); } } } private void serializeTrackPoints(XmlSerializer serializer, Uri waypoints) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.TIME, Waypoints.ALTITUDE, Waypoints._ID, Waypoints.SPEED, Waypoints.ACCURACY, Waypoints.BEARING }, null, null, null); if (waypointsCursor.moveToFirst()) { do { mProgressAdmin.addWaypointProgress(1); serializer.text("\n"); serializer.startTag("", "trkpt"); serializer.attribute(null, "lat", Double.toString(waypointsCursor.getDouble(1))); serializer.attribute(null, "lon", Double.toString(waypointsCursor.getDouble(0))); serializer.text("\n"); serializer.startTag("", "ele"); serializer.text(Double.toString(waypointsCursor.getDouble(3))); serializer.endTag("", "ele"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(waypointsCursor.getLong(2)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); serializer.text("\n"); serializer.startTag("", "extensions"); double speed = waypointsCursor.getDouble(5); double accuracy = waypointsCursor.getDouble(6); double bearing = waypointsCursor.getDouble(7); if (speed > 0.0) { quickTag(serializer, NS_GPX_10, "speed", Double.toString(speed)); } if (accuracy > 0.0) { quickTag(serializer, NS_OGT_10, "accuracy", Double.toString(accuracy)); } if (bearing != 0.0) { quickTag(serializer, NS_GPX_10, "course", Double.toString(bearing)); } serializer.endTag("", "extensions"); serializer.text("\n"); serializer.endTag("", "trkpt"); } while (waypointsCursor.moveToNext()); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } private void serializeWaypoints(Context context, XmlSerializer serializer, Uri media) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor mediaCursor = null; Cursor waypointCursor = null; BufferedReader buf = null; ContentResolver resolver = context.getContentResolver(); try { mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri waypointUri = Waypoints.buildUri(mediaCursor.getLong(1), mediaCursor.getLong(2), mediaCursor.getLong(3)); waypointCursor = resolver.query(waypointUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.ALTITUDE, Waypoints.TIME }, null, null, null); serializer.text("\n"); serializer.startTag("", "wpt"); if (waypointCursor != null && waypointCursor.moveToFirst()) { serializer.attribute(null, "lat", Double.toString(waypointCursor.getDouble(0))); serializer.attribute(null, "lon", Double.toString(waypointCursor.getDouble(1))); serializer.text("\n"); serializer.startTag("", "ele"); serializer.text(Double.toString(waypointCursor.getDouble(2))); serializer.endTag("", "ele"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(waypointCursor.getLong(3)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); } if (waypointCursor != null) { waypointCursor.close(); waypointCursor = null; } Uri mediaUri = Uri.parse(mediaCursor.getString(0)); if (mediaUri.getScheme().equals("file")) { if (mediaUri.getLastPathSegment().endsWith("3gp")) { String fileName = includeMediaFile(mediaUri.getLastPathSegment()); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", fileName); serializer.endTag("", "link"); } else if (mediaUri.getLastPathSegment().endsWith("jpg")) { String mediaPathPrefix = Constants.getSdCardDirectory(mContext); String fileName = includeMediaFile(mediaPathPrefix + mediaUri.getLastPathSegment()); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", fileName); serializer.endTag("", "link"); } else if (mediaUri.getLastPathSegment().endsWith("txt")) { quickTag(serializer, "", "name", mediaUri.getLastPathSegment()); serializer.startTag("", "desc"); if (buf != null) { buf.close(); } buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath())); String line; while ((line = buf.readLine()) != null) { serializer.text(line); serializer.text("\n"); } serializer.endTag("", "desc"); } } else if (mediaUri.getScheme().equals("content")) { if ((GPStracking.AUTHORITY + ".string").equals(mediaUri.getAuthority())) { quickTag(serializer, "", "name", mediaUri.getLastPathSegment()); } else if (mediaUri.getAuthority().equals("media")) { Cursor mediaItemCursor = null; try { mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null); if (mediaItemCursor.moveToFirst()) { String fileName = includeMediaFile(mediaItemCursor.getString(0)); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", mediaItemCursor.getString(1)); serializer.endTag("", "link"); } } finally { if (mediaItemCursor != null) { mediaItemCursor.close(); } } } } serializer.text("\n"); serializer.endTag("", "wpt"); } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } if (waypointCursor != null) { waypointCursor.close(); } if (buf != null) buf.close(); } } @Override protected String getContentType() { return needsBundling() ? "application/zip" : "text/xml"; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxCreator.java
Java
gpl3
20,276
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.Vector; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.ProgressFilterInputStream; import nl.sogeti.android.gpstracker.util.UnicodeReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import android.view.Window; public class GpxParser extends AsyncTask<Uri, Void, Uri> { private static final String LATITUDE_ATRIBUTE = "lat"; private static final String LONGITUDE_ATTRIBUTE = "lon"; private static final String TRACK_ELEMENT = "trkpt"; private static final String SEGMENT_ELEMENT = "trkseg"; private static final String NAME_ELEMENT = "name"; private static final String TIME_ELEMENT = "time"; private static final String ELEVATION_ELEMENT = "ele"; private static final String COURSE_ELEMENT = "course"; private static final String ACCURACY_ELEMENT = "accuracy"; private static final String SPEED_ELEMENT = "speed"; public static final SimpleDateFormat ZULU_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); public static final SimpleDateFormat ZULU_DATE_FORMAT_MS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); public static final SimpleDateFormat ZULU_DATE_FORMAT_BC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'"); protected static final int DEFAULT_UNKNOWN_FILESIZE = 1024 * 1024 * 10; private static final String TAG = "OGT.GpxParser"; static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMAT.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true ZULU_DATE_FORMAT_MS.setTimeZone(utc); } private ContentResolver mContentResolver; protected String mErrorDialogMessage; protected Exception mErrorDialogException; protected Context mContext; private ProgressListener mProgressListener; protected ProgressAdmin mProgressAdmin; public GpxParser(Context context, ProgressListener progressListener) { mContext = context; mProgressListener = progressListener; mContentResolver = mContext.getContentResolver(); } public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } public void determineProgressGoal(Uri importFileUri) { mProgressAdmin = new ProgressAdmin(); mProgressAdmin.setContentLength(DEFAULT_UNKNOWN_FILESIZE); if (importFileUri != null && importFileUri.getScheme().equals("file")) { File file = new File(importFileUri.getPath()); mProgressAdmin.setContentLength(file.length()); } } public Uri importUri(Uri importFileUri) { Uri result = null; String trackName = null; InputStream fis = null; if (importFileUri.getScheme().equals("file")) { trackName = importFileUri.getLastPathSegment(); } try { fis = mContentResolver.openInputStream(importFileUri); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_io)); } result = importTrack( fis, trackName); return result; } /** * Read a stream containing GPX XML into the OGT content provider * * @param fis opened stream the read from, will be closed after this call * @param trackName * @return */ public Uri importTrack( InputStream fis, String trackName ) { Uri trackUri = null; int eventType; ContentValues lastPosition = null; Vector<ContentValues> bulk = new Vector<ContentValues>(); boolean speed = false; boolean accuracy = false; boolean bearing = false; boolean elevation = false; boolean name = false; boolean time = false; Long importDate = Long.valueOf(new Date().getTime()); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xmlParser = factory.newPullParser(); ProgressFilterInputStream pfis = new ProgressFilterInputStream(fis, mProgressAdmin); BufferedInputStream bis = new BufferedInputStream(pfis); UnicodeReader ur = new UnicodeReader(bis, "UTF-8"); xmlParser.setInput(ur); eventType = xmlParser.getEventType(); String attributeName; Uri segmentUri = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xmlParser.getName().equals(NAME_ELEMENT)) { name = true; } else { ContentValues trackContent = new ContentValues(); trackContent.put(Tracks.NAME, trackName); if (xmlParser.getName().equals("trk") && trackUri == null) { trackUri = startTrack(trackContent); } else if (xmlParser.getName().equals(SEGMENT_ELEMENT)) { segmentUri = startSegment(trackUri); } else if (xmlParser.getName().equals(TRACK_ELEMENT)) { lastPosition = new ContentValues(); for (int i = 0; i < 2; i++) { attributeName = xmlParser.getAttributeName(i); if (attributeName.equals(LATITUDE_ATRIBUTE)) { lastPosition.put(Waypoints.LATITUDE, Double.valueOf(xmlParser.getAttributeValue(i))); } else if (attributeName.equals(LONGITUDE_ATTRIBUTE)) { lastPosition.put(Waypoints.LONGITUDE, Double.valueOf(xmlParser.getAttributeValue(i))); } } } else if (xmlParser.getName().equals(SPEED_ELEMENT)) { speed = true; } else if (xmlParser.getName().equals(ACCURACY_ELEMENT)) { accuracy = true; } else if (xmlParser.getName().equals(COURSE_ELEMENT)) { bearing = true; } else if (xmlParser.getName().equals(ELEVATION_ELEMENT)) { elevation = true; } else if (xmlParser.getName().equals(TIME_ELEMENT)) { time = true; } } } else if (eventType == XmlPullParser.END_TAG) { if (xmlParser.getName().equals(NAME_ELEMENT)) { name = false; } else if (xmlParser.getName().equals(SPEED_ELEMENT)) { speed = false; } else if (xmlParser.getName().equals(ACCURACY_ELEMENT)) { accuracy = false; } else if (xmlParser.getName().equals(COURSE_ELEMENT)) { bearing = false; } else if (xmlParser.getName().equals(ELEVATION_ELEMENT)) { elevation = false; } else if (xmlParser.getName().equals(TIME_ELEMENT)) { time = false; } else if (xmlParser.getName().equals(SEGMENT_ELEMENT)) { if (segmentUri == null) { segmentUri = startSegment( trackUri ); } mContentResolver.bulkInsert(Uri.withAppendedPath(segmentUri, "waypoints"), bulk.toArray(new ContentValues[bulk.size()])); bulk.clear(); } else if (xmlParser.getName().equals(TRACK_ELEMENT)) { if (!lastPosition.containsKey(Waypoints.TIME)) { lastPosition.put(Waypoints.TIME, importDate); } if (!lastPosition.containsKey(Waypoints.SPEED)) { lastPosition.put(Waypoints.SPEED, 0); } bulk.add(lastPosition); lastPosition = null; } } else if (eventType == XmlPullParser.TEXT) { String text = xmlParser.getText(); if (name) { ContentValues nameValues = new ContentValues(); nameValues.put(Tracks.NAME, text); if (trackUri == null) { trackUri = startTrack(new ContentValues()); } mContentResolver.update(trackUri, nameValues, null, null); } else if (lastPosition != null && speed) { lastPosition.put(Waypoints.SPEED, Double.parseDouble(text)); } else if (lastPosition != null && accuracy) { lastPosition.put(Waypoints.ACCURACY, Double.parseDouble(text)); } else if (lastPosition != null && bearing) { lastPosition.put(Waypoints.BEARING, Double.parseDouble(text)); } else if (lastPosition != null && elevation) { lastPosition.put(Waypoints.ALTITUDE, Double.parseDouble(text)); } else if (lastPosition != null && time) { lastPosition.put(Waypoints.TIME, parseXmlDateTime(text)); } } eventType = xmlParser.next(); } } catch (XmlPullParserException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_io)); } finally { try { fis.close(); } catch (IOException e) { Log.w( TAG, "Failed closing inputstream"); } } return trackUri; } private Uri startSegment(Uri trackUri) { if (trackUri == null) { trackUri = startTrack(new ContentValues()); } return mContentResolver.insert(Uri.withAppendedPath(trackUri, "segments"), new ContentValues()); } private Uri startTrack(ContentValues trackContent) { return mContentResolver.insert(Tracks.CONTENT_URI, trackContent); } public static Long parseXmlDateTime(String text) { Long dateTime = 0L; try { if(text==null) { throw new ParseException("Unable to parse dateTime "+text+" of length ", 0); } int length = text.length(); switch (length) { case 20: synchronized (ZULU_DATE_FORMAT) { dateTime = Long.valueOf(ZULU_DATE_FORMAT.parse(text).getTime()); } break; case 23: synchronized (ZULU_DATE_FORMAT_BC) { dateTime = Long.valueOf(ZULU_DATE_FORMAT_BC.parse(text).getTime()); } break; case 24: synchronized (ZULU_DATE_FORMAT_MS) { dateTime = Long.valueOf(ZULU_DATE_FORMAT_MS.parse(text).getTime()); } break; default: throw new ParseException("Unable to parse dateTime "+text+" of length "+length, 0); } } catch (ParseException e) { Log.w(TAG, "Failed to parse a time-date", e); } return dateTime; } /** * * @param e * @param text */ protected void handleError(Exception dialogException, String dialogErrorMessage) { Log.e(TAG, "Unable to save ", dialogException); mErrorDialogException = dialogException; mErrorDialogMessage = dialogErrorMessage; cancel(false); throw new CancellationException(dialogErrorMessage); } @Override protected void onPreExecute() { mProgressListener.started(); } @Override protected Uri doInBackground(Uri... params) { Uri importUri = params[0]; determineProgressGoal( importUri); Uri result = importUri( importUri ); return result; } @Override protected void onProgressUpdate(Void... values) { mProgressListener.setProgress(mProgressAdmin.getProgress()); } @Override protected void onPostExecute(Uri result) { mProgressListener.finished(result); } @Override protected void onCancelled() { mProgressListener.showError(mContext.getString(R.string.taskerror_gpx_import), mErrorDialogMessage, mErrorDialogException); } public class ProgressAdmin { private long progressedBytes; private long contentLength; private int progress; private long lastUpdate; /** * Get the progress. * * @return Returns the progress as a int. */ public int getProgress() { return progress; } public void addBytesProgress(int addedBytes) { progressedBytes += addedBytes; progress = (int) (Window.PROGRESS_END * progressedBytes / contentLength); considerPublishProgress(); } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public void considerPublishProgress() { long now = new Date().getTime(); if( now - lastUpdate > 1000 ) { lastUpdate = now; publishProgress(); } } } };
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxParser.java
Java
gpl3
16,565
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.content.Context; import android.net.Uri; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class KmzSharing extends KmzCreator { public KmzSharing(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { super(context, trackUri, chosenFileName, listener); } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_kmzbody), getContentType()); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/KmzSharing.java
Java
gpl3
2,322
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.util.Xml; /** * Create a KMZ version of a stored track * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class KmzCreator extends XmlCreator { public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"; public static final String NS_KML_22 = "http://www.opengis.net/kml/2.2"; public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true } private String TAG = "OGT.KmzCreator"; public KmzCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { super(context, trackUri, chosenFileName, listener); } @Override protected Uri doInBackground(Void... params) { determineProgressGoal(); Uri resultFilename = exportKml(); return resultFilename; } private Uri exportKml() { if (mFileName.endsWith(".kmz") || mFileName.endsWith(".zip")) { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4)); } else { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName); } new File(getExportDirectoryPath()).mkdirs(); String xmlFilePath = getExportDirectoryPath() + "/doc.kml"; String resultFilename = null; FileOutputStream fos = null; BufferedOutputStream buf = null; try { verifySdCardAvailibility(); XmlSerializer serializer = Xml.newSerializer(); File xmlFile = new File(xmlFilePath); fos = new FileOutputStream(xmlFile); buf = new BufferedOutputStream(fos, 8192); serializer.setOutput(buf, "UTF-8"); serializeTrack(mTrackUri, mFileName, serializer); buf.close(); buf = null; fos.close(); fos = null; resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".kmz"); mFileName = new File(resultFilename).getName(); } catch (IllegalArgumentException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } catch (IllegalStateException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } catch (IOException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } finally { if (buf != null) { try { buf.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buf after completion, ignoring.", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { Log.e(TAG, "Failed to close fos after completion, ignoring.", e); } } } return Uri.fromFile(new File(resultFilename)); } private void serializeTrack(Uri trackUri, String trackName, XmlSerializer serializer) throws IOException { serializer.startDocument("UTF-8", true); serializer.setPrefix("xsi", NS_SCHEMA); serializer.setPrefix("kml", NS_KML_22); serializer.startTag("", "kml"); serializer.attribute(NS_SCHEMA, "schemaLocation", NS_KML_22 + " http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd"); serializer.attribute(null, "xmlns", NS_KML_22); serializer.text("\n"); serializer.startTag("", "Document"); serializer.text("\n"); quickTag(serializer, "", "name", trackName); /* from <name/> upto <Folder/> */ serializeTrackHeader(serializer, trackUri); serializer.text("\n"); serializer.endTag("", "Document"); serializer.endTag("", "kml"); serializer.endDocument(); } private String serializeTrackHeader(XmlSerializer serializer, Uri trackUri) throws IOException { ContentResolver resolver = mContext.getContentResolver(); Cursor trackCursor = null; String name = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "Style"); serializer.attribute(null, "id", "lineStyle"); serializer.startTag("", "LineStyle"); serializer.text("\n"); serializer.startTag("", "color"); serializer.text("99ffac59"); serializer.endTag("", "color"); serializer.text("\n"); serializer.startTag("", "width"); serializer.text("6"); serializer.endTag("", "width"); serializer.text("\n"); serializer.endTag("", "LineStyle"); serializer.text("\n"); serializer.endTag("", "Style"); serializer.text("\n"); serializer.startTag("", "Folder"); name = trackCursor.getString(0); serializer.text("\n"); quickTag(serializer, "", "name", name); serializer.text("\n"); serializer.startTag("", "open"); serializer.text("1"); serializer.endTag("", "open"); serializer.text("\n"); serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments")); serializer.text("\n"); serializer.endTag("", "Folder"); } } finally { if (trackCursor != null) { trackCursor.close(); } } return name; } /** * <pre> * &lt;Folder> * &lt;Placemark> * serializeSegmentToTimespan() * &lt;LineString> * serializeWaypoints() * &lt;/LineString> * &lt;/Placemark> * &lt;Placemark/> * &lt;Placemark/> * &lt;/Folder> * </pre> * * @param serializer * @param segments * @throws IOException */ private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException { Cursor segmentCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null); if (segmentCursor.moveToFirst()) { do { Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints"); serializer.text("\n"); serializer.startTag("", "Folder"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text(String.format("Segment %d", 1 + segmentCursor.getPosition())); serializer.endTag("", "name"); serializer.text("\n"); serializer.startTag("", "open"); serializer.text("1"); serializer.endTag("", "open"); /* Single <TimeSpan/> element */ serializeSegmentToTimespan(serializer, waypoints); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text("Path"); serializer.endTag("", "name"); serializer.text("\n"); serializer.startTag("", "styleUrl"); serializer.text("#lineStyle"); serializer.endTag("", "styleUrl"); serializer.text("\n"); serializer.startTag("", "LineString"); serializer.text("\n"); serializer.startTag("", "tessellate"); serializer.text("0"); serializer.endTag("", "tessellate"); serializer.text("\n"); serializer.startTag("", "altitudeMode"); serializer.text("clampToGround"); serializer.endTag("", "altitudeMode"); /* Single <coordinates/> element */ serializeWaypoints(serializer, waypoints); serializer.text("\n"); serializer.endTag("", "LineString"); serializer.text("\n"); serializer.endTag("", "Placemark"); serializeWaypointDescription(serializer, Uri.withAppendedPath(segments, "/" + segmentCursor.getLong(0) + "/media")); serializer.text("\n"); serializer.endTag("", "Folder"); } while (segmentCursor.moveToNext()); } } finally { if (segmentCursor != null) { segmentCursor.close(); } } } /** * &lt;TimeSpan>&lt;begin>...&lt;/begin>&lt;end>...&lt;/end>&lt;/TimeSpan> * * @param serializer * @param waypoints * @throws IOException */ private void serializeSegmentToTimespan(XmlSerializer serializer, Uri waypoints) throws IOException { Cursor waypointsCursor = null; Date segmentStartTime = null; Date segmentEndTime = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.TIME }, null, null, null); if (waypointsCursor.moveToFirst()) { segmentStartTime = new Date(waypointsCursor.getLong(0)); if (waypointsCursor.moveToLast()) { segmentEndTime = new Date(waypointsCursor.getLong(0)); serializer.text("\n"); serializer.startTag("", "TimeSpan"); serializer.text("\n"); serializer.startTag("", "begin"); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(segmentStartTime)); serializer.endTag("", "begin"); serializer.text("\n"); serializer.startTag("", "end"); serializer.text(ZULU_DATE_FORMATER.format(segmentEndTime)); } serializer.endTag("", "end"); serializer.text("\n"); serializer.endTag("", "TimeSpan"); } } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } /** * &lt;coordinates>...&lt;/coordinates> * * @param serializer * @param waypoints * @throws IOException */ private void serializeWaypoints(XmlSerializer serializer, Uri waypoints) throws IOException { Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null); if (waypointsCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "coordinates"); do { mProgressAdmin.addWaypointProgress(1); // Single Coordinate tuple serializeCoordinates(serializer, waypointsCursor); serializer.text(" "); } while (waypointsCursor.moveToNext()); serializer.endTag("", "coordinates"); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } /** * lon,lat,alt tuple without trailing spaces * * @param serializer * @param waypointsCursor * @throws IOException */ private void serializeCoordinates(XmlSerializer serializer, Cursor waypointsCursor) throws IOException { serializer.text(Double.toString(waypointsCursor.getDouble(0))); serializer.text(","); serializer.text(Double.toString(waypointsCursor.getDouble(1))); serializer.text(","); serializer.text(Double.toString(waypointsCursor.getDouble(2))); } private void serializeWaypointDescription(XmlSerializer serializer, Uri media) throws IOException { String mediaPathPrefix = Constants.getSdCardDirectory(mContext); Cursor mediaCursor = null; ContentResolver resolver = mContext.getContentResolver(); BufferedReader buf = null; try { mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri mediaUri = Uri.parse(mediaCursor.getString(0)); Uri singleWaypointUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mediaCursor.getLong(1) + "/segments/" + mediaCursor.getLong(2) + "/waypoints/" + mediaCursor.getLong(3)); String lastPathSegment = mediaUri.getLastPathSegment(); if (mediaUri.getScheme().equals("file")) { if (lastPathSegment.endsWith("3gp")) { String includedMediaFile = includeMediaFile(lastPathSegment); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); serializer.startTag("", "description"); String kmlAudioUnsupported = mContext.getString(R.string.kmlVideoUnsupported); serializer.text(String.format(kmlAudioUnsupported, includedMediaFile)); serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (lastPathSegment.endsWith("jpg")) { String includedMediaFile = includeMediaFile(mediaPathPrefix + lastPathSegment); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); quickTag(serializer, "", "description", "<img src=\"" + includedMediaFile + "\" width=\"500px\"/><br/>" + lastPathSegment); serializer.text("\n"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (lastPathSegment.endsWith("txt")) { serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); serializer.startTag("", "description"); if(buf != null ) buf.close(); buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath())); String line; while ((line = buf.readLine()) != null) { serializer.text(line); serializer.text("\n"); } serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } } else if (mediaUri.getScheme().equals("content")) { if (mediaUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (mediaUri.getAuthority().equals("media")) { Cursor mediaItemCursor = null; try { mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null); if (mediaItemCursor.moveToFirst()) { String includedMediaFile = includeMediaFile(mediaItemCursor.getString(0)); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", mediaItemCursor.getString(1)); serializer.text("\n"); serializer.startTag("", "description"); String kmlAudioUnsupported = mContext.getString(R.string.kmlAudioUnsupported); serializer.text(String.format(kmlAudioUnsupported, includedMediaFile)); serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } } finally { if (mediaItemCursor != null) { mediaItemCursor.close(); } } } } } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } if(buf != null ) buf.close(); } } /** * &lt;Point>...&lt;/Point> &lt;shape>rectangle&lt;/shape> * * @param serializer * @param singleWaypointUri * @throws IllegalArgumentException * @throws IllegalStateException * @throws IOException */ private void serializeMediaPoint(XmlSerializer serializer, Uri singleWaypointUri) throws IllegalArgumentException, IllegalStateException, IOException { Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(singleWaypointUri, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null); if (waypointsCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "Point"); serializer.text("\n"); serializer.startTag("", "coordinates"); serializeCoordinates(serializer, waypointsCursor); serializer.endTag("", "coordinates"); serializer.text("\n"); serializer.endTag("", "Point"); serializer.text("\n"); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } @Override protected String getContentType() { return "application/vnd.google-earth.kmz"; } @Override public boolean needsBundling() { return true; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/KmzCreator.java
Java
gpl3
23,091
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.File; import java.io.IOException; import java.io.InputStream; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.map.LoggerMapHelper; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.HttpMultipartMode; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class OsmSharing extends GpxCreator { public static final String OAUTH_TOKEN = "openstreetmap_oauth_token"; public static final String OAUTH_TOKEN_SECRET = "openstreetmap_oauth_secret"; private static final String TAG = "OGT.OsmSharing"; public static final String OSM_FILENAME = "OSM_Trace"; private String responseText; private Uri mFileUri; public OsmSharing(Activity context, Uri trackUri, boolean attachments, ProgressListener listener) { super(context, trackUri, OSM_FILENAME, attachments, listener); } public void resumeOsmSharing(Uri fileUri, Uri trackUri) { mFileUri = fileUri; mTrackUri = trackUri; execute(); } @Override protected Uri doInBackground(Void... params) { if( mFileUri == null ) { mFileUri = super.doInBackground(params); } sendToOsm(mFileUri, mTrackUri); return mFileUri; } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); CharSequence text = mContext.getString(R.string.osm_success) + responseText; Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); toast.show(); } /** * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website * publishing this track to the public. * * @param fileUri * @param contentType */ private void sendToOsm(final Uri fileUri, final Uri trackUri) { CommonsHttpOAuthConsumer consumer = osmConnectionSetup(); if( consumer == null ) { requestOpenstreetmapOauthToken(); handleError(mContext.getString(R.string.osm_task), null, mContext.getString(R.string.osmauth_message)); } String visibility = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.OSM_VISIBILITY, "trackable"); File gpxFile = new File(fileUri.getEncodedPath()); String url = mContext.getString(R.string.osm_post_url); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; int statusCode = 0; Cursor metaData = null; String sources = null; HttpEntity responseEntity = null; try { metaData = mContext.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"), new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { sources = metaData.getString(0); } if (sources != null && sources.contains(LoggerMapHelper.GOOGLE_PROVIDER)) { throw new IOException("Unable to upload track with materials derived from Google Maps."); } // The POST to the create node HttpPost method = new HttpPost(url); String tags = mContext.getString(R.string.osm_tag) + " " +queryForNotes(); // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new FileBody(gpxFile)); entity.addPart("description", new StringBody( ShareTrack.queryForTrackName(mContext.getContentResolver(), mTrackUri))); entity.addPart("tags", new StringBody(tags)); entity.addPart("visibility", new StringBody(visibility)); method.setEntity(entity); // Execute the POST to OpenStreetMap consumer.sign(method); response = httpclient.execute(method); // Read the response statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); } catch (OAuthMessageSignerException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (OAuthExpectationFailedException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (OAuthCommunicationException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (IOException e) { responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } if (metaData != null) { metaData.close(); } } if (statusCode != 200) { Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText); String text = mContext.getString(R.string.osm_failed) + responseText; if( statusCode == 401 ) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); } handleError(mContext.getString(R.string.osm_task), new HttpException("Unexpected status reported by OSM"), text); } } private CommonsHttpOAuthConsumer osmConnectionSetup() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); boolean mAuthorized = !"".equals(token) && !"".equals(secret); CommonsHttpOAuthConsumer consumer = null; if (mAuthorized) { consumer = new CommonsHttpOAuthConsumer(mContext.getString(R.string.OSM_CONSUMER_KEY), mContext.getString(R.string.OSM_CONSUMER_SECRET)); consumer.setTokenWithSecret(token, secret); } return consumer; } private String queryForNotes() { StringBuilder tags = new StringBuilder(); ContentResolver resolver = mContext.getContentResolver(); Cursor mediaCursor = null; Uri mediaUri = Uri.withAppendedPath(mTrackUri, "media"); try { mediaCursor = resolver.query(mediaUri, new String[] { Media.URI }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri noteUri = Uri.parse(mediaCursor.getString(0)); if (noteUri.getScheme().equals("content") && noteUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { String tag = noteUri.getLastPathSegment().trim(); if (!tag.contains(" ")) { if (tags.length() > 0) { tags.append(" "); } tags.append(tag); } } } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } } return tags.toString(); } public void requestOpenstreetmapOauthToken() { Intent intent = new Intent(mContext.getApplicationContext(), PrepareRequestTokenActivity.class); intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN); intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET); intent.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, mContext.getString(R.string.OSM_CONSUMER_KEY)); intent.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, mContext.getString(R.string.OSM_CONSUMER_SECRET)); intent.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.OSM_REQUEST_URL); intent.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.OSM_ACCESS_URL); intent.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.OSM_AUTHORIZE_URL); mContext.startActivity(intent); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/OsmSharing.java
Java
gpl3
12,525
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.content.Context; import android.net.Uri; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class GpxSharing extends GpxCreator { public GpxSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, attachments, listener); } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_gpxbody), getContentType()); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxSharing.java
Java
gpl3
2,365
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.util.List; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsTracks; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.SpinnerAdapter; /** * Empty Activity that pops up the dialog to describe the track * * @version $Id: NameTrack.java 888 2011-03-14 19:44:44Z rcgroot@gmail.com $ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class DescribeTrack extends Activity { private static final int DIALOG_TRACKDESCRIPTION = 42; protected static final String TAG = "OGT.DescribeTrack"; private static final String ACTIVITY_ID = "ACTIVITY_ID"; private static final String BUNDLE_ID = "BUNDLE_ID"; private Spinner mActivitySpinner; private Spinner mBundleSpinner; private EditText mDescriptionText; private CheckBox mPublicCheck; private Button mOkayButton; private boolean paused; private Uri mTrackUri; private ProgressBar mProgressSpinner; private AlertDialog mDialog; private BreadcrumbsService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVisible(false); paused = false; mTrackUri = this.getIntent().getData(); Intent service = new Intent(this, BreadcrumbsService.class); startService(service); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, BreadcrumbsService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } /* * (non-Javadoc) * @see com.google.android.maps.MapActivity#onPause() */ @Override protected void onResume() { super.onResume(); if (mTrackUri != null) { showDialog(DIALOG_TRACKDESCRIPTION); } else { Log.e(TAG, "Describing track without a track URI supplied."); finish(); } } @Override protected void onPause() { super.onPause(); paused = true; } @Override protected void onStop() { if (mBound) { unbindService(mConnection); mBound = false; mService = null; } super.onStop(); } @Override protected void onDestroy() { if (isFinishing()) { Intent service = new Intent(this, BreadcrumbsService.class); stopService(service); } super.onDestroy(); } @Override protected Dialog onCreateDialog(int id) { LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_TRACKDESCRIPTION: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.describedialog, null); mActivitySpinner = (Spinner) view.findViewById(R.id.activity); mBundleSpinner = (Spinner) view.findViewById(R.id.bundle); mDescriptionText = (EditText) view.findViewById(R.id.description); mPublicCheck = (CheckBox) view.findViewById(R.id.public_checkbox); mProgressSpinner = (ProgressBar) view.findViewById(R.id.progressSpinner); builder.setTitle(R.string.dialog_description_title).setMessage(R.string.dialog_description_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_okay, mTrackDescriptionDialogListener).setNegativeButton(R.string.btn_cancel, mTrackDescriptionDialogListener).setView(view); mDialog = builder.create(); setUiEnabled(); mDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!paused) { finish(); } } }); return mDialog; default: return super.onCreateDialog(id); } } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_TRACKDESCRIPTION: setUiEnabled(); connectBreadcrumbs(); break; default: super.onPrepareDialog(id, dialog); break; } } private void connectBreadcrumbs() { if (mService != null && !mService.isAuthorized()) { mService.collectBreadcrumbsOauthToken(); } } private void saveBreadcrumbsPreference(int activityPosition, int bundlePosition) { Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(ACTIVITY_ID, activityPosition); editor.putInt(BUNDLE_ID, bundlePosition); editor.commit(); } private void loadBreadcrumbsPreference() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); int activityPos = prefs.getInt(ACTIVITY_ID, 0); activityPos = activityPos < mActivitySpinner.getCount() ? activityPos : 0; mActivitySpinner.setSelection(activityPos); int bundlePos = prefs.getInt(BUNDLE_ID, 0); bundlePos = bundlePos < mBundleSpinner.getCount() ? bundlePos : 0; mBundleSpinner.setSelection(bundlePos); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } private void setUiEnabled() { boolean enabled = mService != null && mService.isAuthorized(); if (mProgressSpinner != null) { if (enabled) { mProgressSpinner.setVisibility(View.GONE); } else { mProgressSpinner.setVisibility(View.VISIBLE); } } if (mDialog != null) { mOkayButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE); } for (View view : new View[] { mActivitySpinner, mBundleSpinner, mDescriptionText, mPublicCheck, mOkayButton }) { if (view != null) { view.setEnabled(enabled); } } if (enabled) { mActivitySpinner.setAdapter(getActivityAdapter()); mBundleSpinner.setAdapter(getBundleAdapter()); loadBreadcrumbsPreference(); } } public SpinnerAdapter getActivityAdapter() { List<Pair<Integer, Integer>> activities = mService.getActivityList(); ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, activities); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } public SpinnerAdapter getBundleAdapter() { List<Pair<Integer, Integer>> bundles = mService.getBundleList(); ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, bundles); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; setUiEnabled(); } @Override public void onServiceDisconnected(ComponentName arg0) { mService = null; mBound = false; } }; private final DialogInterface.OnClickListener mTrackDescriptionDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Integer activityId = ((Pair<Integer, Integer>)mActivitySpinner.getSelectedItem()).second; Integer bundleId = ((Pair<Integer, Integer>)mBundleSpinner.getSelectedItem()).second; saveBreadcrumbsPreference(mActivitySpinner.getSelectedItemPosition(), mBundleSpinner.getSelectedItemPosition()); String description = mDescriptionText.getText().toString(); String isPublic = Boolean.toString(mPublicCheck.isChecked()); ContentValues[] metaValues = { buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, activityId.toString()), buildContentValues(BreadcrumbsTracks.BUNDLE_ID, bundleId.toString()), buildContentValues(BreadcrumbsTracks.DESCRIPTION, description), buildContentValues(BreadcrumbsTracks.ISPUBLIC, isPublic), }; getContentResolver().bulkInsert(metadataUri, metaValues); Intent data = new Intent(); data.setData(mTrackUri); if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(Constants.NAME)) { data.putExtra(Constants.NAME, getIntent().getExtras().getString(Constants.NAME)); } setResult(RESULT_OK, data); break; case DialogInterface.BUTTON_NEGATIVE: break; default: Log.e(TAG, "Unknown option ending dialog:" + which); break; } finish(); } }; }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/DescribeTrack.java
Java
gpl3
12,639
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.util.Constants; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ComponentName; import android.content.ContentUris; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; /** * Empty Activity that pops up the dialog to name the track * * @version $Id$ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class ControlTracking extends Activity { private static final int DIALOG_LOGCONTROL = 26; private static final String TAG = "OGT.ControlTracking"; private GPSLoggerServiceManager mLoggerServiceManager; private Button start; private Button pause; private Button resume; private Button stop; private boolean paused; private final View.OnClickListener mLoggingControlListener = new View.OnClickListener() { @Override public void onClick( View v ) { int id = v.getId(); Intent intent = new Intent(); switch( id ) { case R.id.logcontrol_start: long loggerTrackId = mLoggerServiceManager.startGPSLogging( null ); // Start a naming of the track Intent namingIntent = new Intent( ControlTracking.this, NameTrack.class ); namingIntent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) ); startActivity( namingIntent ); // Create data for the caller that a new track has been started ComponentName caller = ControlTracking.this.getCallingActivity(); if( caller != null ) { intent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) ); setResult( RESULT_OK, intent ); } break; case R.id.logcontrol_pause: mLoggerServiceManager.pauseGPSLogging(); setResult( RESULT_OK, intent ); break; case R.id.logcontrol_resume: mLoggerServiceManager.resumeGPSLogging(); setResult( RESULT_OK, intent ); break; case R.id.logcontrol_stop: mLoggerServiceManager.stopGPSLogging(); setResult( RESULT_OK, intent ); break; default: setResult( RESULT_CANCELED, intent ); break; } finish(); } }; private OnClickListener mDialogClickListener = new OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { setResult( RESULT_CANCELED, new Intent() ); finish(); } }; @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); this.setVisible( false ); paused = false; mLoggerServiceManager = new GPSLoggerServiceManager( this ); } @Override protected void onResume() { super.onResume(); mLoggerServiceManager.startup( this, new Runnable() { @Override public void run() { showDialog( DIALOG_LOGCONTROL ); } } ); } @Override protected void onPause() { super.onPause(); mLoggerServiceManager.shutdown( this ); paused = true; } @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch( id ) { case DIALOG_LOGCONTROL: builder = new AlertDialog.Builder( this ); factory = LayoutInflater.from( this ); view = factory.inflate( R.layout.logcontrol, null ); builder.setTitle( R.string.dialog_tracking_title ). setIcon( android.R.drawable.ic_dialog_alert ). setNegativeButton( R.string.btn_cancel, mDialogClickListener ). setView( view ); dialog = builder.create(); start = (Button) view.findViewById( R.id.logcontrol_start ); pause = (Button) view.findViewById( R.id.logcontrol_pause ); resume = (Button) view.findViewById( R.id.logcontrol_resume ); stop = (Button) view.findViewById( R.id.logcontrol_stop ); start.setOnClickListener( mLoggingControlListener ); pause.setOnClickListener( mLoggingControlListener ); resume.setOnClickListener( mLoggingControlListener ); stop.setOnClickListener( mLoggingControlListener ); dialog.setOnDismissListener( new OnDismissListener() { @Override public void onDismiss( DialogInterface dialog ) { if( !paused ) { finish(); } } }); return dialog; default: return super.onCreateDialog( id ); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog( int id, Dialog dialog ) { switch( id ) { case DIALOG_LOGCONTROL: updateDialogState( mLoggerServiceManager.getLoggingState() ); break; default: break; } super.onPrepareDialog( id, dialog ); } private void updateDialogState( int state ) { switch( state ) { case Constants.STOPPED: start.setEnabled( true ); pause.setEnabled( false ); resume.setEnabled( false ); stop.setEnabled( false ); break; case Constants.LOGGING: start.setEnabled( false ); pause.setEnabled( true ); resume.setEnabled( false ); stop.setEnabled( true ); break; case Constants.PAUSED: start.setEnabled( false ); pause.setEnabled( false ); resume.setEnabled( true ); stop.setEnabled( true ); break; default: Log.w( TAG, String.format( "State %d of logging, enabling and hope for the best....", state ) ); start.setEnabled( false ); pause.setEnabled( false ); resume.setEnabled( false ); stop.setEnabled( false ); break; } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/ControlTracking.java
Java
gpl3
8,784
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.util.Constants; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * Empty Activity that pops up the dialog to add a note to the most current * point in the logger service * * @version $Id$ * @author rene (c) Jul 27, 2010, Sogeti B.V. */ public class InsertNote extends Activity { private static final int DIALOG_INSERTNOTE = 27; private static final String TAG = "OGT.InsertNote"; private static final int MENU_PICTURE = 9; private static final int MENU_VOICE = 11; private static final int MENU_VIDEO = 12; private static final int DIALOG_TEXT = 32; private static final int DIALOG_NAME = 33; private GPSLoggerServiceManager mLoggerServiceManager; /** * Action to take when the LoggerService is bound */ private Runnable mServiceBindAction; private boolean paused; private Button name; private Button text; private Button voice; private Button picture; private Button video; private EditText mNoteNameView; private EditText mNoteTextView; private final OnClickListener mNoteTextDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String noteText = mNoteTextView.getText().toString(); Calendar c = Calendar.getInstance(); String newName = String.format("Textnote_%tY-%tm-%td_%tH%tM%tS.txt", c, c, c, c, c, c); File file = new File(Constants.getSdCardDirectory(InsertNote.this) + newName); FileWriter filewriter = null; try { file.getParentFile().mkdirs(); file.createNewFile(); filewriter = new FileWriter(file); filewriter.append(noteText); filewriter.flush(); } catch (IOException e) { Log.e(TAG, "Note storing failed", e); CharSequence text = e.getLocalizedMessage(); Toast toast = Toast.makeText(InsertNote.this, text, Toast.LENGTH_LONG); toast.show(); } finally { if (filewriter != null) { try { filewriter.close(); } catch (IOException e) { /* */ } } } InsertNote.this.mLoggerServiceManager.storeMediaUri(Uri.fromFile(file)); setResult(RESULT_CANCELED, new Intent()); finish(); } }; private final OnClickListener mNoteNameDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = mNoteNameView.getText().toString(); Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(name)); InsertNote.this.mLoggerServiceManager.storeMediaUri(media); setResult(RESULT_CANCELED, new Intent()); finish(); } }; private final View.OnClickListener mNoteInsertListener = new View.OnClickListener() { @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.noteinsert_picture: addPicture(); break; case R.id.noteinsert_video: addVideo(); break; case R.id.noteinsert_voice: addVoice(); break; case R.id.noteinsert_text: showDialog(DIALOG_TEXT); break; case R.id.noteinsert_name: showDialog(DIALOG_NAME); break; default: setResult(RESULT_CANCELED, new Intent()); finish(); break; } } }; private OnClickListener mDialogClickListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED, new Intent()); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVisible(false); paused = false; mLoggerServiceManager = new GPSLoggerServiceManager(this); } @Override protected void onResume() { super.onResume(); if (mServiceBindAction == null) { mServiceBindAction = new Runnable() { @Override public void run() { showDialog(DIALOG_INSERTNOTE); } }; } ; mLoggerServiceManager.startup(this, mServiceBindAction); } @Override protected void onPause() { super.onPause(); mLoggerServiceManager.shutdown(this); paused = true; } /* * (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, * android.content.Intent) */ @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mServiceBindAction = new Runnable() { @Override public void run() { if (resultCode != RESULT_CANCELED) { File file; Uri uri; File newFile; String newName; Uri fileUri; android.net.Uri.Builder builder; boolean isLocal = false; switch (requestCode) { case MENU_PICTURE: file = new File(Constants.getSdCardTmpFile(InsertNote.this)); Calendar c = Calendar.getInstance(); newName = String.format("Picture_%tY-%tm-%td_%tH%tM%tS.jpg", c, c, c, c, c, c); newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName); file.getParentFile().mkdirs(); isLocal = file.renameTo(newFile); // if (!isLocal) { Log.w(TAG, "Failed rename will try copy image: " + file.getAbsolutePath()); isLocal = copyFile(file, newFile); } if (isLocal) { System.gc(); Options opts = new Options(); opts.inJustDecodeBounds = true; Bitmap bm = BitmapFactory.decodeFile(newFile.getAbsolutePath(), opts); String height, width; if (bm != null) { height = Integer.toString(bm.getHeight()); width = Integer.toString(bm.getWidth()); } else { height = Integer.toString(opts.outHeight); width = Integer.toString(opts.outWidth); } bm = null; builder = new Uri.Builder(); fileUri = builder.scheme("file").appendEncodedPath("/").appendEncodedPath(newFile.getAbsolutePath()) .appendQueryParameter("width", width).appendQueryParameter("height", height).build(); InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri); } else { Log.e(TAG, "Failed either rename or copy image: " + file.getAbsolutePath()); } break; case MENU_VIDEO: file = new File(Constants.getSdCardTmpFile(InsertNote.this)); c = Calendar.getInstance(); newName = String.format("Video_%tY%tm%td_%tH%tM%tS.3gp", c, c, c, c, c, c); newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName); file.getParentFile().mkdirs(); isLocal = file.renameTo(newFile); if (!isLocal) { Log.w(TAG, "Failed rename will try copy video: " + file.getAbsolutePath()); isLocal = copyFile(file, newFile); } if (isLocal) { builder = new Uri.Builder(); fileUri = builder.scheme("file").appendPath(newFile.getAbsolutePath()).build(); InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri); } else { Log.e(TAG, "Failed either rename or copy video: " + file.getAbsolutePath()); } break; case MENU_VOICE: uri = Uri.parse(intent.getDataString()); InsertNote.this.mLoggerServiceManager.storeMediaUri(uri); break; default: Log.e(TAG, "Returned form unknow activity: " + requestCode); break; } } else { Log.w(TAG, "Received unexpected resultcode " + resultCode); } setResult(resultCode, new Intent()); finish(); } }; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_INSERTNOTE: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.insertnote, null); builder.setTitle(R.string.menu_insertnote).setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(R.string.btn_cancel, mDialogClickListener) .setView(view); dialog = builder.create(); name = (Button) view.findViewById(R.id.noteinsert_name); text = (Button) view.findViewById(R.id.noteinsert_text); voice = (Button) view.findViewById(R.id.noteinsert_voice); picture = (Button) view.findViewById(R.id.noteinsert_picture); video = (Button) view.findViewById(R.id.noteinsert_video); name.setOnClickListener(mNoteInsertListener); text.setOnClickListener(mNoteInsertListener); voice.setOnClickListener(mNoteInsertListener); picture.setOnClickListener(mNoteInsertListener); video.setOnClickListener(mNoteInsertListener); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (!paused) { finish(); } } }); return dialog; case DIALOG_TEXT: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.notetextdialog, null); mNoteTextView = (EditText) view.findViewById(R.id.notetext); builder.setTitle(R.string.dialog_notetext_title).setMessage(R.string.dialog_notetext_message).setIcon(android.R.drawable.ic_dialog_map) .setPositiveButton(R.string.btn_okay, mNoteTextDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view); dialog = builder.create(); return dialog; case DIALOG_NAME: builder = new AlertDialog.Builder(this); factory = LayoutInflater.from(this); view = factory.inflate(R.layout.notenamedialog, null); mNoteNameView = (EditText) view.findViewById(R.id.notename); builder.setTitle(R.string.dialog_notename_title).setMessage(R.string.dialog_notename_message).setIcon(android.R.drawable.ic_dialog_map) .setPositiveButton(R.string.btn_okay, mNoteNameDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view); dialog = builder.create(); return dialog; default: return super.onCreateDialog(id); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_INSERTNOTE: boolean prepared = mLoggerServiceManager.isMediaPrepared() && mLoggerServiceManager.getLoggingState() == Constants.LOGGING; name = (Button) dialog.findViewById(R.id.noteinsert_name); text = (Button) dialog.findViewById(R.id.noteinsert_text); voice = (Button) dialog.findViewById(R.id.noteinsert_voice); picture = (Button) dialog.findViewById(R.id.noteinsert_picture); video = (Button) dialog.findViewById(R.id.noteinsert_video); name.setEnabled(prepared); text.setEnabled(prepared); voice.setEnabled(prepared); picture.setEnabled(prepared); video.setEnabled(prepared); break; default: break; } super.onPrepareDialog(id, dialog); } /*** * Collecting additional data */ private void addPicture() { Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Constants.getSdCardTmpFile(this)); // Log.d( TAG, "Picture requested at: " + file ); i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(i, MENU_PICTURE); } /*** * Collecting additional data */ private void addVideo() { Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE); File file = new File(Constants.getSdCardTmpFile(this)); i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1); try { startActivityForResult(i, MENU_VIDEO); } catch (ActivityNotFoundException e) { Log.e(TAG, "Unable to start Activity to record video", e); } } private void addVoice() { Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION); try { startActivityForResult(intent, MENU_VOICE); } catch (ActivityNotFoundException e) { Log.e(TAG, "Unable to start Activity to record audio", e); } } private static boolean copyFile(File fileIn, File fileOut) { boolean succes = false; FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(fileIn); out = new FileOutputStream(fileOut); byte[] buf = new byte[8192]; int i = 0; while ((i = in.read(buf)) != -1) { out.write(buf, 0, i); } succes = true; } catch (IOException e) { Log.e(TAG, "File copy failed", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { Log.w(TAG, "File close after copy failed", e); } } if (in != null) { try { out.close(); } catch (IOException e) { Log.w(TAG, "File close after copy failed", e); } } } return succes; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/InsertNote.java
Java
gpl3
18,617
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator; import nl.sogeti.android.gpstracker.actions.tasks.GpxSharing; import nl.sogeti.android.gpstracker.actions.tasks.JogmapSharing; import nl.sogeti.android.gpstracker.actions.tasks.KmzCreator; import nl.sogeti.android.gpstracker.actions.tasks.KmzSharing; import nl.sogeti.android.gpstracker.actions.tasks.OsmSharing; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator; import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RemoteViews; import android.widget.Spinner; import android.widget.Toast; public class ShareTrack extends Activity implements StatisticsDelegate { private static final String TAG = "OGT.ShareTrack"; private static final int EXPORT_TYPE_KMZ = 0; private static final int EXPORT_TYPE_GPX = 1; private static final int EXPORT_TYPE_TEXTLINE = 2; private static final int EXPORT_TARGET_SAVE = 0; private static final int EXPORT_TARGET_SEND = 1; private static final int EXPORT_TARGET_JOGRUN = 2; private static final int EXPORT_TARGET_OSM = 3; private static final int EXPORT_TARGET_BREADCRUMBS = 4; private static final int EXPORT_TARGET_TWITTER = 0; private static final int EXPORT_TARGET_SMS = 1; private static final int EXPORT_TARGET_TEXT = 2; private static final int PROGRESS_STEPS = 10; private static final int DIALOG_ERROR = Menu.FIRST + 28; private static final int DIALOG_CONNECTBREADCRUMBS = Menu.FIRST + 29; private static final int DESCRIBE = 312; private static File sTempBitmap; private RemoteViews mContentView; private int barProgress = 0; private Notification mNotification; private NotificationManager mNotificationManager; private EditText mFileNameView; private EditText mTweetView; private Spinner mShareTypeSpinner; private Spinner mShareTargetSpinner; private Uri mTrackUri; private BreadcrumbsService mService; boolean mBound = false; private String mErrorDialogMessage; private Throwable mErrorDialogException; private ImageView mImageView; private ImageButton mCloseImageView; private Uri mImageUri; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sharedialog); Intent service = new Intent(this, BreadcrumbsService.class); startService(service); mTrackUri = getIntent().getData(); mFileNameView = (EditText) findViewById(R.id.fileNameField); mTweetView = (EditText) findViewById(R.id.tweetField); mImageView = (ImageView) findViewById(R.id.imageView); mCloseImageView = (ImageButton) findViewById(R.id.closeImageView); mShareTypeSpinner = (Spinner) findViewById(R.id.shareTypeSpinner); ArrayAdapter<CharSequence> shareTypeAdapter = ArrayAdapter.createFromResource(this, R.array.sharetype_choices, android.R.layout.simple_spinner_item); shareTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTypeSpinner.setAdapter(shareTypeAdapter); mShareTargetSpinner = (Spinner) findViewById(R.id.shareTargetSpinner); mShareTargetSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3) { if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_GPX && position == EXPORT_TARGET_BREADCRUMBS) { boolean authorized = mService.isAuthorized(); if (!authorized) { showDialog(DIALOG_CONNECTBREADCRUMBS); } } else if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_TEXTLINE && position != EXPORT_TARGET_SMS) { readScreenBitmap(); } else { removeScreenBitmap(); } } @Override public void onNothingSelected(AdapterView< ? > arg0) { /* NOOP */ } }); mShareTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3) { adjustTargetToType(position); } @Override public void onNothingSelected(AdapterView< ? > arg0) { /* NOOP */ } }); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); int lastType = prefs.getInt(Constants.EXPORT_TYPE, EXPORT_TYPE_KMZ); mShareTypeSpinner.setSelection(lastType); adjustTargetToType(lastType); mFileNameView.setText(queryForTrackName(getContentResolver(), mTrackUri)); Button okay = (Button) findViewById(R.id.okayshare_button); okay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); share(); } }); Button cancel = (Button) findViewById(R.id.cancelshare_button); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); ShareTrack.this.finish(); } }); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, BreadcrumbsService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onResume() { super.onResume(); // Upgrade from stored OSM username/password to OAuth authorization SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.contains(Constants.OSM_USERNAME) || prefs.contains(Constants.OSM_PASSWORD)) { Editor editor = prefs.edit(); editor.remove(Constants.OSM_USERNAME); editor.remove(Constants.OSM_PASSWORD); editor.commit(); } findViewById(R.id.okayshare_button).setEnabled(true); findViewById(R.id.cancelshare_button).setEnabled(true); } @Override protected void onStop() { if (mBound) { unbindService(mConnection); mBound = false; mService = null; } super.onStop(); } @Override protected void onDestroy() { if (isFinishing()) { Intent service = new Intent(this, BreadcrumbsService.class); stopService(service); } super.onDestroy(); } /** * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_ERROR: builder = new AlertDialog.Builder(this); String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") "; builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(mErrorDialogMessage + exceptionMessage) .setNeutralButton(android.R.string.cancel, null); dialog = builder.create(); return dialog; case DIALOG_CONNECTBREADCRUMBS: builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_breadcrumbsconnect).setMessage(R.string.dialog_breadcrumbsconnect_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_okay, mBreadcrumbsDialogListener).setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; default: return super.onCreateDialog(id); } } /** * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); AlertDialog alert; switch (id) { case DIALOG_ERROR: alert = (AlertDialog) dialog; String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") "; alert.setMessage(mErrorDialogMessage + exceptionMessage); break; } } private void setGpxExportTargets() { ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharegpxtarget_choices, android.R.layout.simple_spinner_item); shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTargetSpinner.setAdapter(shareTargetAdapter); int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_GPXTARGET, EXPORT_TARGET_SEND); mShareTargetSpinner.setSelection(lastTarget); removeScreenBitmap(); } private void setKmzExportTargets() { ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharekmztarget_choices, android.R.layout.simple_spinner_item); shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTargetSpinner.setAdapter(shareTargetAdapter); int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_KMZTARGET, EXPORT_TARGET_SEND); mShareTargetSpinner.setSelection(lastTarget); removeScreenBitmap(); } private void setTextLineExportTargets() { ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharetexttarget_choices, android.R.layout.simple_spinner_item); shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTargetSpinner.setAdapter(shareTargetAdapter); int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_TXTTARGET, EXPORT_TARGET_TWITTER); mShareTargetSpinner.setSelection(lastTarget); } private void share() { String chosenFileName = mFileNameView.getText().toString(); String textLine = mTweetView.getText().toString(); int type = (int) mShareTypeSpinner.getSelectedItemId(); int target = (int) mShareTargetSpinner.getSelectedItemId(); Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(Constants.EXPORT_TYPE, type); switch (type) { case EXPORT_TYPE_KMZ: editor.putInt(Constants.EXPORT_KMZTARGET, target); editor.commit(); exportKmz(chosenFileName, target); break; case EXPORT_TYPE_GPX: editor.putInt(Constants.EXPORT_GPXTARGET, target); editor.commit(); exportGpx(chosenFileName, target); break; case EXPORT_TYPE_TEXTLINE: editor.putInt(Constants.EXPORT_TXTTARGET, target); editor.commit(); exportTextLine(textLine, target); break; default: Log.e(TAG, "Failed to determine sharing type" + type); break; } } protected void exportKmz(String chosenFileName, int target) { switch (target) { case EXPORT_TARGET_SEND: new KmzSharing(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute(); break; case EXPORT_TARGET_SAVE: new KmzCreator(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute(); break; default: Log.e(TAG, "Unable to determine target for sharing KMZ " + target); break; } ShareTrack.this.finish(); } protected void exportGpx(String chosenFileName, int target) { switch (target) { case EXPORT_TARGET_SAVE: new GpxCreator(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_SEND: new GpxSharing(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_JOGRUN: new JogmapSharing(this, mTrackUri, chosenFileName, false, new ShareProgressListener(chosenFileName)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_OSM: new OsmSharing(this, mTrackUri, false, new ShareProgressListener(OsmSharing.OSM_FILENAME)).execute(); ShareTrack.this.finish(); break; case EXPORT_TARGET_BREADCRUMBS: sendToBreadcrumbs(mTrackUri, chosenFileName); break; default: Log.e(TAG, "Unable to determine target for sharing GPX " + target); break; } } protected void exportTextLine(String message, int target) { String subject = "Open GPS Tracker"; switch (target) { case EXPORT_TARGET_TWITTER: sendTweet(message); break; case EXPORT_TARGET_SMS: sendSMS(message); ShareTrack.this.finish(); break; case EXPORT_TARGET_TEXT: sentGenericText(subject, message); ShareTrack.this.finish(); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_CANCELED) { String name; switch (requestCode) { case DESCRIBE: Uri trackUri = data.getData(); if (data.getExtras() != null && data.getExtras().containsKey(Constants.NAME)) { name = data.getExtras().getString(Constants.NAME); } else { name = "shareToGobreadcrumbs"; } mService.startUploadTask(this, new ShareProgressListener(name), trackUri, name); finish(); break; default: super.onActivityResult(requestCode, resultCode, data); break; } } } private void sendTweet(String tweet) { final Intent intent = findTwitterClient(); intent.putExtra(Intent.EXTRA_TEXT, tweet); if (mImageUri != null) { intent.putExtra(Intent.EXTRA_STREAM, mImageUri); } startActivity(intent); ShareTrack.this.finish(); } private void sendSMS(String msg) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType("vnd.android-dir/mms-sms"); intent.putExtra("sms_body", msg); startActivity(intent); } private void sentGenericText(String subject, String msg) { final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_TEXT, msg); if (mImageUri != null) { intent.putExtra(Intent.EXTRA_STREAM, mImageUri); } startActivity(intent); } private void sendToBreadcrumbs(Uri mTrackUri, String chosenFileName) { // Start a description of the track Intent namingIntent = new Intent(this, DescribeTrack.class); namingIntent.setData(mTrackUri); namingIntent.putExtra(Constants.NAME, chosenFileName); startActivityForResult(namingIntent, DESCRIBE); } private Intent findTwitterClient() { final String[] twitterApps = { // package // name "com.twitter.android", // official "com.twidroid", // twidroyd "com.handmark.tweetcaster", // Tweecaster "com.thedeck.android" // TweetDeck }; Intent tweetIntent = new Intent(Intent.ACTION_SEND); tweetIntent.setType("text/plain"); final PackageManager packageManager = getPackageManager(); List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY); for (int i = 0; i < twitterApps.length; i++) { for (ResolveInfo resolveInfo : list) { String p = resolveInfo.activityInfo.packageName; if (p != null && p.startsWith(twitterApps[i])) { tweetIntent.setPackage(p); } } } return tweetIntent; } private void createTweetText() { StatisticsCalulator calculator = new StatisticsCalulator(this, new UnitsI18n(this), this); findViewById(R.id.tweet_progress).setVisibility(View.VISIBLE); calculator.execute(mTrackUri); } @Override public void finishedCalculations(StatisticsCalulator calculated) { String name = queryForTrackName(getContentResolver(), mTrackUri); String distString = calculated.getDistanceText(); String avgSpeed = calculated.getAvgSpeedText(); String duration = calculated.getDurationText(); String tweetText = String.format(getString(R.string.tweettext, name, distString, avgSpeed, duration)); if (mTweetView.getText().toString().equals("")) { mTweetView.setText(tweetText); } findViewById(R.id.tweet_progress).setVisibility(View.GONE); } private void adjustTargetToType(int position) { switch (position) { case EXPORT_TYPE_KMZ: setKmzExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_GPX: setGpxExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_TEXTLINE: setTextLineExportTargets(); mFileNameView.setVisibility(View.GONE); mTweetView.setVisibility(View.VISIBLE); createTweetText(); break; default: break; } } public static void sendFile(Context context, Uri fileUri, String fileContentType, String body) { Intent sendActionIntent = new Intent(Intent.ACTION_SEND); sendActionIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.email_subject)); sendActionIntent.putExtra(Intent.EXTRA_TEXT, body); sendActionIntent.putExtra(Intent.EXTRA_STREAM, fileUri); sendActionIntent.setType(fileContentType); context.startActivity(Intent.createChooser(sendActionIntent, context.getString(R.string.sender_chooser))); } public static String queryForTrackName(ContentResolver resolver, Uri trackUri) { Cursor trackCursor = null; String name = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToFirst()) { name = trackCursor.getString(0); } } finally { if (trackCursor != null) { trackCursor.close(); } } return name; } public static Uri storeScreenBitmap(Bitmap bm) { Uri fileUri = null; FileOutputStream stream = null; try { clearScreenBitmap(); sTempBitmap = File.createTempFile("shareimage", ".png"); fileUri = Uri.fromFile(sTempBitmap); stream = new FileOutputStream(sTempBitmap); bm.compress(CompressFormat.PNG, 100, stream); } catch (IOException e) { Log.e(TAG, "Bitmap extra storing failed", e); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { Log.e(TAG, "Bitmap extra close failed", e); } } return fileUri; } public static void clearScreenBitmap() { if (sTempBitmap != null && sTempBitmap.exists()) { sTempBitmap.delete(); sTempBitmap = null; } } private void readScreenBitmap() { mImageView.setVisibility(View.GONE); mCloseImageView.setVisibility(View.GONE); if (getIntent().getExtras() != null && getIntent().hasExtra(Intent.EXTRA_STREAM)) { mImageUri = getIntent().getExtras().getParcelable(Intent.EXTRA_STREAM); if (mImageUri != null) { InputStream is = null; try { is = getContentResolver().openInputStream(mImageUri); mImageView.setImageBitmap(BitmapFactory.decodeStream(is)); mImageView.setVisibility(View.VISIBLE); mCloseImageView.setVisibility(View.VISIBLE); mCloseImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { removeScreenBitmap(); } }); } catch (FileNotFoundException e) { Log.e(TAG, "Failed reading image from file", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { Log.e(TAG, "Failed close image from file", e); } } } } } } private void removeScreenBitmap() { mImageView.setVisibility(View.GONE); mCloseImageView.setVisibility(View.GONE); mImageUri = null; } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; mService = null; } }; private OnClickListener mBreadcrumbsDialogListener = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mService.collectBreadcrumbsOauthToken(); } }; public class ShareProgressListener implements ProgressListener { private String mFileName; private int mProgress; public ShareProgressListener(String sharename) { mFileName = sharename; } public void startNotification() { String ns = Context.NOTIFICATION_SERVICE; mNotificationManager = (NotificationManager) ShareTrack.this.getSystemService(ns); int icon = android.R.drawable.ic_menu_save; CharSequence tickerText = getString(R.string.ticker_saving) + "\"" + mFileName + "\""; mNotification = new Notification(); PendingIntent contentIntent = PendingIntent.getActivity(ShareTrack.this, 0, new Intent(ShareTrack.this, LoggerMap.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT); mNotification.contentIntent = contentIntent; mNotification.tickerText = tickerText; mNotification.icon = icon; mNotification.flags |= Notification.FLAG_ONGOING_EVENT; mContentView = new RemoteViews(getPackageName(), R.layout.savenotificationprogress); mContentView.setImageViewResource(R.id.icon, icon); mContentView.setTextViewText(R.id.progresstext, tickerText); mNotification.contentView = mContentView; } private void updateNotification() { // Log.d( "TAG", "Progress " + progress + " of " + goal ); if (mProgress > 0 && mProgress < Window.PROGRESS_END) { if ((mProgress * PROGRESS_STEPS) / Window.PROGRESS_END != barProgress) { barProgress = (mProgress * PROGRESS_STEPS) / Window.PROGRESS_END; mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false); mNotificationManager.notify(R.layout.savenotificationprogress, mNotification); } } else if (mProgress == 0) { mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, true); mNotificationManager.notify(R.layout.savenotificationprogress, mNotification); } else if (mProgress >= Window.PROGRESS_END) { mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false); mNotificationManager.notify(R.layout.savenotificationprogress, mNotification); } } public void endNotification(Uri file) { mNotificationManager.cancel(R.layout.savenotificationprogress); } @Override public void setIndeterminate(boolean indeterminate) { Log.w(TAG, "Unsupported indeterminate progress display"); } @Override public void started() { startNotification(); } @Override public void setProgress(int value) { mProgress = value; updateNotification(); } @Override public void finished(Uri result) { endNotification(result); } @Override public void showError(String task, String errorDialogMessage, Exception errorDialogException) { endNotification(null); mErrorDialogMessage = errorDialogMessage; mErrorDialogException = errorDialogException; if (!isFinishing()) { showDialog(DIALOG_ERROR); } else { Toast toast = Toast.makeText(ShareTrack.this, errorDialogMessage, Toast.LENGTH_LONG); toast.show(); } } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/ShareTrack.java
Java
gpl3
30,165
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.logger; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.LinkedList; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import java.util.concurrent.Semaphore; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.streaming.StreamUtils; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.GpsStatus.Listener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * A system service as controlling the background logging of gps locations. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class GPSLoggerService extends Service implements LocationListener { private static final float FINE_DISTANCE = 5F; private static final long FINE_INTERVAL = 1000l; private static final float FINE_ACCURACY = 20f; private static final float NORMAL_DISTANCE = 10F; private static final long NORMAL_INTERVAL = 15000l; private static final float NORMAL_ACCURACY = 30f; private static final float COARSE_DISTANCE = 25F; private static final long COARSE_INTERVAL = 30000l; private static final float COARSE_ACCURACY = 75f; private static final float GLOBAL_DISTANCE = 500F; private static final long GLOBAL_INTERVAL = 300000l; private static final float GLOBAL_ACCURACY = 1000f; /** * <code>MAX_REASONABLE_SPEED</code> is about 324 kilometer per hour or 201 * mile per hour. */ private static final int MAX_REASONABLE_SPEED = 90; /** * <code>MAX_REASONABLE_ALTITUDECHANGE</code> between the last few waypoints * and a new one the difference should be less then 200 meter. */ private static final int MAX_REASONABLE_ALTITUDECHANGE = 200; private static final Boolean DEBUG = false; private static final boolean VERBOSE = false; private static final String TAG = "OGT.GPSLoggerService"; private static final String SERVICESTATE_DISTANCE = "SERVICESTATE_DISTANCE"; private static final String SERVICESTATE_STATE = "SERVICESTATE_STATE"; private static final String SERVICESTATE_PRECISION = "SERVICESTATE_PRECISION"; private static final String SERVICESTATE_SEGMENTID = "SERVICESTATE_SEGMENTID"; private static final String SERVICESTATE_TRACKID = "SERVICESTATE_TRACKID"; private static final int ADDGPSSTATUSLISTENER = 0; private static final int REQUEST_FINEGPS_LOCATIONUPDATES = 1; private static final int REQUEST_NORMALGPS_LOCATIONUPDATES = 2; private static final int REQUEST_COARSEGPS_LOCATIONUPDATES = 3; private static final int REQUEST_GLOBALNETWORK_LOCATIONUPDATES = 4; private static final int REQUEST_CUSTOMGPS_LOCATIONUPDATES = 5; private static final int STOPLOOPER = 6; private static final int GPSPROBLEM = 7; private static final int LOGGING_UNAVAILABLE = R.string.service_connectiondisabled; /** * DUP from android.app.Service.START_STICKY */ private static final int START_STICKY = 1; public static final String COMMAND = "nl.sogeti.android.gpstracker.extra.COMMAND"; public static final int EXTRA_COMMAND_START = 0; public static final int EXTRA_COMMAND_PAUSE = 1; public static final int EXTRA_COMMAND_RESUME = 2; public static final int EXTRA_COMMAND_STOP = 3; private LocationManager mLocationManager; private NotificationManager mNoticationManager; private PowerManager.WakeLock mWakeLock; private Handler mHandler; /** * If speeds should be checked to sane values */ private boolean mSpeedSanityCheck; /** * If broadcasts of location about should be sent to stream location */ private boolean mStreamBroadcast; private long mTrackId = -1; private long mSegmentId = -1; private long mWaypointId = -1; private int mPrecision; private int mLoggingState = Constants.STOPPED; private boolean mStartNextSegment; private String mSources; private Location mPreviousLocation; private float mDistance; private Notification mNotification; private Vector<Location> mWeakLocations; private Queue<Double> mAltitudes; /** * <code>mAcceptableAccuracy</code> indicates the maximum acceptable accuracy * of a waypoint in meters. */ private float mMaxAcceptableAccuracy = 20; private int mSatellites = 0; private boolean mShowingGpsDisabled; /** * Should the GPS Status monitor update the notification bar */ private boolean mStatusMonitor; /** * Time thread to runs tasks that check whether the GPS listener has received * enough to consider the GPS system alive. */ private Timer mHeartbeatTimer; /** * Listens to changes in preference to precision and sanity checks */ private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.PRECISION) || key.equals(Constants.LOGGING_DISTANCE) || key.equals(Constants.LOGGING_INTERVAL)) { sendRequestLocationUpdatesMessage(); crashProtectState(); updateNotification(); broadCastLoggingState(); } else if (key.equals(Constants.SPEEDSANITYCHECK)) { mSpeedSanityCheck = sharedPreferences.getBoolean(Constants.SPEEDSANITYCHECK, true); } else if (key.equals(Constants.STATUS_MONITOR)) { mLocationManager.removeGpsStatusListener(mStatusListener); sendRequestStatusUpdateMessage(); updateNotification(); } else if(key.equals(Constants.BROADCAST_STREAM) || key.equals("VOICEOVER_ENABLED") || key.equals("CUSTOMUPLOAD_ENABLED") ) { if (key.equals(Constants.BROADCAST_STREAM)) { mStreamBroadcast = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); } StreamUtils.shutdownStreams(GPSLoggerService.this); if( !mStreamBroadcast ) { StreamUtils.initStreams(GPSLoggerService.this); } } } }; @Override public void onLocationChanged(Location location) { if (VERBOSE) { Log.v(TAG, "onLocationChanged( Location " + location + " )"); } ; // Might be claiming GPS disabled but when we were paused this changed and this location proves so if (mShowingGpsDisabled) { notifyOnEnabledProviderNotification(R.string.service_gpsenabled); } Location filteredLocation = locationFilter(location); if (filteredLocation != null) { if (mStartNextSegment) { mStartNextSegment = false; // Obey the start segment if the previous location is unknown or far away if (mPreviousLocation == null || filteredLocation.distanceTo(mPreviousLocation) > 4 * mMaxAcceptableAccuracy) { startNewSegment(); } } else if( mPreviousLocation != null ) { mDistance += mPreviousLocation.distanceTo(filteredLocation); } storeLocation(filteredLocation); broadcastLocation(filteredLocation); mPreviousLocation = location; } } @Override public void onProviderDisabled(String provider) { if (DEBUG) { Log.d(TAG, "onProviderDisabled( String " + provider + " )"); } ; if (mPrecision != Constants.LOGGING_GLOBAL && provider.equals(LocationManager.GPS_PROVIDER)) { notifyOnDisabledProvider(R.string.service_gpsdisabled); } else if (mPrecision == Constants.LOGGING_GLOBAL && provider.equals(LocationManager.NETWORK_PROVIDER)) { notifyOnDisabledProvider(R.string.service_datadisabled); } } @Override public void onProviderEnabled(String provider) { if (DEBUG) { Log.d(TAG, "onProviderEnabled( String " + provider + " )"); } ; if (mPrecision != Constants.LOGGING_GLOBAL && provider.equals(LocationManager.GPS_PROVIDER)) { notifyOnEnabledProviderNotification(R.string.service_gpsenabled); mStartNextSegment = true; } else if (mPrecision == Constants.LOGGING_GLOBAL && provider.equals(LocationManager.NETWORK_PROVIDER)) { notifyOnEnabledProviderNotification(R.string.service_dataenabled); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (DEBUG) { Log.d(TAG, "onStatusChanged( String " + provider + ", int " + status + ", Bundle " + extras + " )"); } ; if (status == LocationProvider.OUT_OF_SERVICE) { Log.e(TAG, String.format("Provider %s changed to status %d", provider, status)); } } /** * Listens to GPS status changes */ private Listener mStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch (event) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: if (mStatusMonitor) { GpsStatus status = mLocationManager.getGpsStatus(null); mSatellites = 0; Iterable<GpsSatellite> list = status.getSatellites(); for (GpsSatellite satellite : list) { if (satellite.usedInFix()) { mSatellites++; } } updateNotification(); } break; case GpsStatus.GPS_EVENT_STOPPED: break; case GpsStatus.GPS_EVENT_STARTED: break; default: break; } } }; private IBinder mBinder = new IGPSLoggerServiceRemote.Stub() { @Override public int loggingState() throws RemoteException { return mLoggingState; } @Override public long startLogging() throws RemoteException { GPSLoggerService.this.startLogging(); return mTrackId; } @Override public void pauseLogging() throws RemoteException { GPSLoggerService.this.pauseLogging(); } @Override public long resumeLogging() throws RemoteException { GPSLoggerService.this.resumeLogging(); return mSegmentId; } @Override public void stopLogging() throws RemoteException { GPSLoggerService.this.stopLogging(); } @Override public Uri storeMediaUri(Uri mediaUri) throws RemoteException { GPSLoggerService.this.storeMediaUri(mediaUri); return null; } @Override public boolean isMediaPrepared() throws RemoteException { return GPSLoggerService.this.isMediaPrepared(); } @Override public void storeDerivedDataSource(String sourceName) throws RemoteException { GPSLoggerService.this.storeDerivedDataSource(sourceName); } @Override public Location getLastWaypoint() throws RemoteException { return GPSLoggerService.this.getLastWaypoint(); } @Override public float getTrackedDistance() throws RemoteException { return GPSLoggerService.this.getTrackedDistance(); } }; /** * Task that will be run periodically during active logging to verify that * the logging really happens and that the GPS hasn't silently stopped. */ private TimerTask mHeartbeat = null; /** * Task to determine if the GPS is alive */ class Heartbeat extends TimerTask { private String mProvider; public Heartbeat(String provider) { mProvider = provider; } @Override public void run() { if (isLogging()) { // Collect the last location from the last logged location or a more recent from the last weak location Location checkLocation = mPreviousLocation; synchronized (mWeakLocations) { if (!mWeakLocations.isEmpty()) { if (checkLocation == null) { checkLocation = mWeakLocations.lastElement(); } else { Location weakLocation = mWeakLocations.lastElement(); checkLocation = weakLocation.getTime() > checkLocation.getTime() ? weakLocation : checkLocation; } } } // Is the last known GPS location something nearby we are not told? Location managerLocation = mLocationManager.getLastKnownLocation(mProvider); if (managerLocation != null && checkLocation != null) { if (checkLocation.distanceTo(managerLocation) < 2 * mMaxAcceptableAccuracy) { checkLocation = managerLocation.getTime() > checkLocation.getTime() ? managerLocation : checkLocation; } } if (checkLocation == null || checkLocation.getTime() + mCheckPeriod < new Date().getTime()) { Log.w(TAG, "GPS system failed to produce a location during logging: " + checkLocation); mLoggingState = Constants.PAUSED; resumeLogging(); if (mStatusMonitor) { soundGpsSignalAlarm(); } } } } }; /** * Number of milliseconds that a functioning GPS system needs to provide a * location. Calculated to be either 120 seconds or 4 times the requested * period, whichever is larger. */ private long mCheckPeriod; private float mBroadcastDistance; private long mLastTimeBroadcast; private class GPSLoggerServiceThread extends Thread { public Semaphore ready = new Semaphore(0); GPSLoggerServiceThread() { this.setName("GPSLoggerServiceThread"); } @Override public void run() { Looper.prepare(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { _handleMessage(msg); } }; ready.release(); // Signal the looper and handler are created Looper.loop(); } } /** * Called by the system when the service is first created. Do not call this * method directly. Be sure to call super.onCreate(). */ @Override public void onCreate() { super.onCreate(); if (DEBUG) { Log.d(TAG, "onCreate()"); } ; GPSLoggerServiceThread looper = new GPSLoggerServiceThread(); looper.start(); try { looper.ready.acquire(); } catch (InterruptedException e) { Log.e(TAG, "Interrupted during wait for the GPSLoggerServiceThread to start, prepare for trouble!", e); } mHeartbeatTimer = new Timer("heartbeat", true); mWeakLocations = new Vector<Location>(3); mAltitudes = new LinkedList<Double>(); mLoggingState = Constants.STOPPED; mStartNextSegment = false; mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mNoticationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); stopNotification(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSpeedSanityCheck = sharedPreferences.getBoolean(Constants.SPEEDSANITYCHECK, true); mStreamBroadcast = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); boolean startImmidiatly = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.LOGATSTARTUP, false); crashRestoreState(); if (startImmidiatly && mLoggingState == Constants.STOPPED) { startLogging(); ContentValues values = new ContentValues(); values.put(Tracks.NAME, "Recorded at startup"); getContentResolver().update(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId), values, null, null); } else { broadCastLoggingState(); } } /** * This is the old onStart method that will be called on the pre-2.0 * * @see android.app.Service#onStart(android.content.Intent, int) platform. On * 2.0 or later we override onStartCommand() so this method will not be * called. */ @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } private void handleCommand(Intent intent) { if (DEBUG) { Log.d(TAG, "handleCommand(Intent " + intent + ")"); } ; if (intent != null && intent.hasExtra(COMMAND)) { switch (intent.getIntExtra(COMMAND, -1)) { case EXTRA_COMMAND_START: startLogging(); break; case EXTRA_COMMAND_PAUSE: pauseLogging(); break; case EXTRA_COMMAND_RESUME: resumeLogging(); break; case EXTRA_COMMAND_STOP: stopLogging(); break; default: break; } } } /** * (non-Javadoc) * * @see android.app.Service#onDestroy() */ @Override public void onDestroy() { if (DEBUG) { Log.d(TAG, "onDestroy()"); } ; super.onDestroy(); if (isLogging()) { Log.w(TAG, "Destroyin an activly logging service"); } mHeartbeatTimer.cancel(); mHeartbeatTimer.purge(); if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); mNoticationManager.cancel(R.layout.map_widgets); Message msg = Message.obtain(); msg.what = STOPLOOPER; mHandler.sendMessage(msg); } private void crashProtectState() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = preferences.edit(); editor.putLong(SERVICESTATE_TRACKID, mTrackId); editor.putLong(SERVICESTATE_SEGMENTID, mSegmentId); editor.putInt(SERVICESTATE_PRECISION, mPrecision); editor.putInt(SERVICESTATE_STATE, mLoggingState); editor.putFloat(SERVICESTATE_DISTANCE, mDistance); editor.commit(); if (DEBUG) { Log.d(TAG, "crashProtectState()"); } ; } private synchronized void crashRestoreState() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); long previousState = preferences.getInt(SERVICESTATE_STATE, Constants.STOPPED); if (previousState == Constants.LOGGING || previousState == Constants.PAUSED) { Log.w(TAG, "Recovering from a crash or kill and restoring state."); startNotification(); mTrackId = preferences.getLong(SERVICESTATE_TRACKID, -1); mSegmentId = preferences.getLong(SERVICESTATE_SEGMENTID, -1); mPrecision = preferences.getInt(SERVICESTATE_PRECISION, -1); mDistance = preferences.getFloat(SERVICESTATE_DISTANCE, 0F); if (previousState == Constants.LOGGING) { mLoggingState = Constants.PAUSED; resumeLogging(); } else if (previousState == Constants.PAUSED) { mLoggingState = Constants.LOGGING; pauseLogging(); } } } /** * (non-Javadoc) * * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return this.mBinder; } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#getLoggingState() */ protected boolean isLogging() { return this.mLoggingState == Constants.LOGGING; } /** * Provides the cached last stored waypoint it current logging is active alse * null. * * @return last waypoint location or null */ protected Location getLastWaypoint() { Location myLastWaypoint = null; if (isLogging()) { myLastWaypoint = mPreviousLocation; } return myLastWaypoint; } public float getTrackedDistance() { float distance = 0F; if (isLogging()) { distance = mDistance; } return distance; } protected boolean isMediaPrepared() { return !(mTrackId < 0 || mSegmentId < 0 || mWaypointId < 0); } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#startLogging() */ public synchronized void startLogging() { if (DEBUG) { Log.d(TAG, "startLogging()"); } ; if (this.mLoggingState == Constants.STOPPED) { startNewTrack(); sendRequestLocationUpdatesMessage(); sendRequestStatusUpdateMessage(); this.mLoggingState = Constants.LOGGING; updateWakeLock(); startNotification(); crashProtectState(); broadCastLoggingState(); } } public synchronized void pauseLogging() { if (DEBUG) { Log.d(TAG, "pauseLogging()"); } ; if (this.mLoggingState == Constants.LOGGING) { mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); mLoggingState = Constants.PAUSED; mPreviousLocation = null; updateWakeLock(); updateNotification(); mSatellites = 0; updateNotification(); crashProtectState(); broadCastLoggingState(); } } public synchronized void resumeLogging() { if (DEBUG) { Log.d(TAG, "resumeLogging()"); } ; if (this.mLoggingState == Constants.PAUSED) { if (mPrecision != Constants.LOGGING_GLOBAL) { mStartNextSegment = true; } sendRequestLocationUpdatesMessage(); sendRequestStatusUpdateMessage(); this.mLoggingState = Constants.LOGGING; updateWakeLock(); updateNotification(); crashProtectState(); broadCastLoggingState(); } } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#stopLogging() */ public synchronized void stopLogging() { if (DEBUG) { Log.d(TAG, "stopLogging()"); } ; mLoggingState = Constants.STOPPED; crashProtectState(); updateWakeLock(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); stopNotification(); broadCastLoggingState(); } private void startListening(String provider, long intervaltime, float distance) { mLocationManager.removeUpdates(this); mLocationManager.requestLocationUpdates(provider, intervaltime, distance, this); mCheckPeriod = Math.max(12 * intervaltime, 120 * 1000); if (mHeartbeat != null) { mHeartbeat.cancel(); mHeartbeat = null; } mHeartbeat = new Heartbeat(provider); mHeartbeatTimer.schedule(mHeartbeat, mCheckPeriod, mCheckPeriod); } private void stopListening() { if (mHeartbeat != null) { mHeartbeat.cancel(); mHeartbeat = null; } mLocationManager.removeUpdates(this); } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#storeDerivedDataSource(java.lang.String) */ public void storeDerivedDataSource(String sourceName) { Uri trackMetaDataUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/metadata"); if (mTrackId >= 0) { if (mSources == null) { Cursor metaData = null; String source = null; try { metaData = this.getContentResolver().query(trackMetaDataUri, new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { source = metaData.getString(0); } } finally { if (metaData != null) { metaData.close(); } } if (source != null) { mSources = source; } else { mSources = sourceName; ContentValues args = new ContentValues(); args.put(MetaData.KEY, Constants.DATASOURCES_KEY); args.put(MetaData.VALUE, mSources); this.getContentResolver().insert(trackMetaDataUri, args); } } if (!mSources.contains(sourceName)) { mSources += "," + sourceName; ContentValues args = new ContentValues(); args.put(MetaData.VALUE, mSources); this.getContentResolver().update(trackMetaDataUri, args, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }); } } } private void startNotification() { mNoticationManager.cancel(R.layout.map_widgets); int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(R.string.service_start); long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); mNotification.flags |= Notification.FLAG_ONGOING_EVENT; updateNotification(); if (Build.VERSION.SDK_INT >= 5) { startForegroundReflected(R.layout.map_widgets, mNotification); } else { mNoticationManager.notify(R.layout.map_widgets, mNotification); } } private void updateNotification() { CharSequence contentTitle = getResources().getString(R.string.app_name); String precision = getResources().getStringArray(R.array.precision_choices)[mPrecision]; String state = getResources().getStringArray(R.array.state_choices)[mLoggingState - 1]; CharSequence contentText; switch (mPrecision) { case (Constants.LOGGING_GLOBAL): contentText = getResources().getString(R.string.service_networkstatus, state, precision); break; default: if (mStatusMonitor) { contentText = getResources().getString(R.string.service_gpsstatus, state, precision, mSatellites); } else { contentText = getResources().getString(R.string.service_gpsnostatus, state, precision); } break; } Intent notificationIntent = new Intent(this, CommonLoggerMap.class); notificationIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); mNotification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); mNotification.setLatestEventInfo(this, contentTitle, contentText, mNotification.contentIntent); mNoticationManager.notify(R.layout.map_widgets, mNotification); } private void stopNotification() { if (Build.VERSION.SDK_INT >= 5) { stopForegroundReflected(true); } else { mNoticationManager.cancel(R.layout.map_widgets); } } private void notifyOnEnabledProviderNotification(int resId) { mNoticationManager.cancel(LOGGING_UNAVAILABLE); mShowingGpsDisabled = false; CharSequence text = this.getString(resId); Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } private void notifyOnPoorSignal(int resId) { int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(resId); long when = System.currentTimeMillis(); Notification signalNotification = new Notification(icon, tickerText, when); CharSequence contentTitle = getResources().getString(R.string.app_name); Intent notificationIntent = new Intent(this, CommonLoggerMap.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); signalNotification.setLatestEventInfo(this, contentTitle, tickerText, contentIntent); signalNotification.flags |= Notification.FLAG_AUTO_CANCEL; mNoticationManager.notify(resId, signalNotification); } private void notifyOnDisabledProvider(int resId) { int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(resId); long when = System.currentTimeMillis(); Notification gpsNotification = new Notification(icon, tickerText, when); gpsNotification.flags |= Notification.FLAG_AUTO_CANCEL; CharSequence contentTitle = getResources().getString(R.string.app_name); CharSequence contentText = getResources().getString(resId); Intent notificationIntent = new Intent(this, CommonLoggerMap.class); notificationIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); gpsNotification.setLatestEventInfo(this, contentTitle, contentText, contentIntent); mNoticationManager.notify(LOGGING_UNAVAILABLE, gpsNotification); mShowingGpsDisabled = true; } /** * Send a system broadcast to notify a change in the logging or precision */ private void broadCastLoggingState() { Intent broadcast = new Intent(Constants.LOGGING_STATE_CHANGED_ACTION); broadcast.putExtra(Constants.EXTRA_LOGGING_PRECISION, mPrecision); broadcast.putExtra(Constants.EXTRA_LOGGING_STATE, mLoggingState); this.getApplicationContext().sendBroadcast(broadcast); if( isLogging() ) { StreamUtils.initStreams(this); } else { StreamUtils.shutdownStreams(this); } } private void sendRequestStatusUpdateMessage() { mStatusMonitor = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.STATUS_MONITOR, false); Message msg = Message.obtain(); msg.what = ADDGPSSTATUSLISTENER; mHandler.sendMessage(msg); } private void sendRequestLocationUpdatesMessage() { stopListening(); mPrecision = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PRECISION, "2")).intValue(); Message msg = Message.obtain(); switch (mPrecision) { case (Constants.LOGGING_FINE): // Fine msg.what = REQUEST_FINEGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_NORMAL): // Normal msg.what = REQUEST_NORMALGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_COARSE): // Coarse msg.what = REQUEST_COARSEGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_GLOBAL): // Global msg.what = REQUEST_GLOBALNETWORK_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_CUSTOM): // Global msg.what = REQUEST_CUSTOMGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; default: Log.e(TAG, "Unknown precision " + mPrecision); break; } } /** * Message handler method to do the work off-loaded by mHandler to * GPSLoggerServiceThread * * @param msg */ private void _handleMessage(Message msg) { if (DEBUG) { Log.d(TAG, "_handleMessage( Message " + msg + " )"); } ; long intervaltime = 0; float distance = 0; switch (msg.what) { case ADDGPSSTATUSLISTENER: this.mLocationManager.addGpsStatusListener(mStatusListener); break; case REQUEST_FINEGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = FINE_ACCURACY; intervaltime = FINE_INTERVAL; distance = FINE_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_NORMALGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = NORMAL_ACCURACY; intervaltime = NORMAL_INTERVAL; distance = NORMAL_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_COARSEGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = COARSE_ACCURACY; intervaltime = COARSE_INTERVAL; distance = COARSE_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_GLOBALNETWORK_LOCATIONUPDATES: mMaxAcceptableAccuracy = GLOBAL_ACCURACY; intervaltime = GLOBAL_INTERVAL; distance = GLOBAL_DISTANCE; startListening(LocationManager.NETWORK_PROVIDER, intervaltime, distance); if (!isNetworkConnected()) { notifyOnDisabledProvider(R.string.service_connectiondisabled); } break; case REQUEST_CUSTOMGPS_LOCATIONUPDATES: intervaltime = 60 * 1000 * Long.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.LOGGING_INTERVAL, "15000")); distance = Float.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.LOGGING_DISTANCE, "10")); mMaxAcceptableAccuracy = Math.max(10f, Math.min(distance, 50f)); startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case STOPLOOPER: mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); Looper.myLooper().quit(); break; case GPSPROBLEM: notifyOnPoorSignal(R.string.service_gpsproblem); break; } } private void updateWakeLock() { if (this.mLoggingState == Constants.LOGGING) { PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } this.mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); this.mWakeLock.acquire(); } else { if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } } } /** * Some GPS waypoints received are of to low a quality for tracking use. Here * we filter those out. * * @param proposedLocation * @return either the (cleaned) original or null when unacceptable */ public Location locationFilter(Location proposedLocation) { // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop if (proposedLocation != null && (proposedLocation.getLatitude() == 0.0d || proposedLocation.getLongitude() == 0.0d)) { Log.w(TAG, "A wrong location was received, 0.0 latitude and 0.0 longitude... "); proposedLocation = null; } // Do not log a waypoint which is more inaccurate then is configured to be acceptable if (proposedLocation != null && proposedLocation.getAccuracy() > mMaxAcceptableAccuracy) { Log.w(TAG, String.format("A weak location was received, lots of inaccuracy... (%f is more then max %f)", proposedLocation.getAccuracy(), mMaxAcceptableAccuracy)); proposedLocation = addBadLocation(proposedLocation); } // Do not log a waypoint which might be on any side of the previous waypoint if (proposedLocation != null && mPreviousLocation != null && proposedLocation.getAccuracy() > mPreviousLocation.distanceTo(proposedLocation)) { Log.w(TAG, String.format("A weak location was received, not quite clear from the previous waypoint... (%f more then max %f)", proposedLocation.getAccuracy(), mPreviousLocation.distanceTo(proposedLocation))); proposedLocation = addBadLocation(proposedLocation); } // Speed checks, check if the proposed location could be reached from the previous one in sane speed // Common to jump on network logging and sometimes jumps on Samsung Galaxy S type of devices if (mSpeedSanityCheck && proposedLocation != null && mPreviousLocation != null) { // To avoid near instant teleportation on network location or glitches cause continent hopping float meters = proposedLocation.distanceTo(mPreviousLocation); long seconds = (proposedLocation.getTime() - mPreviousLocation.getTime()) / 1000L; float speed = meters / seconds; if (speed > MAX_REASONABLE_SPEED) { Log.w(TAG, "A strange location was received, a really high speed of " + speed + " m/s, prob wrong..."); proposedLocation = addBadLocation(proposedLocation); // Might be a messed up Samsung Galaxy S GPS, reset the logging if (speed > 2 * MAX_REASONABLE_SPEED && mPrecision != Constants.LOGGING_GLOBAL) { Log.w(TAG, "A strange location was received on GPS, reset the GPS listeners"); stopListening(); mLocationManager.removeGpsStatusListener(mStatusListener); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); sendRequestStatusUpdateMessage(); sendRequestLocationUpdatesMessage(); } } } // Remove speed if not sane if (mSpeedSanityCheck && proposedLocation != null && proposedLocation.getSpeed() > MAX_REASONABLE_SPEED) { Log.w(TAG, "A strange speed, a really high speed, prob wrong..."); proposedLocation.removeSpeed(); } // Remove altitude if not sane if (mSpeedSanityCheck && proposedLocation != null && proposedLocation.hasAltitude()) { if (!addSaneAltitude(proposedLocation.getAltitude())) { Log.w(TAG, "A strange altitude, a really big difference, prob wrong..."); proposedLocation.removeAltitude(); } } // Older bad locations will not be needed if (proposedLocation != null) { mWeakLocations.clear(); } return proposedLocation; } /** * Store a bad location, when to many bad locations are stored the the * storage is cleared and the least bad one is returned * * @param location bad location * @return null when the bad location is stored or the least bad one if the * storage was full */ private Location addBadLocation(Location location) { mWeakLocations.add(location); if (mWeakLocations.size() < 3) { location = null; } else { Location best = mWeakLocations.lastElement(); for (Location whimp : mWeakLocations) { if (whimp.hasAccuracy() && best.hasAccuracy() && whimp.getAccuracy() < best.getAccuracy()) { best = whimp; } else { if (whimp.hasAccuracy() && !best.hasAccuracy()) { best = whimp; } } } synchronized (mWeakLocations) { mWeakLocations.clear(); } location = best; } return location; } /** * Builds a bit of knowledge about altitudes to expect and return if the * added value is deemed sane. * * @param altitude * @return whether the altitude is considered sane */ private boolean addSaneAltitude(double altitude) { boolean sane = true; double avg = 0; int elements = 0; // Even insane altitude shifts increases alter perception mAltitudes.add(altitude); if (mAltitudes.size() > 3) { mAltitudes.poll(); } for (Double alt : mAltitudes) { avg += alt; elements++; } avg = avg / elements; sane = Math.abs(altitude - avg) < MAX_REASONABLE_ALTITUDECHANGE; return sane; } /** * Trigged by events that start a new track */ private void startNewTrack() { mDistance = 0; Uri newTrack = this.getContentResolver().insert(Tracks.CONTENT_URI, new ContentValues(0)); mTrackId = Long.valueOf(newTrack.getLastPathSegment()).longValue(); startNewSegment(); } /** * Trigged by events that start a new segment */ private void startNewSegment() { this.mPreviousLocation = null; Uri newSegment = this.getContentResolver().insert(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments"), new ContentValues(0)); mSegmentId = Long.valueOf(newSegment.getLastPathSegment()).longValue(); crashProtectState(); } protected void storeMediaUri(Uri mediaUri) { if (isMediaPrepared()) { Uri mediaInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mSegmentId + "/waypoints/" + mWaypointId + "/media"); ContentValues args = new ContentValues(); args.put(Media.URI, mediaUri.toString()); this.getContentResolver().insert(mediaInsertUri, args); } else { Log.e(TAG, "No logging done under which to store the track"); } } /** * Use the ContentResolver mechanism to store a received location * * @param location */ public void storeLocation(Location location) { if (!isLogging()) { Log.e(TAG, String.format("Not logging but storing location %s, prepare to fail", location.toString())); } ContentValues args = new ContentValues(); args.put(Waypoints.LATITUDE, Double.valueOf(location.getLatitude())); args.put(Waypoints.LONGITUDE, Double.valueOf(location.getLongitude())); args.put(Waypoints.SPEED, Float.valueOf(location.getSpeed())); args.put(Waypoints.TIME, Long.valueOf(System.currentTimeMillis())); if (location.hasAccuracy()) { args.put(Waypoints.ACCURACY, Float.valueOf(location.getAccuracy())); } if (location.hasAltitude()) { args.put(Waypoints.ALTITUDE, Double.valueOf(location.getAltitude())); } if (location.hasBearing()) { args.put(Waypoints.BEARING, Float.valueOf(location.getBearing())); } Uri waypointInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mSegmentId + "/waypoints"); Uri inserted = this.getContentResolver().insert(waypointInsertUri, args); mWaypointId = Long.parseLong(inserted.getLastPathSegment()); } /** * Consult broadcast options and execute broadcast if necessary * * @param location */ public void broadcastLocation(Location location) { Intent intent = new Intent(Constants.STREAMBROADCAST); if (mStreamBroadcast) { final long minDistance = (long) PreferenceManager.getDefaultSharedPreferences(this).getFloat("streambroadcast_distance_meter", 5000F); final long minTime = 60000 * Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this).getString("streambroadcast_time", "1")); final long nowTime = location.getTime(); if (mPreviousLocation != null) { mBroadcastDistance += location.distanceTo(mPreviousLocation); } if (mLastTimeBroadcast == 0) { mLastTimeBroadcast = nowTime; } long passedTime = (nowTime - mLastTimeBroadcast); intent.putExtra(Constants.EXTRA_DISTANCE, (int) mBroadcastDistance); intent.putExtra(Constants.EXTRA_TIME, (int) passedTime/60000); intent.putExtra(Constants.EXTRA_LOCATION, location); intent.putExtra(Constants.EXTRA_TRACK, ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); boolean distanceBroadcast = minDistance > 0 && mBroadcastDistance >= minDistance; boolean timeBroadcast = minTime > 0 && passedTime >= minTime; if (distanceBroadcast || timeBroadcast) { if (distanceBroadcast) { mBroadcastDistance = 0; } if (timeBroadcast) { mLastTimeBroadcast = nowTime; } this.sendBroadcast(intent, "android.permission.ACCESS_FINE_LOCATION"); } } } private boolean isNetworkConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connMgr.getActiveNetworkInfo(); return (info != null && info.isConnected()); } private void soundGpsSignalAlarm() { Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alert == null) { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if (alert == null) { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); } } MediaPlayer mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(GPSLoggerService.this, alert); final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.setLooping(false); mMediaPlayer.prepare(); mMediaPlayer.start(); } } catch (IllegalArgumentException e) { Log.e(TAG, "Problem setting data source for mediaplayer", e); } catch (SecurityException e) { Log.e(TAG, "Problem setting data source for mediaplayer", e); } catch (IllegalStateException e) { Log.e(TAG, "Problem with mediaplayer", e); } catch (IOException e) { Log.e(TAG, "Problem with mediaplayer", e); } Message msg = Message.obtain(); msg.what = GPSPROBLEM; mHandler.sendMessage(msg); } @SuppressWarnings("rawtypes") private void startForegroundReflected(int id, Notification notification) { Method mStartForeground; Class[] mStartForegroundSignature = new Class[] { int.class, Notification.class }; Object[] mStartForegroundArgs = new Object[2]; mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStartForeground.invoke(this, mStartForegroundArgs); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } } @SuppressWarnings("rawtypes") private void stopForegroundReflected(boolean b) { Class[] mStopForegroundSignature = new Class[] { boolean.class }; Method mStopForeground; Object[] mStopForegroundArgs = new Object[1]; mStopForegroundArgs[0] = Boolean.TRUE; try { mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); mStopForeground.invoke(this, mStopForegroundArgs); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/logger/GPSLoggerService.java
Java
gpl3
53,293
package nl.sogeti.android.gpstracker.logger; import android.net.Uri; import android.location.Location; interface IGPSLoggerServiceRemote { int loggingState(); long startLogging(); void pauseLogging(); long resumeLogging(); void stopLogging(); Uri storeMediaUri(in Uri mediaUri); boolean isMediaPrepared(); void storeDerivedDataSource(in String sourceName); Location getLastWaypoint(); float getTrackedDistance(); }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/logger/IGPSLoggerServiceRemote.aidl
AIDL
gpl3
465
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.logger; import nl.sogeti.android.gpstracker.util.Constants; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.location.Location; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * Class to interact with the service that tracks and logs the locations * * @version $Id$ * @author rene (c) Jan 18, 2009, Sogeti B.V. */ public class GPSLoggerServiceManager { private static final String TAG = "OGT.GPSLoggerServiceManager"; private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION"; private IGPSLoggerServiceRemote mGPSLoggerRemote; public final Object mStartLock = new Object(); private boolean mBound = false; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mServiceConnection; private Runnable mOnServiceConnected; public GPSLoggerServiceManager(Context ctx) { ctx.startService(new Intent(Constants.SERVICENAME)); } public Location getLastWaypoint() { synchronized (mStartLock) { Location lastWaypoint = null; try { if( mBound ) { lastWaypoint = this.mGPSLoggerRemote.getLastWaypoint(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could get lastWaypoint GPSLoggerService.", e ); } return lastWaypoint; } } public float getTrackedDistance() { synchronized (mStartLock) { float distance = 0F; try { if( mBound ) { distance = this.mGPSLoggerRemote.getTrackedDistance(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could get tracked distance from GPSLoggerService.", e ); } return distance; } } public int getLoggingState() { synchronized (mStartLock) { int logging = Constants.UNKNOWN; try { if( mBound ) { logging = this.mGPSLoggerRemote.loggingState(); // Log.d( TAG, "mGPSLoggerRemote tells state to be "+logging ); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could stat GPSLoggerService.", e ); } return logging; } } public boolean isMediaPrepared() { synchronized (mStartLock) { boolean prepared = false; try { if( mBound ) { prepared = this.mGPSLoggerRemote.isMediaPrepared(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could stat GPSLoggerService.", e ); } return prepared; } } public long startGPSLogging( String name ) { synchronized (mStartLock) { if( mBound ) { try { return this.mGPSLoggerRemote.startLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } return -1; } } public void pauseGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.pauseLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } } } public long resumeGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { return this.mGPSLoggerRemote.resumeLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } return -1; } } public void stopGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.stopLogging(); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } public void storeDerivedDataSource( String datasource ) { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.storeDerivedDataSource( datasource ); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send datasource to GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } public void storeMediaUri( Uri mediaUri ) { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.storeMediaUri( mediaUri ); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding * * @param onServiceConnected Run on main thread after the service is bound */ public void startup( Context context, final Runnable onServiceConnected ) { // Log.d( TAG, "connectToGPSLoggerService()" ); synchronized (mStartLock) { if( !mBound ) { mOnServiceConnected = onServiceConnected; mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected( ComponentName className, IBinder service ) { synchronized (mStartLock) { // Log.d( TAG, "onServiceConnected() "+ Thread.currentThread().getId() ); GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface( service ); mBound = true; } if( mOnServiceConnected != null ) { mOnServiceConnected.run(); mOnServiceConnected = null; } } @Override public void onServiceDisconnected( ComponentName className ) { synchronized (mStartLock) { // Log.d( TAG, "onServiceDisconnected()"+ Thread.currentThread().getId() ); mBound = false; } } }; context.bindService( new Intent( Constants.SERVICENAME ), this.mServiceConnection, Context.BIND_AUTO_CREATE ); } else { Log.w( TAG, "Attempting to connect whilst already connected" ); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void shutdown(Context context) { // Log.d( TAG, "disconnectFromGPSLoggerService()" ); synchronized (mStartLock) { try { if( mBound ) { // Log.d( TAG, "unbindService()"+this.mServiceConnection ); context.unbindService( this.mServiceConnection ); GPSLoggerServiceManager.this.mGPSLoggerRemote = null; mServiceConnection = null; mBound = false; } } catch (IllegalArgumentException e) { Log.w( TAG, "Failed to unbind a service, prehaps the service disapearded?", e ); } } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/logger/GPSLoggerServiceManager.java
Java
gpl3
10,546
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import nl.sogeti.android.gpstracker.util.Constants; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class StreamUtils { @SuppressWarnings("unused") private static final String TAG = "OGT.StreamUtils"; /** * Initialize all appropriate stream listeners * @param ctx */ public static void initStreams(final Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); boolean streams_enabled = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); if (streams_enabled && sharedPreferences.getBoolean("VOICEOVER_ENABLED", false)) { VoiceOver.initStreaming(ctx); } if (streams_enabled && sharedPreferences.getBoolean("CUSTOMUPLOAD_ENABLED", false)) { CustomUpload.initStreaming(ctx); } } /** * Shutdown all stream listeners * * @param ctx */ public static void shutdownStreams(Context ctx) { VoiceOver.shutdownStreaming(ctx); CustomUpload.shutdownStreaming(ctx); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/streaming/StreamUtils.java
Java
gpl3
2,708
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.speech.tts.TextToSpeech; import android.util.Log; public class VoiceOver extends BroadcastReceiver implements TextToSpeech.OnInitListener { private static VoiceOver sVoiceOver = null; private static final String TAG = "OGT.VoiceOver"; public static synchronized void initStreaming(Context ctx) { if( sVoiceOver != null ) { shutdownStreaming(ctx); } sVoiceOver = new VoiceOver(ctx); IntentFilter filter = new IntentFilter(Constants.STREAMBROADCAST); ctx.registerReceiver(sVoiceOver, filter); } public static synchronized void shutdownStreaming(Context ctx) { if( sVoiceOver != null ) { ctx.unregisterReceiver(sVoiceOver); sVoiceOver.onShutdown(); sVoiceOver = null; } } private TextToSpeech mTextToSpeech; private int mVoiceStatus = -1; private Context mContext; public VoiceOver(Context ctx) { mContext = ctx.getApplicationContext(); mTextToSpeech = new TextToSpeech(mContext, this); } @Override public void onInit(int status) { mVoiceStatus = status; } private void onShutdown() { mVoiceStatus = -1; mTextToSpeech.shutdown(); } @Override public void onReceive(Context context, Intent intent) { if( mVoiceStatus == TextToSpeech.SUCCESS ) { int meters = intent.getIntExtra(Constants.EXTRA_DISTANCE, 0); int minutes = intent.getIntExtra(Constants.EXTRA_TIME, 0); String myText = context.getString(R.string.voiceover_speaking, minutes, meters); mTextToSpeech.speak(myText, TextToSpeech.QUEUE_ADD, null); } else { Log.w(TAG, "Voice stream failed TTS not ready"); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/streaming/VoiceOver.java
Java
gpl3
3,582
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.Queue; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.ApplicationPreferenceActivity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.client.ClientProtocolException; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Location; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; public class CustomUpload extends BroadcastReceiver { private static final String CUSTOMUPLOAD_BACKLOG_DEFAULT = "20"; private static CustomUpload sCustomUpload = null; private static final String TAG = "OGT.CustomUpload"; private static final int NOTIFICATION_ID = R.string.customupload_failed; private static Queue<HttpGet> sRequestBacklog = new LinkedList<HttpGet>(); public static synchronized void initStreaming(Context ctx) { if( sCustomUpload != null ) { shutdownStreaming(ctx); } sCustomUpload = new CustomUpload(); sRequestBacklog = new LinkedList<HttpGet>(); IntentFilter filter = new IntentFilter(Constants.STREAMBROADCAST); ctx.registerReceiver(sCustomUpload, filter); } public static synchronized void shutdownStreaming(Context ctx) { if( sCustomUpload != null ) { ctx.unregisterReceiver(sCustomUpload); sCustomUpload.onShutdown(); sCustomUpload = null; } } private void onShutdown() { } @Override public void onReceive(Context context, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefUrl = preferences.getString(ApplicationPreferenceActivity.CUSTOMUPLOAD_URL, "http://www.example.com"); Integer prefBacklog = Integer.valueOf( preferences.getString(ApplicationPreferenceActivity.CUSTOMUPLOAD_BACKLOG, CUSTOMUPLOAD_BACKLOG_DEFAULT) ); Location loc = intent.getParcelableExtra(Constants.EXTRA_LOCATION); Uri trackUri = intent.getParcelableExtra(Constants.EXTRA_TRACK); String buildUrl = prefUrl; buildUrl = buildUrl.replace("@LAT@", Double.toString(loc.getLatitude())); buildUrl = buildUrl.replace("@LON@", Double.toString(loc.getLongitude())); buildUrl = buildUrl.replace("@ID@", trackUri.getLastPathSegment()); buildUrl = buildUrl.replace("@TIME@", Long.toString(loc.getTime())); buildUrl = buildUrl.replace("@SPEED@", Float.toString(loc.getSpeed())); buildUrl = buildUrl.replace("@ACC@", Float.toString(loc.getAccuracy())); buildUrl = buildUrl.replace("@ALT@", Double.toString(loc.getAltitude())); buildUrl = buildUrl.replace("@BEAR@", Float.toString(loc.getBearing())); HttpClient client = new DefaultHttpClient(); URI uploadUri; try { uploadUri = new URI(buildUrl); HttpGet currentRequest = new HttpGet(uploadUri ); sRequestBacklog.add(currentRequest); if( sRequestBacklog.size() > prefBacklog ) { sRequestBacklog.poll(); } while( !sRequestBacklog.isEmpty() ) { HttpGet request = sRequestBacklog.peek(); HttpResponse response = client.execute(request); sRequestBacklog.poll(); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } clearNotification(context); } } catch (URISyntaxException e) { notifyError(context, e); } catch (ClientProtocolException e) { notifyError(context, e); } catch (IOException e) { notifyError(context, e); } } private void notifyError(Context context, Exception e) { Log.e( TAG, "Custom upload failed", e); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = context.getText(R.string.customupload_failed); long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context appContext = context.getApplicationContext(); CharSequence contentTitle = tickerText; CharSequence contentText = e.getMessage(); Intent notificationIntent = new Intent(context, CustomUpload.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(appContext, contentTitle, contentText, contentIntent); notification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, notification); } private void clearNotification(Context context) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); mNotificationManager.cancel(NOTIFICATION_ID); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/streaming/CustomUpload.java
Java
gpl3
7,377
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.util.Log; /** * Model containing agregrated data retrieved from the GoBreadcrumbs.com API * * @version $Id:$ * @author rene (c) May 9, 2011, Sogeti B.V. */ public class BreadcrumbsTracks extends Observable { public static final String DESCRIPTION = "DESCRIPTION"; public static final String NAME = "NAME"; public static final String ENDTIME = "ENDTIME"; public static final String TRACK_ID = "BREADCRUMBS_TRACK_ID"; public static final String BUNDLE_ID = "BREADCRUMBS_BUNDLE_ID"; public static final String ACTIVITY_ID = "BREADCRUMBS_ACTIVITY_ID"; public static final String DIFFICULTY = "DIFFICULTY"; public static final String STARTTIME = "STARTTIME"; public static final String ISPUBLIC = "ISPUBLIC"; public static final String RATING = "RATING"; public static final String LATITUDE = "LATITUDE"; public static final String LONGITUDE = "LONGITUDE"; public static final String TOTALDISTANCE = "TOTALDISTANCE"; public static final String TOTALTIME = "TOTALTIME"; private static final String TAG = "OGT.BreadcrumbsTracks"; private static final Integer CACHE_VERSION = Integer.valueOf(3); private static final String BREADCRUMSB_BUNDLES_CACHE_FILE = "breadcrumbs_bundles_cache.data"; private static final String BREADCRUMSB_ACTIVITY_CACHE_FILE = "breadcrumbs_activity_cache.data"; /** * Time in milliseconds that a persisted breadcrumbs cache is used without a refresh */ private static final long CACHE_TIMEOUT = 1000 * 60;//1000*60*10 ; /** * Mapping from bundleId to a list of trackIds */ private static Map<Integer, List<Integer>> sBundlesWithTracks; /** * Map from activityId to a dictionary containing keys like NAME */ private static Map<Integer, Map<String, String>> sActivityMappings; /** * Map from bundleId to a dictionary containing keys like NAME and DESCRIPTION */ private static Map<Integer, Map<String, String>> sBundleMappings; /** * Map from trackId to a dictionary containing keys like NAME, ISPUBLIC, DESCRIPTION and more */ private static Map<Integer, Map<String, String>> sTrackMappings; /** * Cache of OGT Tracks that have a Breadcrumbs track id stored in the meta-data table */ private Map<Long, Integer> mSyncedTracks = null; private static Set<Pair<Integer, Integer>> sScheduledTracksLoading; static { BreadcrumbsTracks.initCacheVariables(); } private static void initCacheVariables() { sBundlesWithTracks = new LinkedHashMap<Integer, List<Integer>>(); sActivityMappings = new HashMap<Integer, Map<String, String>>(); sBundleMappings = new HashMap<Integer, Map<String, String>>(); sTrackMappings = new HashMap<Integer, Map<String, String>>(); sScheduledTracksLoading = new HashSet<Pair<Integer, Integer>>(); } private ContentResolver mResolver; /** * Constructor: create a new BreadcrumbsTracks. * * @param resolver Content resolver to obtain local Breadcrumbs references */ public BreadcrumbsTracks(ContentResolver resolver) { mResolver = resolver; } public void addActivity(Integer activityId, String activityName) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addActivity(Integer " + activityId + " String " + activityName + ")"); } if (!sActivityMappings.containsKey(activityId)) { sActivityMappings.put(activityId, new HashMap<String, String>()); } sActivityMappings.get(activityId).put(NAME, activityName); setChanged(); notifyObservers(); } /** * Add bundle to the track list * * @param activityId * @param bundleId * @param bundleName * @param bundleDescription */ public void addBundle(Integer bundleId, String bundleName, String bundleDescription) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addBundle(Integer " + bundleId + ", String " + bundleName + ", String " + bundleDescription + ")"); } if (!sBundleMappings.containsKey(bundleId)) { sBundleMappings.put(bundleId, new HashMap<String, String>()); } if (!sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } sBundleMappings.get(bundleId).put(NAME, bundleName); sBundleMappings.get(bundleId).put(DESCRIPTION, bundleDescription); setChanged(); notifyObservers(); } /** * Add track to tracklist * * @param trackId * @param trackName * @param bundleId * @param trackDescription * @param difficulty * @param startTime * @param endTime * @param isPublic * @param lat * @param lng * @param totalDistance * @param totalTime * @param trackRating */ public void addTrack(Integer trackId, String trackName, Integer bundleId, String trackDescription, String difficulty, String startTime, String endTime, String isPublic, Float lat, Float lng, Float totalDistance, Integer totalTime, String trackRating) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addTrack(Integer " + trackId + ", String " + trackName + ", Integer " + bundleId + "..."); } if (!sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } if (!sBundlesWithTracks.get(bundleId).contains(trackId)) { sBundlesWithTracks.get(bundleId).add(trackId); sScheduledTracksLoading.remove(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } if (!sTrackMappings.containsKey(trackId)) { sTrackMappings.put(trackId, new HashMap<String, String>()); } putForTrack(trackId, NAME, trackName); putForTrack(trackId, ISPUBLIC, isPublic); putForTrack(trackId, STARTTIME, startTime); putForTrack(trackId, ENDTIME, endTime); putForTrack(trackId, DESCRIPTION, trackDescription); putForTrack(trackId, DIFFICULTY, difficulty); putForTrack(trackId, RATING, trackRating); putForTrack(trackId, LATITUDE, lat); putForTrack(trackId, LONGITUDE, lng); putForTrack(trackId, TOTALDISTANCE, totalDistance); putForTrack(trackId, TOTALTIME, totalTime); notifyObservers(); } public void addSyncedTrack(Long trackId, Integer bcTrackId) { if (mSyncedTracks == null) { isLocalTrackOnline(-1l); } mSyncedTracks.put(trackId, bcTrackId); setChanged(); notifyObservers(); } public void addTracksLoadingScheduled(Pair<Integer, Integer> item) { sScheduledTracksLoading.add(item); setChanged(); notifyObservers(); } /** * Cleans old bundles based a set of all bundles * * @param mBundleIds */ public void setAllBundleIds(Set<Integer> mBundleIds) { for (Integer oldBundleId : getAllBundleIds()) { if (!mBundleIds.contains(oldBundleId)) { removeBundle(oldBundleId); } } } public void setAllTracksForBundleId(Integer mBundleId, Set<Integer> updatedbcTracksIdList) { List<Integer> trackIdList = sBundlesWithTracks.get(mBundleId); for (int location = 0; location < trackIdList.size(); location++) { Integer oldTrackId = trackIdList.get(location); if (!updatedbcTracksIdList.contains(oldTrackId)) { removeTrack(mBundleId, oldTrackId); } } setChanged(); notifyObservers(); } private void putForTrack(Integer trackId, String key, Object value) { if (value != null) { sTrackMappings.get(trackId).put(key, value.toString()); } setChanged(); notifyObservers(); } /** * Remove a bundle * * @param deletedId */ public void removeBundle(Integer deletedId) { sBundleMappings.remove(deletedId); sBundlesWithTracks.remove(deletedId); setChanged(); notifyObservers(); } /** * Remove a track * * @param deletedId */ public void removeTrack(Integer bundleId, Integer trackId) { sTrackMappings.remove(trackId); if (sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.get(bundleId).remove(trackId); } setChanged(); notifyObservers(); mResolver.delete(MetaData.CONTENT_URI, MetaData.TRACK + " = ? AND " + MetaData.KEY + " = ? ", new String[] { trackId.toString(), TRACK_ID }); if (mSyncedTracks != null && mSyncedTracks.containsKey(trackId)) { mSyncedTracks.remove(trackId); } } public int positions() { int size = 0; for (Integer bundleId : sBundlesWithTracks.keySet()) { // One row for the Bundle header size += 1; int bundleSize = sBundlesWithTracks.get(bundleId) != null ? sBundlesWithTracks.get(bundleId).size() : 0; // One row per track in each bundle size += bundleSize; } return size; } public Integer getBundleIdForTrackId(Integer trackId) { for (Integer bundlId : sBundlesWithTracks.keySet()) { List<Integer> trackIds = sBundlesWithTracks.get(bundlId); if (trackIds.contains(trackId)) { return bundlId; } } return null; } public Integer[] getAllActivityIds() { return sActivityMappings.keySet().toArray(new Integer[sActivityMappings.keySet().size()]); } /** * Get all bundles * * @return */ public Integer[] getAllBundleIds() { return sBundlesWithTracks.keySet().toArray(new Integer[sBundlesWithTracks.keySet().size()]); } /** * @param position list postition 0...n * @return a pair of a TYPE and an ID */ public List<Pair<Integer, Integer>> getAllItems() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer bundleId : sBundlesWithTracks.keySet()) { items.add(Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId)); for(Integer trackId : sBundlesWithTracks.get(bundleId)) { items.add(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } } return items; } public List<Pair<Integer, Integer>> getActivityList() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer activityId : sActivityMappings.keySet()) { Pair<Integer, Integer> pair = Pair.create(Constants.BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE, activityId); pair.overrideToString(getValueForItem(pair, NAME)); items.add(pair); } return items; } public List<Pair<Integer, Integer>> getBundleList() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer bundleId : sBundleMappings.keySet()) { Pair<Integer, Integer> pair = Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId); pair.overrideToString(getValueForItem(pair, NAME)); items.add(pair); } return items; } public String getValueForItem(Pair<Integer, Integer> item, String key) { String value = null; switch (item.first) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: value = sBundleMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: value = sTrackMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE: value = sActivityMappings.get(item.second).get(key); break; default: value = null; break; } return value; } private boolean isLocalTrackOnline(Long qtrackId) { if (mSyncedTracks == null) { mSyncedTracks = new HashMap<Long, Integer>(); Cursor cursor = null; try { cursor = mResolver.query(MetaData.CONTENT_URI, new String[] { MetaData.TRACK, MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { TRACK_ID }, null); if (cursor.moveToFirst()) { do { Long trackId = cursor.getLong(0); try { Integer bcTrackId = Integer.valueOf(cursor.getString(1)); mSyncedTracks.put(trackId, bcTrackId); } catch (NumberFormatException e) { Log.w(TAG, "Illigal value stored as track id", e); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } setChanged(); notifyObservers(); } boolean synced = mSyncedTracks.containsKey(qtrackId); return synced; } public boolean isLocalTrackSynced(Long qtrackId) { boolean uploaded = isLocalTrackOnline(qtrackId); boolean synced = sTrackMappings.containsKey(mSyncedTracks.get(qtrackId)); return uploaded && synced; } public boolean areTracksLoaded(Pair<Integer, Integer> item) { return sBundlesWithTracks.containsKey(item.second) && item.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE; } public boolean areTracksLoadingScheduled(Pair<Integer, Integer> item) { return sScheduledTracksLoading.contains(item); } /** * Read the static breadcrumbs data from private file * * @param ctx * @return is refresh is needed */ @SuppressWarnings("unchecked") public boolean readCache(Context ctx) { FileInputStream fis = null; ObjectInputStream ois = null; Date bundlesPersisted = null, activitiesPersisted = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fis = ctx.openFileInput(BREADCRUMSB_BUNDLES_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivitiesWithBundles, sBundlesWithTracks, sBundleMappings, sTrackMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { bundlesPersisted = (Date) cache[1]; Map<Integer, List<Integer>> bundles = (Map<Integer, List<Integer>>) cache[2]; Map<Integer, Map<String, String>> bundlemappings = (Map<Integer, Map<String, String>>) cache[3]; Map<Integer, Map<String, String>> trackmappings = (Map<Integer, Map<String, String>>) cache[4]; sBundlesWithTracks = bundles != null ? bundles : sBundlesWithTracks; sBundleMappings = bundlemappings != null ? bundlemappings : sBundleMappings; sTrackMappings = trackmappings != null ? trackmappings : sTrackMappings; } else { clearPersistentCache(ctx); } fis = ctx.openFileInput(BREADCRUMSB_ACTIVITY_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { activitiesPersisted = (Date) cache[1]; Map<Integer, Map<String, String>> activitymappings = (Map<Integer, Map<String, String>>) cache[2]; sActivityMappings = activitymappings != null ? activitymappings : sActivityMappings; } else { clearPersistentCache(ctx); } } catch (OptionalDataException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassNotFoundException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (IOException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassCastException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ArrayIndexOutOfBoundsException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after reading cache", e); } } if (ois != null) { try { ois.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after reading cache", e); } } } } setChanged(); notifyObservers(); boolean refreshNeeded = false; refreshNeeded = refreshNeeded || bundlesPersisted == null || activitiesPersisted == null; refreshNeeded = refreshNeeded || (activitiesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT * 10); refreshNeeded = refreshNeeded || (bundlesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT); return refreshNeeded; } public void persistCache(Context ctx) { FileOutputStream fos = null; ObjectOutputStream oos = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fos = ctx.openFileOutput(BREADCRUMSB_BUNDLES_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sBundlesWithTracks, sBundleMappings, sTrackMappings }; oos.writeObject(cache); fos = ctx.openFileOutput(BREADCRUMSB_ACTIVITY_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; oos.writeObject(cache); } catch (FileNotFoundException e) { Log.e(TAG, "Error in file stream during persist cache", e); } catch (IOException e) { Log.e(TAG, "Error in object stream during persist cache", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after writing cache", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after writing cache", e); } } } } } public void clearAllCache(Context ctx) { BreadcrumbsTracks.initCacheVariables(); setChanged(); clearPersistentCache(ctx); notifyObservers(); } public void clearPersistentCache(Context ctx) { Log.w(TAG, "Deleting old Breadcrumbs cache files"); synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { ctx.deleteFile(BREADCRUMSB_ACTIVITY_CACHE_FILE); ctx.deleteFile(BREADCRUMSB_BUNDLES_CACHE_FILE); } } @Override public String toString() { return "BreadcrumbsTracks [mActivityMappings=" + sActivityMappings + ", mBundleMappings=" + sBundleMappings + ", mTrackMappings=" + sTrackMappings + ", mActivities=" + sActivityMappings + ", mBundles=" + sBundlesWithTracks + "]"; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/BreadcrumbsTracks.java
Java
gpl3
22,876
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsBundlesTask extends BreadcrumbsTask { final String TAG = "OGT.GetBreadcrumbsBundlesTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Set<Integer> mBundleIds; private LinkedList<Object[]> mBundles; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param listener * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsBundlesTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer) { super(context, adapter, listener); mHttpclient = httpclient; mConsumer = consumer; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { HttpEntity responseEntity = null; mBundleIds = new HashSet<Integer>(); mBundles = new LinkedList<Object[]>(); try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String bundleName = null, bundleDescription = null; Integer bundleId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("bundle".equals(xpp.getName()) && bundleId != null) { mBundles.add( new Object[]{bundleId, bundleName, bundleDescription} ); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("description".equals(tagName)) { bundleDescription = xpp.getText(); } else if ("id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); mBundleIds.add(bundleId); } else if ("name".equals(tagName)) { bundleName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem while reading the XML data"); } catch (IllegalStateException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.w(TAG, "Failed closing inputstream"); } } } return null; } @Override protected void updateTracksData(BreadcrumbsTracks tracks) { tracks.setAllBundleIds( mBundleIds ); for( Object[] bundle : mBundles ) { Integer bundleId = (Integer) bundle[0]; String bundleName = (String) bundle[1]; String bundleDescription = (String) bundle[2]; tracks.addBundle(bundleId, bundleName, bundleDescription); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/GetBreadcrumbsBundlesTask.java
Java
gpl3
8,517
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsActivitiesTask extends BreadcrumbsTask { private LinkedList<Pair<Integer, String>> mActivities; final String TAG = "OGT.GetBreadcrumbsActivitiesTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpClient; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsActivitiesTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer) { super(context, adapter, listener); mHttpClient = httpclient; mConsumer = consumer; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { mActivities = new LinkedList<Pair<Integer,String>>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/activities.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String activityName = null; Integer activityId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("activity".equals(xpp.getName()) && activityId != null && activityName != null) { mActivities.add(new Pair<Integer, String>(activityId, activityName)); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("id".equals(tagName)) { activityId = Integer.parseInt(xpp.getText()); } else if ("name".equals(tagName)) { activityName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; } @Override protected void updateTracksData( BreadcrumbsTracks tracks ) { for( Pair<Integer, String> activity : mActivities ) { tracks.addActivity(activity.first, activity.second); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/GetBreadcrumbsActivitiesTask.java
Java
gpl3
7,926
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsTracksTask extends BreadcrumbsTask { final String TAG = "OGT.GetBreadcrumbsTracksTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Integer mBundleId; private LinkedList<Object[]> mTracks; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsTracksTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer, Integer bundleId) { super(context, adapter, listener); mHttpclient = httpclient; mConsumer = consumer; mBundleId = bundleId; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { mTracks = new LinkedList<Object[]>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles/"+mBundleId+"/tracks.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String trackName = null, description = null, difficulty = null, startTime = null, endTime = null, trackRating = null, isPublic = null; Integer trackId = null, bundleId = null, totalTime = null; Float lat = null, lng = null, totalDistance = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("track".equals(xpp.getName()) && trackId != null && bundleId != null) { mTracks.add(new Object[] { trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating }); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("bundle-id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); } else if ("description".equals(tagName)) { description = xpp.getText(); } else if ("difficulty".equals(tagName)) { difficulty = xpp.getText(); } else if ("start-time".equals(tagName)) { startTime = xpp.getText(); } else if ("end-time".equals(tagName)) { endTime = xpp.getText(); } else if ("id".equals(tagName)) { trackId = Integer.parseInt(xpp.getText()); } else if ("is-public".equals(tagName)) { isPublic = xpp.getText(); } else if ("lat".equals(tagName)) { lat = Float.parseFloat(xpp.getText()); } else if ("lng".equals(tagName)) { lng = Float.parseFloat(xpp.getText()); } else if ("name".equals(tagName)) { trackName = xpp.getText(); } else if ("track-rating".equals(tagName)) { trackRating = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; } @Override protected void updateTracksData(BreadcrumbsTracks tracks) { Set<Integer> mTracksIds = new HashSet<Integer>() ; for (Object[] track : mTracks) { mTracksIds.add((Integer) track[0]); } tracks.setAllTracksForBundleId( mBundleId, mTracksIds ); for (Object[] track : mTracks) { Integer trackId = (Integer) track[0]; String trackName = (String) track[1]; Integer bundleId = (Integer) track[2]; String description = (String) track[3]; String difficulty = (String) track[4]; String startTime = (String) track[5]; String endTime = (String) track[6]; String isPublic = (String) track[7]; Float lat = (Float) track[8]; Float lng = (Float) track[9]; Float totalDistance = (Float) track[10]; Integer totalTime = (Integer) track[11]; String trackRating = (String) track[12]; tracks.addTrack(trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/GetBreadcrumbsTracksTask.java
Java
gpl3
10,413
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Oct 20, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.scheme.PlainSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) Oct 20, 2012, Sogeti B.V. */ public class BreadcrumbsService extends Service implements Observer, ProgressListener { public static final String OAUTH_TOKEN = "breadcrumbs_oauth_token"; public static final String OAUTH_TOKEN_SECRET = "breadcrumbs_oauth_secret"; private static final String TAG = "OGT.BreadcrumbsService"; public static final String NOTIFY_DATA_SET_CHANGED = "nl.sogeti.android.gpstracker.intent.action.NOTIFY_DATA_SET_CHANGED"; public static final String NOTIFY_PROGRESS_CHANGED = "nl.sogeti.android.gpstracker.intent.action.NOTIFY_PROGRESS_CHANGED"; public static final String PROGRESS_INDETERMINATE = null; public static final String PROGRESS = null; public static final String PROGRESS_STATE = null; public static final String PROGRESS_RESULT = null; public static final String PROGRESS_TASK = null; public static final String PROGRESS_MESSAGE = null; public static final int PROGRESS_STARTED = 1; public static final int PROGRESS_FINISHED = 2; public static final int PROGRESS_ERROR = 3; private final IBinder mBinder = new LocalBinder(); private BreadcrumbsTracks mTracks; private DefaultHttpClient mHttpClient; private OnSharedPreferenceChangeListener tokenChangedListener; private boolean mFinishing; boolean mAuthorized; ExecutorService mExecutor; @Override public void onCreate() { super.onCreate(); mExecutor = Executors.newFixedThreadPool(1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry); mHttpClient = new DefaultHttpClient(cm); mTracks = new BreadcrumbsTracks(this.getContentResolver()); mTracks.addObserver(this); connectionSetup(); } @Override public void onDestroy() { if (tokenChangedListener != null) { PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(tokenChangedListener); } mAuthorized = false; mFinishing = true; new AsyncTask<Void, Void, Void>() { public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } @Override protected Void doInBackground(Void... params) { mHttpClient.getConnectionManager().shutdown(); mExecutor.shutdown(); mHttpClient = null; return null; } }.executeOn(mExecutor); mTracks.persistCache(this); super.onDestroy(); } /** * Class used for the client Binder. Because we know this service always runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public BreadcrumbsService getService() { return BreadcrumbsService.this; } } /** * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return mBinder; } private boolean connectionSetup() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); mAuthorized = !"".equals(token) && !"".equals(secret); if (mAuthorized) { CommonsHttpOAuthConsumer consumer = getOAuthConsumer(); if (mTracks.readCache(this)) { new GetBreadcrumbsActivitiesTask(this, this, this, mHttpClient, consumer).executeOn(mExecutor); new GetBreadcrumbsBundlesTask(this, this, this, mHttpClient, consumer).executeOn(mExecutor); } } return mAuthorized; } public CommonsHttpOAuthConsumer getOAuthConsumer() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.getString(R.string.CONSUMER_KEY), this.getString(R.string.CONSUMER_SECRET)); consumer.setTokenWithSecret(token, secret); return consumer; } public void removeAuthentication() { Log.w(TAG, "Removing Breadcrumbs OAuth tokens"); Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit(); e.remove(OAUTH_TOKEN); e.remove(OAUTH_TOKEN_SECRET); e.commit(); } /** * Use a locally stored token or start the request activity to collect one */ public void collectBreadcrumbsOauthToken() { if (!connectionSetup()) { tokenChangedListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (OAUTH_TOKEN.equals(key)) { PreferenceManager.getDefaultSharedPreferences(BreadcrumbsService.this).unregisterOnSharedPreferenceChangeListener(tokenChangedListener); connectionSetup(); } } }; PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(tokenChangedListener); Intent i = new Intent(this.getApplicationContext(), PrepareRequestTokenActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN); i.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET); i.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, this.getString(R.string.CONSUMER_KEY)); i.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, this.getString(R.string.CONSUMER_SECRET)); i.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.REQUEST_URL); i.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.ACCESS_URL); i.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.AUTHORIZE_URL); this.startActivity(i); } } public void startDownloadTask(Context context, ProgressListener listener, Pair<Integer, Integer> track) { new DownloadBreadcrumbsTrackTask(context, listener, this, mHttpClient, getOAuthConsumer(), track).executeOn(mExecutor); } public void startUploadTask(Context context, ProgressListener listener, Uri trackUri, String name) { new UploadBreadcrumbsTrackTask(context, this, listener, mHttpClient, getOAuthConsumer(), trackUri, name).executeOn(mExecutor); } public boolean isAuthorized() { return mAuthorized; } public void willDisplayItem(Pair<Integer, Integer> item) { if (item.first == Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE) { if (!mFinishing && !mTracks.areTracksLoaded(item) && !mTracks.areTracksLoadingScheduled(item)) { new GetBreadcrumbsTracksTask(this, this, this, mHttpClient, getOAuthConsumer(), item.second).executeOn(mExecutor); mTracks.addTracksLoadingScheduled(item); } } } public List<Pair<Integer, Integer>> getAllItems() { List<Pair<Integer, Integer>> items = mTracks.getAllItems(); return items; } public List<Pair<Integer, Integer>> getActivityList() { List<Pair<Integer, Integer>> activities = mTracks.getActivityList(); return activities; } public List<Pair<Integer, Integer>> getBundleList() { List<Pair<Integer, Integer>> bundles = mTracks.getBundleList(); return bundles; } public String getValueForItem(Pair<Integer, Integer> item, String name) { return mTracks.getValueForItem(item, name); } public void clearAllCache() { mTracks.clearAllCache(this); } protected BreadcrumbsTracks getBreadcrumbsTracks() { return mTracks; } public boolean isLocalTrackSynced(long trackId) { return mTracks.isLocalTrackSynced(trackId); } /**** * Observer interface */ @Override public void update(Observable observable, Object data) { Intent broadcast = new Intent(); broadcast.setAction(BreadcrumbsService.NOTIFY_DATA_SET_CHANGED); getApplicationContext().sendBroadcast(broadcast); } /**** * ProgressListener interface */ @Override public void setIndeterminate(boolean indeterminate) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_INDETERMINATE, indeterminate); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void started() { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_STARTED); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void setProgress(int value) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS, value); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void finished(Uri result) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_FINISHED); broadcast.putExtra(BreadcrumbsService.PROGRESS_RESULT, result); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void showError(String task, String errorMessage, Exception exception) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_ERROR); broadcast.putExtra(BreadcrumbsService.PROGRESS_TASK, task); broadcast.putExtra(BreadcrumbsService.PROGRESS_MESSAGE, errorMessage); broadcast.putExtra(BreadcrumbsService.PROGRESS_RESULT, exception); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/BreadcrumbsService.java
Java
gpl3
12,931
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.HttpMultipartMode; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.util.EntityUtils; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class UploadBreadcrumbsTrackTask extends GpxCreator { final String TAG = "OGT.UploadBreadcrumbsTrackTask"; private BreadcrumbsService mService; private OAuthConsumer mConsumer; private HttpClient mHttpClient; private String mActivityId; private String mBundleId; private String mDescription; private String mIsPublic; private String mBundleName; private String mBundleDescription; private boolean mIsBundleCreated; private List<File> mPhotoUploadQueue; /** * Constructor: create a new UploadBreadcrumbsTrackTask. * * @param context * @param adapter * @param listener * @param httpclient * @param consumer * @param trackUri * @param name */ public UploadBreadcrumbsTrackTask(Context context, BreadcrumbsService adapter, ProgressListener listener, HttpClient httpclient, OAuthConsumer consumer, Uri trackUri, String name) { super(context, trackUri, name, true, listener); mService = adapter; mHttpClient = httpclient; mConsumer = consumer; mPhotoUploadQueue = new LinkedList<File>(); } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Uri doInBackground(Void... params) { // Leave room in the progressbar for uploading determineProgressGoal(); mProgressAdmin.setUpload(true); // Build GPX file Uri gpxFile = exportGpx(); if (isCancelled()) { String text = mContext.getString(R.string.ticker_failed) + " \"http://api.gobreadcrumbs.com/v1/tracks\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Fail to execute request due to canceling"), text); } // Collect GPX Import option params mActivityId = null; mBundleId = null; mDescription = null; mIsPublic = null; Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Cursor cursor = null; try { cursor = mContext.getContentResolver().query(metadataUri, new String[] { MetaData.KEY, MetaData.VALUE }, null, null, null); if (cursor.moveToFirst()) { do { String key = cursor.getString(0); if (BreadcrumbsTracks.ACTIVITY_ID.equals(key)) { mActivityId = cursor.getString(1); } else if (BreadcrumbsTracks.BUNDLE_ID.equals(key)) { mBundleId = cursor.getString(1); } else if (BreadcrumbsTracks.DESCRIPTION.equals(key)) { mDescription = cursor.getString(1); } else if (BreadcrumbsTracks.ISPUBLIC.equals(key)) { mIsPublic = cursor.getString(1); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } if ("-1".equals(mActivityId)) { String text = "Unable to upload without a activity id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } int statusCode = 0; String responseText = null; Uri trackUri = null; HttpEntity responseEntity = null; try { if ("-1".equals(mBundleId)) { mBundleDescription = "";//mContext.getString(R.string.breadcrumbs_bundledescription); mBundleName = mContext.getString(R.string.app_name); mBundleId = createOpenGpsTrackerBundle(); } String gpxString = XmlCreator.convertStreamToString(mContext.getContentResolver().openInputStream(gpxFile)); HttpPost method = new HttpPost("http://api.gobreadcrumbs.com:80/v1/tracks"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("import_type", new StringBody("GPX")); //entity.addPart("gpx", new FileBody(gpxFile)); entity.addPart("gpx", new StringBody(gpxString)); entity.addPart("bundle_id", new StringBody(mBundleId)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mDescription)); // entity.addPart("difficulty", new StringBody("3")); // entity.addPart("rating", new StringBody("4")); entity.addPart("public", new StringBody(mIsPublic)); method.setEntity(entity); // Execute the POST to OpenStreetMap mConsumer.sign(method); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "HTTP Method "+method.getMethod() ); Log.d( TAG, "URI scheme "+method.getURI().getScheme() ); Log.d( TAG, "Host name "+method.getURI().getHost() ); Log.d( TAG, "Port "+method.getURI().getPort() ); Log.d( TAG, "Request path "+method.getURI().getPath()); Log.d( TAG, "Consumer Key: "+mConsumer.getConsumerKey()); Log.d( TAG, "Consumer Secret: "+mConsumer.getConsumerSecret()); Log.d( TAG, "Token: "+mConsumer.getToken()); Log.d( TAG, "Token Secret: "+mConsumer.getTokenSecret()); Log.d( TAG, "Execute request: "+method.getURI() ); for( Header header : method.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(method); mProgressAdmin.addUploadProgress(); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Upload Response: "+responseText); } Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); if (m.find()) { Integer trackId = Integer.valueOf(m.group(1)); trackUri = Uri.parse("http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"); for( File photo :mPhotoUploadQueue ) { uploadPhoto(photo, trackId); } } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode == 200 || statusCode == 201) { if (trackUri == null) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Unable to retrieve URI from response"), responseText); } } else { //mAdapter.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Status code: " + statusCode), responseText); } return trackUri; } private String createOpenGpsTrackerBundle() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { HttpPost method = new HttpPost("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(mBundleName)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mBundleDescription)); method.setEntity(entity); mConsumer.sign(method); HttpResponse response = mHttpClient.execute(method); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); String bundleId = null; if (m.find()) { bundleId = m.group(1); ContentValues values = new ContentValues(); values.put(MetaData.KEY, BreadcrumbsTracks.BUNDLE_ID); values.put(MetaData.VALUE, bundleId); Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); mContext.getContentResolver().insert(metadataUri, values); mIsBundleCreated = true; } else { String text = "Unable to upload (yet) without a bunld id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } return bundleId; } /** * Queue's media * * @param inputFilePath * @return file path relative to the export dir * @throws IOException */ @Override protected String includeMediaFile(String inputFilePath) throws IOException { File source = new File(inputFilePath); if (source.exists()) { mProgressAdmin.setPhotoUpload(source.length()); mPhotoUploadQueue.add(source); } return source.getName(); } private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(photo.getName())); entity.addPart("track_id", new StringBody(Integer.toString(trackId))); //entity.addPart("description", new StringBody("")); entity.addPart("file", new FileBody(photo)); request.setEntity(entity); mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); mProgressAdmin.addPhotoUploadProgress(photo.length()); Log.i( TAG, "Uploaded photo "+responseText); } @Override protected void onPostExecute(Uri result) { BreadcrumbsTracks tracks = mService.getBreadcrumbsTracks(); Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); List<String> segments = result.getPathSegments(); Integer bcTrackId = Integer.valueOf(segments.get(segments.size() - 2)); ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>(); metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId))); if (mDescription != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, mDescription)); } if (mIsPublic != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, mIsPublic)); } metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, mBundleId)); metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, mActivityId)); // Store in OGT provider ContentResolver resolver = mContext.getContentResolver(); resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1])); // Store in Breadcrumbs adapter tracks.addSyncedTrack(Long.valueOf(mTrackUri.getLastPathSegment()), bcTrackId); if( mIsBundleCreated ) { mService.getBreadcrumbsTracks().addBundle(Integer.parseInt(mBundleId), mBundleName, mBundleDescription); } //"http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx" mService.getBreadcrumbsTracks().addTrack(bcTrackId, mName, Integer.valueOf(mBundleId), mDescription, null, null, null, mIsPublic, null, null, null, null, null); super.onPostExecute(result); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/UploadBreadcrumbsTrackTask.java
Java
gpl3
17,596
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) May 29, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.util.concurrent.Executor; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.annotation.TargetApi; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public abstract class BreadcrumbsTask extends AsyncTask<Void, Void, Void> { private static final String TAG = "OGT.BreadcrumbsTask"; private ProgressListener mListener; private String mErrorText; private Exception mException; protected BreadcrumbsService mService; private String mTask; protected Context mContext; public BreadcrumbsTask(Context context, BreadcrumbsService adapter, ProgressListener listener) { mContext = context; mListener = listener; mService = adapter; } @TargetApi(11) public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } protected void handleError(String task, Exception e, String text) { Log.e(TAG, "Received error will cancel background task " + this.getClass().getName(), e); mService.removeAuthentication(); mTask = task; mException = e; mErrorText = text; cancel(true); } @Override protected void onPreExecute() { if (mListener != null) { mListener.setIndeterminate(true); mListener.started(); } } @Override protected void onPostExecute(Void result) { this.updateTracksData(mService.getBreadcrumbsTracks()); if (mListener != null) { mListener.finished(null); } } protected abstract void updateTracksData(BreadcrumbsTracks tracks); @Override protected void onCancelled() { if (mListener != null) { mListener.finished(null); } if (mListener != null && mErrorText != null && mException != null) { mListener.showError(mTask, mErrorText, mException); } else if (mException != null) { Log.e(TAG, "Incomplete error after cancellation:" + mErrorText, mException); } else { Log.e(TAG, "Incomplete error after cancellation:" + mErrorText); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/BreadcrumbsTask.java
Java
gpl3
3,932
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class DownloadBreadcrumbsTrackTask extends GpxParser { final String TAG = "OGT.GetBreadcrumbsTracksTask"; private BreadcrumbsService mAdapter; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Pair<Integer, Integer> mTrack; /** * * Constructor: create a new DownloadBreadcrumbsTrackTask. * @param context * @param progressListener * @param adapter * @param httpclient * @param consumer * @param track */ public DownloadBreadcrumbsTrackTask(Context context, ProgressListener progressListener, BreadcrumbsService adapter, DefaultHttpClient httpclient, OAuthConsumer consumer, Pair<Integer, Integer> track) { super(context, progressListener); mAdapter = adapter; mHttpclient = httpclient; mConsumer = consumer; mTrack = track; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Uri doInBackground(Uri... params) { determineProgressGoal(null); Uri trackUri = null; String trackName = mAdapter.getBreadcrumbsTracks().getValueForItem(mTrack, BreadcrumbsTracks.NAME); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/tracks/" + mTrack.second + "/placemarks.gpx"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } trackUri = importTrack(stream, trackName); } catch (OAuthMessageSignerException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthExpectationFailedException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthCommunicationException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e( TAG, "Failed to close the content stream", e); } } } return trackUri; } @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); long ogtTrackId = Long.parseLong(result.getLastPathSegment()); Uri metadataUri = Uri.withAppendedPath(ContentUris.withAppendedId(Tracks.CONTENT_URI, ogtTrackId), "metadata"); BreadcrumbsTracks tracks = mAdapter.getBreadcrumbsTracks(); Integer bcTrackId = mTrack.second; Integer bcBundleId = tracks.getBundleIdForTrackId(bcTrackId); //TODO Integer bcActivityId = tracks.getActivityIdForBundleId(bcBundleId); String bcDifficulty = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DIFFICULTY); String bcRating = tracks.getValueForItem(mTrack, BreadcrumbsTracks.RATING); String bcPublic = tracks.getValueForItem(mTrack, BreadcrumbsTracks.ISPUBLIC); String bcDescription = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DESCRIPTION); ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>(); if (bcTrackId != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId))); } if (bcDescription != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, bcDescription)); } if (bcDifficulty != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DIFFICULTY, bcDifficulty)); } if (bcRating != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.RATING, bcRating)); } if (bcPublic != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, bcPublic)); } if (bcBundleId != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, Integer.toString(bcBundleId))); } // if (bcActivityId != null) // { // metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, Integer.toString(bcActivityId))); // } ContentResolver resolver = mContext.getContentResolver(); resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1])); tracks.addSyncedTrack(ogtTrackId, mTrack.second); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/DownloadBreadcrumbsTrackTask.java
Java
gpl3
8,737
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask.Status; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.TextView; /** * Prepares a OAuthConsumer and OAuthProvider OAuthConsumer is configured with * the consumer key & consumer secret. Both key and secret are retrieved from * the extras in the Intent * * OAuthProvider is configured with the 3 * OAuth endpoints. These are retrieved from the extras in the Intent. * * Execute the OAuthRequestTokenTask to retrieve the request, * and authorize the request. After the request is authorized, a callback is * made here and this activity finishes to return to the last Activity on the * stack. */ public class PrepareRequestTokenActivity extends Activity { /** * Name of the Extra in the intent holding the consumer secret */ public static final String CONSUMER_SECRET = "CONSUMER_SECRET"; /** * Name of the Extra in the intent holding the consumer key */ public static final String CONSUMER_KEY = "CONSUMER_KEY"; /** * Name of the Extra in the intent holding the authorizationWebsiteUrl */ public static final String AUTHORIZE_URL = "AUTHORIZE_URL"; /** * Name of the Extra in the intent holding the accessTokenEndpointUrl */ public static final String ACCESS_URL = "ACCESS_URL"; /** * Name of the Extra in the intent holding the requestTokenEndpointUrl */ public static final String REQUEST_URL = "REQUEST_URL"; /** * String value of the key in the DefaultSharedPreferences * in which to store the permission token */ public static final String OAUTH_TOKEN_PREF = "OAUTH_TOKEN"; /** * String value of the key in the DefaultSharedPreferences * in which to store the permission secret */ public static final String OAUTH_TOKEN_SECRET_PREF = "OAUTH_TOKEN_SECRET"; final String TAG = "OGT.PrepareRequestTokenActivity"; private OAuthConsumer consumer; private OAuthProvider provider; private String mTokenKey; private String mSecretKey; private OAuthRequestTokenTask mTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.oauthentication); String key = getIntent().getStringExtra(CONSUMER_KEY); String secret = getIntent().getStringExtra(CONSUMER_SECRET); String requestUrl = getIntent().getStringExtra(REQUEST_URL); String accessUrl = getIntent().getStringExtra(ACCESS_URL); String authUrl = getIntent().getStringExtra(AUTHORIZE_URL); TextView tv = (TextView) findViewById(R.id.detail); tv.setText(requestUrl); mTokenKey = getIntent().getStringExtra(OAUTH_TOKEN_PREF); mSecretKey = getIntent().getStringExtra(OAUTH_TOKEN_SECRET_PREF); this.consumer = new CommonsHttpOAuthConsumer(key, secret); this.provider = new CommonsHttpOAuthProvider(requestUrl, accessUrl, authUrl); mTask = new OAuthRequestTokenTask(this, consumer, provider); mTask.execute(); } @Override protected void onResume() { super.onResume(); // Will not be called if onNewIntent() was called with callback scheme Status status = mTask.getStatus(); if( status != Status.RUNNING ) { finish(); } } /** * Called when the OAuthRequestTokenTask finishes (user has authorized the * request token). The callback URL will be intercepted here. */ @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final Uri uri = intent.getData(); if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) { Log.i(TAG, "Callback received : " + uri); Log.i(TAG, "Retrieving Access Token"); new RetrieveAccessTokenTask(this, consumer, provider, prefs, mTokenKey, mSecretKey).execute(uri); finish(); } } }
1053182527-johndoe-betterperformance-v8
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/oauth/PrepareRequestTokenActivity.java
Java
gpl3
6,091