code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.net;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import java.io.IOException;
/**
* Handles creating and parsing request for image somewhere on the web.
*/
public class ImageDownloadHelper extends HttpHelper {
public ImageDownloadHelper(int messageType, Object data, boolean showDialog, Activity activity,
HttpListener listener) {
super(messageType, data, showDialog, activity, listener);
start();
}
@Override
public int getDialogMessage() {
// No dialog message
return UNKNOWN_DIALOG_MESSAGE;
}
@Override
public HttpUriRequest createRequest() {
Uri url = Uri.parse((String) requestData);
return new HttpGet(url.toString());
}
@Override
public void parseResponse(HttpResponse response) {
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(response.getEntity()
.getContent());
success(bitmap);
} catch (IllegalStateException e) {
// Ignore
} catch (IOException e) {
// Ignore
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.net;
import com.google.android.common.gdata2.AndroidXmlParserFactory;
import com.google.wireless.gdata2.data.Entry;
import com.google.wireless.gdata2.parser.ParseException;
import com.google.wireless.gdata2.parser.xml.XmlGDataParser;
import android.net.Uri;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.quizpoll.R;
import org.quizpoll.data.Preferences;
import org.quizpoll.data.Preferences.PrefType;
import org.quizpoll.data.model.DocsEntry;
import org.quizpoll.ui.GoogleAuthActivity;
import org.quizpoll.util.Utils;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Creates and parses requests for Google Document List API.
*/
public class DocsHelper extends HttpHelper {
// URL to Google Document List API - private quizzes
private static final String PRIVATE_DOCLIST_URL =
"https://docs.google.com/feeds/default/private/full?title=%5BQ%5D";
// Message types
public static final int MY_DOCUMENTS = 0;
private GoogleAuthActivity authActivity;
public DocsHelper(int messageType, Object data, boolean showDialog,
GoogleAuthActivity authActivity,
HttpListener listener) {
super(messageType, data, showDialog, authActivity, listener);
this.authActivity = authActivity;
authActivity.authenticatedRequest(GoogleAuthActivity.AUTHSERVER_DOCS, this);
}
@Override
public int getDialogMessage() {
switch (messageType) {
case MY_DOCUMENTS:
return R.string.fetching_quiz_games;
}
return UNKNOWN_DIALOG_MESSAGE;
}
@Override
public HttpUriRequest createRequest() {
Uri url;
switch (messageType) {
case MY_DOCUMENTS:
// Own documents
url = Uri.parse(PRIVATE_DOCLIST_URL);
return addHeaders(new HttpGet(url.toString()), PrefType.AUTH_TOKEN_DOCS);
}
return null;
}
@Override
public void parseResponse(HttpResponse response) {
try {
switch (messageType) {
case MY_DOCUMENTS:
handleDocumentList(response);
break;
}
} catch (IOException e) {
error(ERROR_CONNECTION);
} catch (ParseException e) {
error(ERROR_CONNECTION);
} catch (IllegalStateException e) {
error(ERROR_CONNECTION);
} catch (XmlPullParserException e) {
error(ERROR_CONNECTION);
}
}
@Override
protected void error(int statusCode) {
super.error(statusCode);
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
// Authtoken expired, login again
authActivity.authenticatedRequest(GoogleAuthActivity.AUTHSERVER_DOCS, this, true);
}
}
/**
* Adds GData API headers to the request
*/
private HttpUriRequest addHeaders(HttpUriRequest request, PrefType type) {
request.addHeader("GData-Version", "3.0");
request.addHeader(
"Authorization",
"GoogleLogin auth="
+ Preferences.getString(type, authActivity));
request.addHeader("Content-Type", "application/atom+xml; charset=UTF-8");
return request;
}
/**
* Starts parsing XML-based data
*/
private XmlGDataParser getXmlParser(HttpResponse response) throws ParseException,
IllegalStateException, IOException, XmlPullParserException {
return new XmlGDataParser(response.getEntity().getContent(),
new AndroidXmlParserFactory().createParser());
}
/**
* Parses documents in some folder and filter folders and spreadsheets
*/
private void handleDocumentList(HttpResponse response) throws ParseException,
IllegalStateException, IOException, XmlPullParserException {
final XmlGDataParser parser = getXmlParser(response);
parser.parseFeedEnvelope();
List<DocsEntry> docsEntries = new ArrayList<DocsEntry>();
Entry entry = null;
while (parser.hasMoreData()) {
entry = parser.readNextEntry(entry);
int type;
if (entry.getCategory().endsWith("folder")) {
type = DocsEntry.COLLECTION;
} else if (entry.getCategory().endsWith("spreadsheet")) {
type = DocsEntry.QUIZ;
} else {
// Skip other types than folders and spreadsheets
continue;
}
String[] parts = Uri.parse(entry.getId()).getLastPathSegment().split(":");
if (parts.length < 2) {
throw new ParseException();
}
String id = parts[1];
String title = entry.getTitle();
if (!title.contains("[Q]")) {
continue; // Skip spreadsheets which do not have [Q] in title
}
docsEntries.add(new DocsEntry(type, Utils.formatQuizName(entry.getTitle()), id));
}
success(docsEntries);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.net;
import android.app.Activity;
import android.net.Uri;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.quizpoll.R;
import org.quizpoll.data.model.ShortenedUrl;
import java.io.UnsupportedEncodingException;
/**
* Creates and parses requests for URL Shortener service.
*/
public class UrlShortenerHelper extends HttpHelper {
// API key for URL Shortener service
private static final String URL_SHORTENER_API_KEY = "AIzaSyBWORrW1tLCNfe4_44eWqP_bxfugEHMasg";
// URL to Google URL Shortener API
private static final String URL_SHORTENER_URL = "https://www.googleapis.com/urlshortener/v1/url";
public UrlShortenerHelper(int messageType, Object data, boolean showDialog, Activity activity,
HttpListener listener) {
super(messageType, data, showDialog, activity, listener);
start();
}
@Override
public int getDialogMessage() {
return R.string.loading;
}
@Override
public HttpUriRequest createRequest() {
try {
Uri url = Uri.parse(URL_SHORTENER_URL).buildUpon()
.appendQueryParameter("key", URL_SHORTENER_API_KEY).build();
HttpUriRequest request = new HttpPost(url.toString());
String requestString = "{\"longUrl\": \"" + (String) requestData + "\"}";
((HttpPost) request).setEntity(new StringEntity(requestString));
request.setHeader("Content-Type", "application/json");
return request;
} catch (UnsupportedEncodingException e) {
return null;
}
}
@Override
public void parseResponse(HttpResponse response) {
String content = readContent(response);
ShortenedUrl shortenerResponse = getGson().fromJson(content, ShortenedUrl.class);
success(shortenerResponse.getId());
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.net;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpUriRequest;
import org.quizpoll.R;
import org.quizpoll.ui.AboutActivity;
import org.quizpoll.util.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Handles HTTP connections, connection progress and downloading data from the
* network. Also reacts to common HTTP-related errors. Create subclass of this
* helper for every server you are communicating with.
*/
public abstract class HttpHelper {
protected static final String TAG = "HttpHelper";
private static final String USER_AGENT = "Android/org.quizpoll/";
/**
* Should be returned when network connection error occurs.
*/
public static final int ERROR_CONNECTION = 0;
/**
* Should be used when subclass has just one message type
*/
public static final int SINGLE_MESSAGE_TYPE = -1;
/**
* Should be returned when no dialog message is defined;
*/
public static final int UNKNOWN_DIALOG_MESSAGE = -1;
protected final int messageType;
protected final Object requestData;
private final HttpListener listener;
protected final Activity activity;
private ProgressDialog progressDialog;
private final boolean showDialog;
private AndroidHttpClient httpClient;
public HttpHelper(int messageType, Object data, boolean showDialog, Activity context,
HttpListener listener) {
this.messageType = messageType;
this.requestData = data;
this.listener = listener;
this.activity = context;
this.showDialog = showDialog;
}
/**
* Starts the HTTP request-response
*/
public void start() {
if (showDialog) {
progressDialog = new ProgressDialog(activity);
progressDialog.setOwnerActivity(activity);
int message = getDialogMessage();
progressDialog.setMessage(activity.getString(message));
progressDialog.show();
}
new NetworkTask().execute();
}
/**
* Subclass should provide string resource for loading dialog
*/
public abstract int getDialogMessage();
/**
* Subclass should implement creation of requests
*/
public abstract HttpUriRequest createRequest();
/**
* Subclass should implement parsing of valid response
*/
public abstract void parseResponse(HttpResponse response);
/**
* Makes HTTP request with JSON data.
*/
private HttpResponse doRequest(HttpUriRequest request) {
try {
httpClient =
AndroidHttpClient.newInstance(USER_AGENT + Utils.getVersion(activity) + "/"
+ Utils.getVersionCode(activity));
Log.i(TAG, "Request: " + request.getURI());
HttpResponse response = httpClient.execute(request);
Log.i(TAG, "Response: " + response.getStatusLine().toString());
return response;
} catch (IOException e) {
return null;
}
}
/**
* Handles received data from network.
*/
private void handleResponse(HttpResponse response) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode <= HttpStatus.SC_MOVED_TEMPORARILY) {
parseResponse(response);
} else {
error(statusCode);
}
}
/**
* Reads content of HTTP response, is used in subclasses
*/
protected String readContent(HttpResponse response) {
try {
BufferedReader br =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String content = sb.toString();
if (content != null) {
Log.i(TAG, content);
}
br.close();
return content;
} catch (IOException e) {
error(ERROR_CONNECTION);
return null;
}
}
/**
* Creates new GSON parser instance, is used in subclasses
*/
protected Gson getGson() {
return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
}
/**
* HTTP request successful, send parsed object back to caller.
*/
protected void success(Object responseData) {
if (showDialog) {
progressDialog.hide();
progressDialog.dismiss();
}
listener.onSuccess(responseData);
httpClient.close();
}
/**
* Default handing of errors
*/
protected void error(int statusCode) {
// General errors
switch (statusCode) {
case ERROR_CONNECTION:
Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_SHORT).show();
break;
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
Toast.makeText(activity, R.string.server_error, Toast.LENGTH_SHORT).show();
break;
case HttpStatus.SC_NOT_FOUND:
Toast.makeText(activity, R.string.not_found_error, Toast.LENGTH_SHORT).show();
break;
case 426:
// Upgrade Required
showUpgradeRequiredDialog();
break;
}
if (showDialog) {
progressDialog.hide();
progressDialog.dismiss();
}
listener.onFailure(statusCode);
httpClient.close();
}
/**
* Shows dialog for forced update
*/
private void showUpgradeRequiredDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle(R.string.update_required);
alert.setMessage(R.string.update_required_description);
alert.setPositiveButton(R.string.go_to_market, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(AboutActivity.MARKET_LISTING));
activity.startActivity(intent);
}
});
Dialog dialog = alert.create();
dialog.setOwnerActivity(activity);
dialog.show();
}
/**
* Make network request on background
*/
private class NetworkTask extends AsyncTask<Void, Void, HttpResponse> {
@Override
protected HttpResponse doInBackground(Void... parameters) {
return doRequest(createRequest());
}
@Override
protected void onPostExecute(HttpResponse response) {
if (response == null) {
error(ERROR_CONNECTION);
} else {
handleResponse(response);
}
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.net;
import com.google.gson.reflect.TypeToken;
import android.net.Uri;
import android.net.Uri.Builder;
import android.text.TextUtils;
import android.widget.Toast;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.quizpoll.data.Preferences;
import org.quizpoll.data.Preferences.PrefType;
import org.quizpoll.data.model.Answer;
import org.quizpoll.data.model.DocsEntry;
import org.quizpoll.data.model.LeaderboardEntry;
import org.quizpoll.data.model.Poll;
import org.quizpoll.data.model.PollResponse;
import org.quizpoll.data.model.Question;
import org.quizpoll.data.model.Quiz;
import org.quizpoll.ui.GoogleAuthActivity;
import org.quizpoll.R;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* Creating and parsing of requests for the AppEngine backend.
*/
public class AppEngineHelper extends HttpHelper {
// URL to broker JSON API
public static final String BROKER_URL = "http://quiz-n-poll.appspot.com";
// Message types
public static final int LOGIN = -1;
public static final int COLLECTION_DOCUMENTS = 0;
public static final int QUIZ = 1;
public static final int QUIZ_LEADERBOARD = 2;
public static final int QUIZ_SUBMIT = 3;
public static final int POLL = 4;
public static final int POLL_STATUS = 5;
public static final int POLL_SUBMIT = 6;
protected GoogleAuthActivity authActivity;
public AppEngineHelper(int messageType, Object data, boolean showDialog,
GoogleAuthActivity authActivity, HttpListener listener) {
super(messageType, data, showDialog, authActivity, listener);
this.authActivity = authActivity;
if (messageType == LOGIN) {
start();
} else {
authActivity.authenticatedRequest(GoogleAuthActivity.AUTHSERVER_APPENGINE, this);
}
}
@Override
public int getDialogMessage() {
switch (messageType) {
case LOGIN:
return R.string.verifying_google_account;
case COLLECTION_DOCUMENTS:
return R.string.fetching_quiz_games;
case QUIZ:
return R.string.loading_quiz;
case QUIZ_LEADERBOARD:
return R.string.fetching_leaderboard;
case QUIZ_SUBMIT:
return R.string.submitting_score;
case POLL:
return R.string.loading_polling;
case POLL_SUBMIT:
return R.string.submitting_answer;
}
return UNKNOWN_DIALOG_MESSAGE;
}
@Override
public HttpUriRequest createRequest() {
Builder url = Uri.parse(BROKER_URL).buildUpon().appendPath("qp_api");
String postData = null;
switch (messageType) {
case LOGIN:
return createLoginRequest(BROKER_URL);
case COLLECTION_DOCUMENTS:
url.appendPath("documents").appendPath((String) requestData);
break;
case QUIZ:
url.appendPath("quiz").appendPath((String) requestData);
break;
case QUIZ_LEADERBOARD:
@SuppressWarnings("unchecked")
List<String> args = (List<String>) requestData;
url.appendPath("quiz").appendPath("leaderboard").appendPath(args.get(0))
.appendPath(args.get(1));
break;
case QUIZ_SUBMIT:
url.appendPath("quiz").appendPath("submit");
postData = getGson().toJson(requestData);
break;
case POLL:
url.appendPath("poll").appendPath((String) requestData);
break;
case POLL_STATUS:
@SuppressWarnings("unchecked")
List<String> pargs = (List<String>) requestData;
url.appendPath("poll").appendPath("status").appendPath(pargs.get(0))
.appendPath(pargs.get(1));
break;
case POLL_SUBMIT:
Poll poll = (Poll) requestData;
url.appendPath("poll").appendPath("submit");
postData = createPollSubmitRequest(poll);
break;
}
if (postData == null) {
return addCookie(new HttpGet(url.build().toString()));
} else {
HttpPost post = new HttpPost(url.build().toString());
try {
post.setEntity(new StringEntity(postData, "utf8"));
} catch (UnsupportedEncodingException e) {
return null;
}
return addCookie(post);
}
}
@Override
public void parseResponse(HttpResponse response) {
if (messageType == LOGIN) {
parseLoginResponse(response);
} else {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
// Cookie expired
error(HttpStatus.SC_UNAUTHORIZED);
authActivity.authenticatedRequest(GoogleAuthActivity.AUTHSERVER_APPENGINE, this, true);
} else {
switch (messageType) {
case COLLECTION_DOCUMENTS:
handleDocuments(response);
break;
case QUIZ:
handleQuiz(response);
break;
case QUIZ_LEADERBOARD:
handleLeaderboard(response);
break;
case QUIZ_SUBMIT:
success(null); // Ignore response
break;
case POLL:
handlePoll(response);
break;
case POLL_STATUS:
handlePollStatus(response);
break;
case POLL_SUBMIT:
success(null); // Ignore response
break;
}
}
}
}
@Override
protected void error(int statusCode) {
if (statusCode == HttpStatus.SC_FORBIDDEN) {
Toast.makeText(activity, R.string.wrong_permissions_error, Toast.LENGTH_SHORT).show();
} else if (statusCode == HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE) {
Toast.makeText(activity, R.string.format_error, Toast.LENGTH_SHORT).show();
}
super.error(statusCode);
}
/**
* Makes login request to AppEngine server
*/
protected HttpUriRequest createLoginRequest(String baseUrl) {
Uri url =
Uri.parse(baseUrl).buildUpon().appendEncodedPath("_ah/login")
.appendQueryParameter("auth", (String) requestData).build();
return new HttpGet(url.toString());
}
/**
* Saves cookies from AppEngine login
*/
protected void parseLoginResponse(HttpResponse response) {
Header[] cookies = response.getHeaders("Set-Cookie");
String acsid = null;
if (cookies.length > 0) {
acsid = cookies[0].getValue().split("; ")[0];
success(acsid);
} else {
error(HttpStatus.SC_UNAUTHORIZED);
}
}
/**
* Adds AppEngine cookies to the request
*/
private HttpUriRequest addCookie(HttpUriRequest request) {
String cookie = Preferences.getString(PrefType.COOKIE_APPENGINE, activity);
if (cookie != null) {
request.setHeader("Cookie", cookie);
}
return request;
}
/**
* Create polling submit request
*/
private String createPollSubmitRequest(Poll poll) {
Question question = poll.getQuestions().get(poll.getCurrentQuestion());
List<String> answeredAnswers = new ArrayList<String>();
for (Answer answer : question.getAnswers()) {
if (answer.isAnswered()) {
answeredAnswers.add(String.valueOf(answer.getNumber() + 1));
}
}
String answers = TextUtils.join(",", answeredAnswers);
PollResponse response =
new PollResponse(poll.getDocumentId(), poll.getResponsesSheet(), question.isAnonymous(),
poll.getCurrentQuestion() + 1, answers, question.isSuccess());
return getGson().toJson(response);
}
/**
* Parses document list inside collection from broker
*/
private void handleDocuments(HttpResponse response) {
String content = readContent(response);
Type collectionType = new TypeToken<List<DocsEntry>>() {}.getType();
List<DocsEntry> entries = getGson().fromJson(content, collectionType);
success(entries);
}
/**
* Parses the quiz from broker
*/
private void handleQuiz(HttpResponse response) {
String content = readContent(response);
Quiz quiz = getGson().fromJson(content, Quiz.class);
success(quiz);
}
/**
* Parses statistics from broker
*/
private void handleLeaderboard(HttpResponse response) {
String content = readContent(response);
Type collectionType = new TypeToken<List<LeaderboardEntry>>() {}.getType();
List<LeaderboardEntry> entries = getGson().fromJson(content, collectionType);
success(entries);
}
/**
* Parses the polling from broker
*/
private void handlePoll(HttpResponse response) {
String content = readContent(response);
Poll polling = getGson().fromJson(content, Poll.class);
success(polling);
}
/**
* Parses the polling status from broker
*/
private void handlePollStatus(HttpResponse response) {
String content = readContent(response);
Integer questionNumber = getGson().fromJson(content, Integer.class);
if (questionNumber != Poll.CLOSED && questionNumber != Poll.WAITING_FOR_INSTRUCTOR) {
questionNumber--;
}
success(questionNumber);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.net;
/**
* Use this listener in activity to make HTTP requests.
*/
public abstract class HttpListener {
/**
* Handle received data in UI
*/
public abstract void onSuccess(Object responseData);
/**
* Default errors are handled in HttpHelper and children, so overriding this
* is optional
*/
public void onFailure(int errorCode) {
// Do nothing
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.quizpoll.R;
import org.quizpoll.data.model.Answer;
import org.quizpoll.data.model.Question;
import org.quizpoll.data.model.Question.QuestionType;
import org.quizpoll.data.model.Quiz;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.util.ActivityHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* Screen where actual game is played.
*/
public class QuizPlayerActivity extends GoogleAuthActivity {
@SuppressWarnings("unused")
private static final String TAG = "QuizPlayerActivity";
public static final String EXTRA_QUIZ = "org.quizpoll.Quiz";
// Constants defining rules of the game
public static final int SECONDS_PER_QUESTION = 120;
public static final int MAX_QUESTIONS = 10;
public static final int COST_OF_WRONG_ANSWER = 100;
private Quiz quiz;
private ActivityHelper activityHelper;
private int currentQuestion = -1; // Next question after start will be 0
private int remainingTime;
private int score;
private Timer timer;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_player);
quiz = (Quiz) getIntent().getSerializableExtra(EXTRA_QUIZ);
activityHelper = new ActivityHelper(this);
activityHelper.setupActionBar(""); // Empty title, it is changed in
// showQuestion
setVolumeControlStream(AudioManager.STREAM_MUSIC);
randomizeQuestions();
showNextQuestion();
handler = new Handler();
}
@Override
protected void onPause() {
super.onPause();
if (timer != null) {
timer.cancel();
}
}
/**
* Submit answer button was clicked
*/
public void submitClicked(View view) {
// Stop timer
if (timer != null) {
timer.cancel();
}
// Was the answer correct?
boolean correct = isAnswerCorrect();
// Show special effects (sound, vibration, color)
specialEffects(correct);
// Update score
updateScore(correct);
// Disable Submit button
((Button) findViewById(R.id.submit)).setEnabled(false);
// Wait some time and show next question
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Enable Submit button
((Button) findViewById(R.id.submit)).setEnabled(true);
if (currentQuestion + 1 < quiz.getQuestions().size()) {
showNextQuestion();
} else {
submitScoreAndStatistics();
}
}
}, 500);
}
/**
* Determine if answer is correct and mark this for later statistics
*/
private boolean isAnswerCorrect() {
SparseBooleanArray checkedPositions = ((ListView) findViewById(R.id.answers))
.getCheckedItemPositions();
boolean correct = true;
Question question = quiz.getQuestions().get(currentQuestion);
for (int i = 0; i < question.getAnswers().size(); i++) {
Answer answer = question.getAnswers().get(i);
boolean answered = checkedPositions.get(i);
if (answer.isCorrect() != answered) {
correct = false;
}
answer.setAnswered(answered);
}
question.setSuccess(correct);
return correct;
}
/**
* Shows question with answers in the UI
*/
private void showNextQuestion() {
currentQuestion++;
activityHelper.changeTitle(getString(R.string.question_number, (currentQuestion + 1), quiz
.getQuestions().size()));
Question question = quiz.getQuestions().get(currentQuestion);
QuestionType questionType = question.getType();
String questionText = question.getQuestionText();
if (questionType == QuestionType.MULTIPLE_CHOICE) {
findViewById(R.id.choose_all_correct).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.choose_all_correct).setVisibility(View.GONE);
}
((TextView) findViewById(R.id.question_text)).setText(questionText);
// Show answers in UI
List<String> answerTexts = new ArrayList<String>();
for (Answer answer : question.getAnswers()) {
answerTexts.add(answer.getAnswerText());
}
ListView answerList = (ListView) findViewById(R.id.answers);
// Multiple choice questions are radio buttons, Multiple select questions
// are checkboxes
if (question.getType() == QuestionType.SINGLE_CHOICE) {
answerList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
answerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.list_item_single_choice, answerTexts));
} else {
answerList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
answerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.list_item_multiple_choice, answerTexts));
}
startTimer();
}
/**
* Starts the countdown for each question
*/
private void startTimer() {
remainingTime = SECONDS_PER_QUESTION;
timer = new Timer();
final TextView timerTextView = (TextView) findViewById(R.id.timer);
final Runnable tick = new Runnable() {
@Override
public void run() {
timerTextView.setText(remainingTime + " s");
if (remainingTime <= 0) {
submitClicked(null); // Time is out, click the button
}
}
};
timer.schedule(new TimerTask() {
@Override
public void run() {
remainingTime--;
runOnUiThread(tick);
}
}, 0, 1000);
}
/**
* Update score based on correctness
*/
private void updateScore(boolean correct) {
if (correct) {
score += remainingTime;
} else {
score -= COST_OF_WRONG_ANSWER;
}
((TextView) findViewById(R.id.score)).setText(String.valueOf(score));
}
/**
* Blinks with color, plays sound and vibration based on correctness of answer
*/
private void specialEffects(boolean correct) {
// Blink bottom bar with color
final RelativeLayout bottomBar = (RelativeLayout) findViewById(R.id.bottom_bar);
if (correct) {
bottomBar.setBackgroundColor(getResources().getColor(R.color.positive));
} else {
bottomBar.setBackgroundColor(getResources().getColor(R.color.negative));
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
bottomBar.setBackgroundColor(getResources().getColor(R.color.lightgray));
}
}, 500);
// vibrate
if (!correct) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(300);
}
// play sound
if (correct) {
MediaPlayer.create(this, R.raw.positive).start();
} else {
MediaPlayer.create(this, R.raw.negative).start();
}
}
/**
* Selects subset of questions, randomizes questions and answers
*/
private void randomizeQuestions() {
//TODO(vavrad): remove this after randomizing is live on prod server
List<Question> questions = quiz.getQuestions();
Collections.shuffle(questions);
// Filter questions
if (questions.size() > MAX_QUESTIONS) {
questions = questions.subList(0, MAX_QUESTIONS);
quiz.setQuestions(questions);
}
// Randomize answers within questions
for (Question question : questions) {
Collections.shuffle(question.getAnswers());
}
}
/**
* Submits score into spreadsheet
*/
private void submitScoreAndStatistics() {
// Disable Submit button
((Button) findViewById(R.id.submit)).setEnabled(false);
// Save score
quiz.setScore(score);
new AppEngineHelper(AppEngineHelper.QUIZ_SUBMIT, quiz, true, this,
new HttpListener() {
@Override
public void onSuccess(Object responseData) {
showLeaderboard();
}
});
}
/**
* Shows native leaderboard or calls Arena
*/
private void showLeaderboard() {
Intent intent = new Intent(this,
LeaderboardActivity.class);
intent.putExtra(LeaderboardActivity.EXTRA_WORKSHEET, quiz.getLeaderboardSheet());
intent.putExtra(LeaderboardActivity.EXTRA_DOCUMENT_ID, quiz.getDocumentId());
intent.putExtra(LeaderboardActivity.EXTRA_SCORE, score);
startActivity(intent);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.quizpoll.R;
import org.quizpoll.data.QuizPollProvider.PollList;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.util.ActivityHelper;
import java.util.ArrayList;
import java.util.List;
/**
* List of recently used polls. Allows to scan QR code right from the app.
*/
public class RecentPollsActivity extends GoogleAuthActivity {
@SuppressWarnings("unused")
private static final String TAG = "RecentPollsActivity";
static final int DIALOG_CREATE_POLL = 0;
static final String INFO_URL = "http://quiz-n-poll.appspot.com";
static final int SCAN_QR = 1;
// Google Goggles use same API as Zxing's QR Code scanner, it works for both
static final String GOGGLES_INTENT = "com.google.zxing.client.android.SCAN";
static final String GOGGLES_RESULT = "SCAN_RESULT";
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recent_polls);
ActivityHelper helper = new ActivityHelper(this);
helper.setupActionBar(getString(R.string.recent_polls));
helper.addActionButtonCompat(R.drawable.ic_title_scan, new View.OnClickListener() {
@Override
public void onClick(View v) {
scanQrCode();
}
}, false);
}
@Override
protected void onStart() {
super.onStart();
new RecentPollsTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.recent_polls_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan_poll_qr:
scanQrCode();
return true;
case R.id.create_game:
showDialog(DIALOG_CREATE_POLL);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected Dialog onCreateDialog(int id) {
if (id != DIALOG_CREATE_POLL) {
throw new IllegalArgumentException("Invalid dialog");
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.create_own_poll);
alert.setMessage(R.string.create_poll_description);
alert.setPositiveButton(R.string.read_more, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(INFO_URL));
startActivity(intent);
}
});
alert.setNegativeButton(R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alert.create();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SCAN_QR && resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
String url = data.getStringExtra(GOGGLES_RESULT);
if (url != null && url.startsWith(AppEngineHelper.BROKER_URL + "/poll")) {
Intent intent = new Intent(this, PollActivity.class);
intent.setData(Uri.parse(url));
startActivity(intent);
} else {
Toast.makeText(this, R.string.unsupported_qr_code, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, R.string.qr_scan_failed, Toast.LENGTH_SHORT).show();
}
}
}
private void scanQrCode() {
try {
Intent intent = new Intent(GOGGLES_INTENT);
startActivityForResult(intent, SCAN_QR);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.goggles_needed, Toast.LENGTH_LONG).show();
// Launches Market listing of Google Goggles
Intent intent =
new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.google.android.apps.unveil"));
try {
startActivity(intent);
} catch (ActivityNotFoundException e2) {
// Ignore
}
}
}
private class RecentPollsTask extends AsyncTask<Void, Void, List<RecentPollsEntry>> {
@Override
protected List<RecentPollsEntry> doInBackground(Void... arg0) {
Cursor cursor =
getContentResolver().query(PollList.CONTENT_URI,
new String[] {PollList._ID, PollList.TITLE, PollList.DOCUMENT_ID}, null, null, null);
try {
List<RecentPollsEntry> entries = new ArrayList<RecentPollsEntry>();
while (cursor.moveToNext()) {
entries.add(new RecentPollsEntry(cursor.getString(1), cursor.getString(2)));
}
return entries;
} finally {
cursor.close();
}
}
@Override
protected void onPostExecute(final List<RecentPollsEntry> entries) {
if (entries.size() == 0) {
findViewById(R.id.no_recent_polls).setVisibility(View.VISIBLE);
findViewById(R.id.poll_list).setVisibility(View.GONE);
} else {
ListView list = ((ListView) findViewById(R.id.poll_list));
list.setVisibility(View.VISIBLE);
findViewById(R.id.no_recent_polls).setVisibility(View.GONE);
ListAdapter adapter =
new ArrayAdapter<RecentPollsEntry>(RecentPollsActivity.this,
android.R.layout.simple_list_item_1, entries);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent intent = new Intent(RecentPollsActivity.this, PollActivity.class);
String url = AppEngineHelper.BROKER_URL + "/poll/" + entries.get(position).documentId;
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
}
}
class RecentPollsEntry {
private final String title;
private final String documentId;
public RecentPollsEntry(String title, String documentId) {
this.title = title;
this.documentId = documentId;
}
public String getTitle() {
return title;
}
public String getDocumentId() {
return documentId;
}
@Override
public String toString() {
return title;
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import org.quizpoll.R;
import org.quizpoll.data.Preferences;
import org.quizpoll.data.Preferences.PrefType;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.net.HttpHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.util.Utils;
import java.io.IOException;
/**
* Handles authentication to Google Account against AppEngine instance. It uses
* ClientLogin and built-in Android auth. It's also used for authenticating
* against Google Docs API.
*/
public class GoogleAuthActivity extends Activity {
/**
* Auth server types
*/
public static final int AUTHSERVER_APPENGINE = 0;
public static final int AUTHSERVER_DOCS = 1;
@SuppressWarnings("unused")
private static final String TAG = "GoogleAuthActivity";
private static final int REQUEST_AUTHENTICATE = 0;
private static final String AUTHTYPE_APPENGINE = "ah"; // AppEngine
private static final String AUTHTYPE_DOCS_LIST = "writely"; // Google Docs
// List
private static String email;
private String authType;
private Listener listener;
/**
* Allows to renew token for each authserver just once for one session. It
* prevents infinite renewing in case of some error.
*/
private boolean[] renewedToken = new boolean[] {false, false, false};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_AUTHENTICATE) {
if (resultCode == RESULT_OK) {
start(false, listener);
} else {
listener.onFailure();
}
}
}
public void authenticatedRequest(final int server, final HttpHelper helper) {
authenticatedRequest(server, helper, false);
}
/**
* Authenticates against server if needed and then runs the request
*/
public void authenticatedRequest(final int server, final HttpHelper helper,
final boolean invalidToken) {
if (invalidToken) {
// Prevent never ending token renewals in case of errors, only one renewal
// per session is permitted
if (renewedToken[server]) {
Toast.makeText(GoogleAuthActivity.this, R.string.auth_failed, Toast.LENGTH_SHORT).show();
return;
} else {
renewedToken[server] = true;
}
}
if (email == null) {
email = Utils.getGoogleAccount(this);
}
if (email == null) {
Toast.makeText(this, R.string.google_account_required, Toast.LENGTH_LONG).show();
} else {
boolean needsAuth = true;
switch (server) {
case AUTHSERVER_APPENGINE:
authType = AUTHTYPE_APPENGINE;
needsAuth = (Preferences.getString(PrefType.COOKIE_APPENGINE, this) == null);
break;
case AUTHSERVER_DOCS:
authType = AUTHTYPE_DOCS_LIST;
needsAuth = (Preferences.getString(PrefType.AUTH_TOKEN_DOCS, this) == null);
break;
}
if (invalidToken) {
needsAuth = true;
}
if (!needsAuth) {
helper.start();
} else {
start(invalidToken, new Listener() {
@Override
public void onSuccess() {
switch (server) {
case AUTHSERVER_APPENGINE:
new AppEngineHelper(AppEngineHelper.LOGIN, Preferences.getString(
PrefType.AUTH_TOKEN_AE, GoogleAuthActivity.this), true,
GoogleAuthActivity.this, new HttpListener() {
@Override
public void onSuccess(Object responseData) {
Preferences.add(PrefType.COOKIE_APPENGINE, (String) responseData,
GoogleAuthActivity.this);
helper.start();
}
});
break;
case AUTHSERVER_DOCS:
helper.start();
break;
}
}
@Override
public void onFailure() {
Toast.makeText(GoogleAuthActivity.this, R.string.auth_failed, Toast.LENGTH_SHORT)
.show();
}
});
}
}
}
/**
* Starts auth process.
*/
private void start(boolean tokenExpired, Listener listener) {
this.listener = listener;
AccountManager manager = AccountManager.get(this);
if (tokenExpired) {
if (authType.equals(AUTHTYPE_APPENGINE)) {
manager.invalidateAuthToken("com.google",
Preferences.getString(PrefType.AUTH_TOKEN_AE, this));
} else if (authType.equals(AUTHTYPE_DOCS_LIST)) {
manager.invalidateAuthToken("com.google",
Preferences.getString(PrefType.AUTH_TOKEN_DOCS, this));
}
}
Account[] accounts = manager.getAccountsByType("com.google");
for (Account account : accounts) {
if (account.name.trim().equals(email.trim())) {
authenticate(manager, account);
break;
}
}
}
/**
* Authenticate using native Android auth mechanism.
*/
private void authenticate(final AccountManager manager, final Account account) {
manager.getAuthToken(account, authType, null, this, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
Bundle bundle;
try {
bundle = future.getResult();
} catch (OperationCanceledException e) {
bundle = null;
} catch (AuthenticatorException e) {
bundle = null;
} catch (IOException e) {
bundle = null;
}
if (bundle == null) {
listener.onFailure();
return;
}
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
int flags = intent.getFlags();
flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags(flags);
startActivityForResult(intent, REQUEST_AUTHENTICATE);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
handleAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
}
}
}, null);
}
/**
* Finish auth process - save auth token
*/
private void handleAuthToken(String authToken) {
Preferences.add(PrefType.USER_EMAIL, email, this);
if (authType.equals(AUTHTYPE_APPENGINE)) {
Preferences.add(PrefType.AUTH_TOKEN_AE, authToken, this);
listener.onSuccess();
} else if (authType.equals(AUTHTYPE_DOCS_LIST)) {
Preferences.add(PrefType.AUTH_TOKEN_DOCS, authToken, this);
listener.onSuccess();
}
}
/**
* Listener for google auth
*/
public interface Listener {
public void onSuccess();
public void onFailure();
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import org.quizpoll.R;
import org.quizpoll.util.ActivityHelper;
/**
* Home screen of the app. Uses DashBoardLayout for main app icons.
*/
public class HomeActivity extends Activity {
@SuppressWarnings("unused")
private static final String TAG = "HomeActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityHelper helper = new ActivityHelper(this);
helper.setupActionBar(null); // No title, app name instead
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return true;
}
/**
* When menu item selected.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
startActivity(new Intent(this, AboutActivity.class));
return true;
// More menu items to come
default:
return super.onOptionsItemSelected(item);
}
}
/**
* When button Quiz Games clicked
*/
public void gamesClicked(View view) {
Intent intent = new Intent(HomeActivity.this, QuizBrowserActivity.class);
intent.putExtra(QuizBrowserActivity.EXTRA_COLLECTION_ID,
QuizBrowserActivity.QUIZZES_SHARED_COLLECTION);
intent.putExtra(QuizBrowserActivity.EXTRA_TITLE, getString(R.string.public_quizzes));
startActivity(intent);
}
/**
* When button Polling clicked
*/
public void pollingClicked(View view) {
Intent intent = new Intent(HomeActivity.this, RecentPollsActivity.class);
startActivity(intent);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.quizpoll.R;
import org.quizpoll.data.model.DocsEntry;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.net.DocsHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.util.ActivityHelper;
import java.util.ArrayList;
import java.util.Collections;
/**
* Browser for available quizzes. Uses Google Document List API - collections
* and spreadsheets.
*/
public class QuizBrowserActivity extends GoogleAuthActivity implements OnItemClickListener {
@SuppressWarnings("unused")
private static final String TAG = "QuizBrowserActivity";
public static final String EXTRA_COLLECTION_ID = "org.quizpoll.CollectionId";
public static final String EXTRA_TITLE = "org.quizpoll.Title";
static final String INFO_URL = "http://quiz-n-poll.appspot.com";
static final int DIALOG_CREATE_GAME = 0;
// ID of shared collection in Docs containing all quizzes
public static final String QUIZZES_SHARED_COLLECTION =
"0B6rxb_ov7Sd5OWVkNmEyNTAtNWM1Ni00Yzg2LWE0NmEtYjc3YzIyOTcxNjU4";
private ArrayList<DocsEntry> docsEntries;
private boolean privateQuizGames = false;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_browser);
String title = getIntent().getStringExtra(EXTRA_TITLE);
ActivityHelper helper = new ActivityHelper(this);
helper.setupActionBar(title);
String collectionId = getIntent().getStringExtra(EXTRA_COLLECTION_ID);
if (collectionId == null) {
privateQuizGames = true;
}
if (privateQuizGames) {
fetchPrivateDocList();
} else {
fetchCollectionDocList(collectionId);
helper.addActionButtonCompat(R.drawable.ic_title_private, new View.OnClickListener() {
@Override
public void onClick(View v) {
showPrivateQuizzes();
}
}, false);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!privateQuizGames) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.quiz_browser_menu, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.private_quiz:
showPrivateQuizzes();
return true;
case R.id.create_game:
showDialog(DIALOG_CREATE_GAME);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onItemClick(final AdapterView<?> adapter, final View view, final int position,
final long id) {
final DocsEntry item = docsEntries.get(position);
switch (item.getType()) {
case DocsEntry.COLLECTION:
Intent intent = new Intent(QuizBrowserActivity.this, QuizBrowserActivity.class);
intent.putExtra(QuizBrowserActivity.EXTRA_COLLECTION_ID, item.getId());
intent.putExtra(QuizBrowserActivity.EXTRA_TITLE, item.getTitle());
startActivity(intent);
break;
case DocsEntry.QUIZ:
Intent intent2 = new Intent(this, QuizInfoActivity.class);
intent2.putExtra(QuizInfoActivity.EXTRA_DOC_ID, item.getId());
startActivity(intent2);
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_CREATE_GAME) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.create_own_game);
alert.setMessage(R.string.create_description);
alert.setPositiveButton(R.string.read_more, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(INFO_URL));
startActivity(intent);
}
});
alert.setNegativeButton(R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alert.create();
}
return null;
}
/**
* Fetch private quizzes
*/
private void fetchPrivateDocList() {
new DocsHelper(DocsHelper.MY_DOCUMENTS, null, true, QuizBrowserActivity.this,
new HttpListener() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(Object responseData) {
docsEntries = (ArrayList<DocsEntry>) responseData;
ListView list = (ListView) findViewById(R.id.quiz_list);
list.setAdapter(new DocsListAdapter(QuizBrowserActivity.this, R.layout.list_item_icon,
docsEntries));
list.setOnItemClickListener(QuizBrowserActivity.this);
}
});
}
/**
* Fetch documents from some collection
*/
private void fetchCollectionDocList(final String collectionId) {
new AppEngineHelper(AppEngineHelper.COLLECTION_DOCUMENTS, collectionId, true,
QuizBrowserActivity.this, new HttpListener() {
@SuppressWarnings("unchecked")
@Override
public void onSuccess(Object responseData) {
docsEntries = (ArrayList<DocsEntry>) responseData;
Collections.sort(docsEntries);
ListView list = (ListView) findViewById(R.id.quiz_list);
list.setAdapter(new DocsListAdapter(QuizBrowserActivity.this, R.layout.list_item_icon,
docsEntries));
list.setOnItemClickListener(QuizBrowserActivity.this);
}
});
}
/**
* Shows user's spreadsheets
*/
private void showPrivateQuizzes() {
Intent intent = new Intent(this, QuizBrowserActivity.class);
intent.putExtra(QuizBrowserActivity.EXTRA_TITLE, getString(R.string.my_own_quiz_games));
startActivity(intent);
}
/**
* List adapter for document list, showing name of the spreadsheet/folder and
* icon
*/
private class DocsListAdapter extends ArrayAdapter<DocsEntry> {
private ArrayList<DocsEntry> items;
public DocsListAdapter(Context context, int textViewResourceId, ArrayList<DocsEntry> items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item_icon, parent, false);
}
DocsEntry item = items.get(position);
TextView text = (TextView) view.findViewById(R.id.title);
text.setText(item.getTitle());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
switch (item.getType()) {
case DocsEntry.COLLECTION:
icon.setImageResource(R.drawable.folder);
break;
case DocsEntry.QUIZ:
icon.setImageResource(R.drawable.quiz);
break;
}
return view;
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.quizpoll.R;
import org.quizpoll.data.model.Quiz;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.net.HttpHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.net.ImageDownloadHelper;
import org.quizpoll.util.ActivityHelper;
/**
* Info screen for selected quiz. Starts the game.
*/
public class QuizInfoActivity extends GoogleAuthActivity {
@SuppressWarnings("unused")
private static final String TAG = "QuizInfoActivity";
public static final String EXTRA_DOC_ID = "org.quizpoll.DocId";
private Quiz quiz;
private ActivityHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_info);
String docId;
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
// This activity was called from URL directly
docId = getIntent().getData().getLastPathSegment();
} else {
// Called from the list of spreadsheets
docId = getIntent().getStringExtra(EXTRA_DOC_ID);
}
helper = new ActivityHelper(QuizInfoActivity.this);
helper.setupActionBar(getString(R.string.quiz_game_detail));
fetchQuiz(docId);
// Button in action bar for sharing quizzes
helper.addActionButtonCompat(R.drawable.ic_title_share, new View.OnClickListener() {
@Override
public void onClick(View v) {
shareQuiz();
}
}, false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.quiz_info_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
shareQuiz();
return true;
// More menu items to come
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Starts the game
*/
public void startClicked(View view) {
Intent intent = new Intent(QuizInfoActivity.this,
QuizPlayerActivity.class);
intent.putExtra(QuizPlayerActivity.EXTRA_QUIZ, quiz);
startActivity(intent);
finish();
}
/**
* Shows the leaderboard directly
*/
public void leaderboardClicked(View view) {
Intent intent = new Intent(QuizInfoActivity.this,
LeaderboardActivity.class);
intent.putExtra(LeaderboardActivity.EXTRA_DOCUMENT_ID, quiz.getDocumentId());
intent.putExtra(LeaderboardActivity.EXTRA_WORKSHEET, quiz.getLeaderboardSheet());
startActivity(intent);
}
/**
* Fetch worksheets of selected spreadsheet
*/
private void fetchQuiz(final String docId) {
new AppEngineHelper(AppEngineHelper.QUIZ, docId, true, this,
new HttpListener() {
@Override
public void onSuccess(Object responseData) {
quiz = (Quiz) responseData;
helper.changeTitle(quiz.getTitle());
((TextView) findViewById(R.id.quiz_description)).setText(quiz.getDescription());
((LinearLayout) findViewById(R.id.quiz_info)).setVisibility(View.VISIBLE);
// Download image
new ImageDownloadHelper(HttpHelper.SINGLE_MESSAGE_TYPE, quiz.getImage(), false,
QuizInfoActivity.this,
new HttpListener() {
@Override
public void onSuccess(Object responseData) {
Bitmap bitmap = (Bitmap) responseData;
((ImageView) findViewById(R.id.quiz_image)).setImageBitmap(bitmap);
}
});
}
});
}
/**
* Shares quiz using ShareActivity
*/
private void shareQuiz() {
Intent intent = new Intent(this, ShareActivity.class);
Uri url = Uri.parse(AppEngineHelper.BROKER_URL + "/quiz/").buildUpon()
.appendPath(quiz.getDocumentId()).build();
intent.putExtra(ShareActivity.EXTRA_URL, url.toString());
intent.putExtra(ShareActivity.EXTRA_QUIZ_NAME, quiz.getTitle());
startActivity(intent);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import org.quizpoll.R;
import org.quizpoll.util.ActivityHelper;
/**
* Screen for user feedback and help.
*/
public class AboutActivity extends Activity {
public static final String INFO_URL = "http://quiz-n-poll.appspot.com";
public static final String FEEDBACK_EMAIL = "quiz-and-poll@googlegroups.com";
public static final String MARKET_LISTING = "market://details?id=org.quizpoll";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
new ActivityHelper(this).setupActionBar(getString(R.string.about));
}
/**
* Sends e-mail to developer with some predefined text.
*/
public void mailClicked(View view) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {FEEDBACK_EMAIL});
i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.feedback_subject));
String device =
Build.MANUFACTURER + " " + Build.MODEL + " (Android " + Build.VERSION.RELEASE + ")";
i.putExtra(Intent.EXTRA_TEXT, getString(R.string.feedback_text, device));
startActivity(i);
}
/**
* Opens website of the project.
*/
public void webClicked(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(INFO_URL));
startActivity(intent);
}
/**
* Opens Android Market listing
*/
public void rate(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_LISTING));
startActivity(intent);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Custom layout that arranges children in a grid-like manner, optimizing for
* even horizontal and vertical whitespace. Taken from Google IO 2011 app.
*/
public class DashboardLayout extends ViewGroup {
private static final int UNEVEN_GRID_PENALTY_MULTIPLIER = 10;
private int mMaxChildWidth = 0;
private int mMaxChildHeight = 0;
public DashboardLayout(Context context) {
super(context, null);
}
public DashboardLayout(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public DashboardLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mMaxChildWidth = 0;
mMaxChildHeight = 0;
// Measure once to find the maximum child size.
int childWidthMeasureSpec =
MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
int childHeightMeasureSpec =
MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST);
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
mMaxChildWidth = Math.max(mMaxChildWidth, child.getMeasuredWidth());
mMaxChildHeight = Math.max(mMaxChildHeight, child.getMeasuredHeight());
}
// Measure again for each child to be exactly the same size.
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxChildWidth, MeasureSpec.EXACTLY);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxChildHeight, MeasureSpec.EXACTLY);
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
setMeasuredDimension(resolveSize(mMaxChildWidth, widthMeasureSpec),
resolveSize(mMaxChildHeight, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
final int count = getChildCount();
// Calculate the number of visible children.
int visibleCount = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
++visibleCount;
}
if (visibleCount == 0) {
return;
}
// Calculate what number of rows and columns will optimize for even
// horizontal and
// vertical whitespace between items. Start with a 1 x N grid, then try 2 x
// N, and so on.
int bestSpaceDifference = Integer.MAX_VALUE;
int spaceDifference;
// Horizontal and vertical space between items
int hSpace = 0;
int vSpace = 0;
int cols = 1;
int rows;
while (true) {
rows = (visibleCount - 1) / cols + 1;
hSpace = ((width - mMaxChildWidth * cols) / (cols + 1));
vSpace = ((height - mMaxChildHeight * rows) / (rows + 1));
spaceDifference = Math.abs(vSpace - hSpace);
if (rows * cols != visibleCount) {
spaceDifference *= UNEVEN_GRID_PENALTY_MULTIPLIER;
}
if (spaceDifference < bestSpaceDifference) {
// Found a better whitespace squareness/ratio
bestSpaceDifference = spaceDifference;
// If we found a better whitespace squareness and there's only 1 row,
// this is
// the best we can do.
if (rows == 1) {
break;
}
} else {
// This is a worse whitespace ratio, use the previous value of cols and
// exit.
--cols;
rows = (visibleCount - 1) / cols + 1;
hSpace = ((width - mMaxChildWidth * cols) / (cols + 1));
vSpace = ((height - mMaxChildHeight * rows) / (rows + 1));
break;
}
++cols;
}
// Lay out children based on calculated best-fit number of rows and cols.
// If we chose a layout that has negative horizontal or vertical space,
// force it to zero.
hSpace = Math.max(0, hSpace);
vSpace = Math.max(0, vSpace);
// Re-use width/height variables to be child width/height.
width = (width - hSpace * (cols + 1)) / cols;
height = (height - vSpace * (rows + 1)) / rows;
int left, top;
int col, row;
int visibleIndex = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
row = visibleIndex / cols;
col = visibleIndex % cols;
left = hSpace * (col + 1) + width * col;
top = vSpace * (row + 1) + height * row;
child.layout(left, top, (hSpace == 0 && col == cols - 1) ? r : (left + width),
(vSpace == 0 && row == rows - 1) ? b : (top + height));
++visibleIndex;
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui.widget;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Custom ImageView handling QR code generation using Zxing library.
*/
public class QrCodeView extends ImageView {
private String url;
public QrCodeView(Context context) {
super(context, null);
}
public QrCodeView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public QrCodeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setUrl(String url) {
this.url = url;
new GenerateQrTask().execute();
}
private class GenerateQrTask extends AsyncTask<Void, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Void... arg0) {
if (url == null) {
return null;
}
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix =
writer.encode(url, BarcodeFormat.QR_CODE,
QrCodeView.this.getHeight(), QrCodeView.this.getHeight());
} catch (WriterException e) {
e.printStackTrace();
}
int width = matrix.getWidth();
int height = matrix.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
QrCodeView.this.setImageBitmap(result);
}
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.quizpoll.R;
import org.quizpoll.data.model.LeaderboardEntry;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.util.ActivityHelper;
import org.quizpoll.util.Utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Screen where leaderboard is shown. It is native leaderboard with data from
* spreadsheet.
*/
public class LeaderboardActivity extends GoogleAuthActivity {
@SuppressWarnings("unused")
private static final String TAG = "LeaderboardActivity";
public static final String EXTRA_DOCUMENT_ID = "org.quizpoll.DocumentId";
public static final String EXTRA_SCORE = "org.quizpoll.Score";
public static final String EXTRA_WORKSHEET = "org.quizpoll.Worksheet";
private String documentId;
private String worksheetId;
private int score;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
ActivityHelper helper = new ActivityHelper(this);
helper.setupActionBar(getString(R.string.leaderboard));
helper.addActionButtonCompat(R.drawable.ic_title_refresh, new OnClickListener() {
@Override
public void onClick(View v) {
fetchLeaderboard();
}
}, false);
documentId = getIntent().getStringExtra(EXTRA_DOCUMENT_ID);
worksheetId = getIntent().getStringExtra(EXTRA_WORKSHEET);
score = getIntent().getIntExtra(EXTRA_SCORE, Integer.MIN_VALUE);
fetchLeaderboard();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.leaderboard_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
fetchLeaderboard();
return true;
// More menu items to come
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Try again button was clicked
*/
public void tryAgainClicked(View view) {
Intent intent = new Intent(this, QuizInfoActivity.class);
intent.putExtra(QuizInfoActivity.EXTRA_DOC_ID, documentId);
startActivity(intent);
finish();
}
/**
* Loads leaderboard data into UI
*/
private void load(List<LeaderboardEntry> entries) {
Collections.sort(entries);
ListView list = (ListView) findViewById(R.id.leaderboard_list);
list.setAdapter(new LeaderboardAdapter(this, R.layout.list_item_leaderboard, entries));
// Select player
boolean firstInLeaderboard = false;
String ldap = Utils.getLdap(this);
int position = -1;
int lastScore = Integer.MIN_VALUE;
for (int i = 0; i < entries.size(); i++) {
LeaderboardEntry entry = entries.get(i);
if (ldap.equals(entry.getLdap())) {
position = i;
lastScore = entry.getScore();
}
}
if (position != -1) {
list.setSelection(position);
if (position == 0) {
firstInLeaderboard = true;
}
}
// React to score change after game
if (score == Integer.MIN_VALUE) {
// Leaderboard directly from QuizInfo
findViewById(R.id.bottom_bar).setVisibility(View.GONE);
} else {
// Leaderboard after game
TextView status = (TextView) findViewById(R.id.status_message);
if (firstInLeaderboard) {
status.setText(R.string.no_1);
} else {
if (score >= lastScore) {
status.setText(R.string.new_highscore);
} else {
status.setText(getString(R.string.less_than_highscore, score));
}
}
}
}
/**
* Reloads leaderboard
*/
private void fetchLeaderboard() {
List<String> arguments = new ArrayList<String>();
arguments.add(documentId);
arguments.add(worksheetId);
new AppEngineHelper(AppEngineHelper.QUIZ_LEADERBOARD, arguments, true, this,
new HttpListener() {
@Override
public void onSuccess(Object responseData) {
@SuppressWarnings("unchecked")
List<LeaderboardEntry> entries = (List<LeaderboardEntry>) responseData;
load(entries);
}
});
}
/**
* Adapter to fill leaderboard data into the list
*/
private class LeaderboardAdapter extends ArrayAdapter<LeaderboardEntry> {
private List<LeaderboardEntry> entries;
private String player;
private Context context;
public LeaderboardAdapter(Context context, int textViewResourceId,
List<LeaderboardEntry> entries) {
super(context, textViewResourceId, entries);
this.entries = entries;
player = Utils.getLdap(context);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_item_leaderboard, parent, false);
}
LeaderboardEntry entry = entries.get(position);
TextView number = (TextView) convertView.findViewById(R.id.number);
number.setText((position + 1) + ".");
TextView ldap = (TextView) convertView.findViewById(R.id.ldap);
ldap.setText(entry.getLdap());
TextView score = (TextView) convertView.findViewById(R.id.score);
score.setText(String.valueOf(entry.getScore()));
// Coloring of this player
if (entry.getLdap().equals(player)) {
convertView.setBackgroundColor(context.getResources().getColor(R.color.pressed_start));
ldap.setTextColor(Color.BLACK);
} else {
convertView.setBackgroundColor(Color.WHITE);
ldap.setTextColor(context.getResources().getColor(R.color.orange));
}
return convertView;
}
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.quizpoll.R;
import org.quizpoll.net.HttpHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.net.UrlShortenerHelper;
import org.quizpoll.ui.widget.QrCodeView;
import org.quizpoll.util.ActivityHelper;
import java.io.IOException;
/**
* Allows sharing of URL using NFC, NFC stickers, QR codes of e-mail. Supports
* Quiz Games and Polls. Uses URL shortener for links in NFC and QR.
*/
public class ShareActivity extends Activity {
@SuppressWarnings("unused")
private static final String TAG = "ShareActivity";
public static final String EXTRA_URL = "org.quizpoll.Url";
public static final String EXTRA_QUIZ_NAME = "org.quizpoll.QuizName";
public static final String EXTRA_POLL_NAME = "org.quizpoll.PollName";
static final int DIALOG_NFC_STICKER = 0;
private boolean nfcBroadcasting = false;
private boolean nfcAvailable = false;
private NfcAdapter nfcAdapter;
private ActivityHelper helper;
private String originalUrl;
private String shortenedUrl;
private String quizName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
helper = new ActivityHelper(this);
// Shorten URL and start sharing
originalUrl = getIntent().getStringExtra(EXTRA_URL);
shortenUrl(originalUrl);
quizName = getIntent().getStringExtra(EXTRA_QUIZ_NAME);
if (quizName != null) {
helper.setupActionBar(getString(R.string.share_quiz));
} else {
quizName = getIntent().getStringExtra(EXTRA_POLL_NAME);
helper.setupActionBar(getString(R.string.share_poll));
}
((TextView) findViewById(R.id.content_title)).setText(quizName);
helper.addActionButtonCompat(R.drawable.ic_title_send, new View.OnClickListener() {
@Override
public void onClick(View v) {
shareByEmail();
}
}, false);
}
@Override
protected void onResume() {
super.onResume();
// If NFC is supported, start broadcasting
if (nfcAvailable && !nfcBroadcasting) {
nfcBroadcasting = true;
enableNdefExchangeMode();
}
}
@Override
protected void onPause() {
if (nfcBroadcasting) {
disableNdefExchangeMode();
nfcBroadcasting = false;
}
super.onPause();
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_NFC_STICKER) {
// Show UI
AlertDialog.Builder alert = new AlertDialog.Builder(ShareActivity.this);
alert.setTitle(R.string.write_to_sticker);
alert.setMessage(R.string.nfc_sticker_message);
alert.setNegativeButton(R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
disableTagWriteMode();
}
});
enableTagWriteMode();
return alert.create();
}
return null;
}
@Override
protected void onNewIntent(Intent intent) {
// Tag writing mode
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(encodeUrlAsNdef(), detectedTag);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.share_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.write:
if (nfcAvailable) {
showDialog(DIALOG_NFC_STICKER);
}
return true;
case R.id.send:
shareByEmail();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Shares quiz or session via e-mail
*/
private void shareByEmail() {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String subject;
subject = getString(R.string.email_subject_quiz, quizName);
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
getString(R.string.email_text, originalUrl));
startActivity(shareIntent);
}
/**
* Starts broadcasting NFC and enables QR code
*/
private void startSharing(String url) {
this.shortenedUrl = url;
((QrCodeView) findViewById(R.id.qr_code)).setUrl(url);
// Setup NFC
if (Build.VERSION.SDK_INT >= 10
&& getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) {
enableNfcFunctions(helper);
nfcAvailable = true;
onResume();
} else {
// NFC not available
((ProgressBar) findViewById(R.id.nfc_progress)).setIndeterminate(false);
((TextView) findViewById(R.id.nfc_text)).setText(R.string.nfc_not_available);
}
}
/**
* Try to shorten URL for marking attendance and show attendance tracking
* activity. Shortening is needed, because current URLs exceeds memory of NFC
* stickers. It also makes NFC and QR scanning much faster.
*/
private void shortenUrl(final String url) {
new UrlShortenerHelper(HttpHelper.SINGLE_MESSAGE_TYPE, url, true, this, new HttpListener() {
@Override
public void onSuccess(Object responseData) {
// Use shortened URL
startSharing((String) responseData);
}
@Override
public void onFailure(int errorCode) {
// Use full URL without shortener
startSharing(url);
}
});
}
/**
* Enable specific functionality for phones which support NFC.
*/
private void enableNfcFunctions(ActivityHelper helper) {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// Button in actionbar for writing to NFC sticker
helper.addActionButtonCompat(R.drawable.ic_title_write, new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_NFC_STICKER);
}
}, false);
}
/**
* Starts to broadcast URL to any NFC-capable device nearby.
*/
private void enableNdefExchangeMode() {
nfcAdapter.enableForegroundNdefPush(this, encodeUrlAsNdef());
}
/**
* Encodes attendance tracking URL in NDEF format for NFC.
*/
private NdefMessage encodeUrlAsNdef() {
NdefRecord textRecord =
new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, NdefRecord.RTD_URI, new byte[0],
shortenedUrl.getBytes());
return new NdefMessage(new NdefRecord[] {textRecord});
}
/**
* Stops URL broadcasting.
*/
private void disableNdefExchangeMode() {
nfcAdapter.disableForegroundNdefPush(this);
}
/**
* Starts writing to any writable NFC tag nearby.
*/
private void enableTagWriteMode() {
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter[] writeTagFilters = new IntentFilter[] {tagDetected};
PendingIntent nfcPendingIntent =
PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, writeTagFilters, null);
}
/**
* Stops writing to NFC tags.
*/
private void disableTagWriteMode() {
nfcAdapter.disableForegroundDispatch(this);
}
/**
* Actually writes data into tag (sticker).
*/
private void writeTag(NdefMessage message, Tag tag) {
int size = message.toByteArray().length;
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
toast(R.string.tag_read_only);
return;
}
if (ndef.getMaxSize() < size) {
toast(R.string.exceeded_tag_capacity);
return;
}
ndef.writeNdefMessage(message);
toast(R.string.sticker_write_success);
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
toast(R.string.sticker_write_success);
} catch (IOException e) {
toast(R.string.sticker_write_error);
}
} else {
toast(R.string.sticker_write_error);
}
}
} catch (FormatException e) {
toast(R.string.sticker_write_error);
} catch (IOException e) {
toast(R.string.sticker_write_error);
}
}
private void toast(int text) {
Toast.makeText(this, getString(text), Toast.LENGTH_LONG).show();
dismissDialog(DIALOG_NFC_STICKER);
}
}
| Java |
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.quizpoll.ui;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.quizpoll.R;
import org.quizpoll.data.QuizPollProvider.PollList;
import org.quizpoll.data.model.Answer;
import org.quizpoll.data.model.Poll;
import org.quizpoll.data.model.Question;
import org.quizpoll.data.model.Question.QuestionType;
import org.quizpoll.net.AppEngineHelper;
import org.quizpoll.net.HttpListener;
import org.quizpoll.util.ActivityHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* Screen for polling. It's launched only from link, so it works like private
* quiz. Polling is basically a type of quiz which is driven by the instructor
* (using interface written in Apps Script).
*/
public class PollActivity extends GoogleAuthActivity {
@SuppressWarnings("unused")
private static final String TAG = "PollActivity";
// How often to check if there is new question
private static final int CHECKING_INTERVAL = 3000;
private static final int NOTIFICATION_ID = 1;
private ActivityHelper activityHelper;
private static Poll poll;
private Timer timer;
private Handler handler = new Handler();
// UI elements for faster access
LinearLayout questionLayout;
LinearLayout waitingLayout;
ProgressBar waitingProgress;
TextView statusTextView;
TextView questionTextView;
TextView anonymousTextView;
TextView chooseAllCorrect;
ListView answerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_polling);
activityHelper = new ActivityHelper(this);
activityHelper.setupActionBar(getString(R.string.loading_polling), false);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (getIntent().getData() != null) {
// Called from URL
poll = null;
String docId = getIntent().getData().getLastPathSegment();
fetchPoll(docId);
} else {
// Called from notification
if (savedInstanceState != null) {
// if activity was killed in the meantime
poll = (Poll) savedInstanceState.getSerializable("poll");
}
if (poll != null) {
activityHelper.changeTitle(poll.getTitle());
}
}
// Button in action bar for sharing quizzes
activityHelper.addActionButtonCompat(R.drawable.ic_title_share, new View.OnClickListener() {
@Override
public void onClick(View v) {
sharePoll();
}
}, false);
// Load UI elements for better performance
questionLayout = (LinearLayout) findViewById(R.id.question);
waitingLayout = (LinearLayout) findViewById(R.id.waiting);
waitingProgress = (ProgressBar) findViewById(R.id.polling_progress);
statusTextView = (TextView) findViewById(R.id.polling_status);
questionTextView = (TextView) findViewById(R.id.question_text);
anonymousTextView = (TextView) findViewById(R.id.anonymous);
answerList = (ListView) findViewById(R.id.answers);
chooseAllCorrect = (TextView) findViewById(R.id.choose_all_correct);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("poll", poll);
super.onSaveInstanceState(outState);
}
@Override
protected void onStart() {
super.onStart();
if (poll != null) {
poll.setCurrentQuestion(Poll.UNKNOWN);
startTimer();
}
}
@Override
protected void onStop() {
if (timer != null) {
timer.cancel();
}
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.polling_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exit:
hideNotification();
finish();
return true;
case R.id.share:
sharePoll();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Submit answer button was clicked
*/
public void submitClicked(View view) {
// Was the answer correct?
boolean correct = isAnswerCorrect();
// Show special effects (sound, vibration, color)
specialEffects(correct);
// Submit response
new AppEngineHelper(AppEngineHelper.POLL_SUBMIT, poll, true, this, new HttpListener() {
@Override
public void onSuccess(Object responseData) {
waitForInstructor();
}
});
}
/**
* Exit button clicked
*/
public void exitClicked(View view) {
hideNotification();
finish();
}
/**
* Shows notification to access running polling later
*/
private void showNotification() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification =
new Notification(R.drawable.ic_stat_polling, null, System
.currentTimeMillis());
notification.flags |= Notification.FLAG_ONGOING_EVENT;
Intent notificationIntent = new Intent(this, PollActivity.class);
PendingIntent contentIntent =
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, getString(R.string.running_polling), poll.getTitle(),
contentIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
}
/**
* Disables notification
*/
private void hideNotification() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
/**
* Determine if answer is correct and mark this for later statistics
*/
private boolean isAnswerCorrect() {
SparseBooleanArray checkedPositions = answerList.getCheckedItemPositions();
boolean correct = true;
Question question = poll.getQuestions().get(poll.getCurrentQuestion());
for (int i = 0; i < question.getAnswers().size(); i++) {
Answer answer = question.getAnswers().get(i);
boolean answered = checkedPositions.get(i);
if (answer.isCorrect() != answered) {
correct = false;
}
answer.setAnswered(answered);
}
question.setSuccess(correct);
return correct;
}
/**
* During polling, app periodically checks the spreadsheet for current
* question and it shows it.
*/
private void startTimer() {
timer = new Timer();
final Runnable tick = new Runnable() {
@Override
public void run() {
List<String> arguments = new ArrayList<String>();
arguments.add(poll.getDocumentId());
arguments.add(poll.getInternalDataSheet());
new AppEngineHelper(AppEngineHelper.POLL_STATUS, arguments, false, PollActivity.this,
new HttpListener() {
@Override
public void onSuccess(Object responseData) {
int questionNumber = (Integer) responseData;
if (questionNumber != poll.getCurrentQuestion()) {
poll.setCurrentQuestion(questionNumber);
if (questionNumber == Poll.WAITING_FOR_INSTRUCTOR) {
waitForInstructor();
} else if (questionNumber == Poll.CLOSED) {
closePolling();
} else {
showQuestion();
}
}
}
});
}
};
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(tick);
}
}, 0, CHECKING_INTERVAL);
}
/**
* This screen is shown when instructor don't want students to answer anything
*/
private void waitForInstructor() {
questionLayout.setVisibility(View.GONE);
waitingLayout.setVisibility(View.VISIBLE);
waitingProgress.setVisibility(View.VISIBLE);
statusTextView.setText(R.string.waiting_for_instructor);
}
/**
* Is showed when instructor goes to results - polling is closed.
*/
private void closePolling() {
questionLayout.setVisibility(View.GONE);
waitingLayout.setVisibility(View.VISIBLE);
waitingProgress.setVisibility(View.GONE);
statusTextView.setText(R.string.polling_is_closed);
hideNotification();
if (timer != null) {
timer.cancel();
}
timer = null;
}
/**
* Shows question with answers in the UI
*/
private void showQuestion() {
questionLayout.setVisibility(View.VISIBLE);
waitingLayout.setVisibility(View.GONE);
Question question = poll.getQuestions().get(poll.getCurrentQuestion());
QuestionType questionType = question.getType();
String questionText = question.getQuestionText();
if (questionType == QuestionType.MULTIPLE_CHOICE) {
chooseAllCorrect.setVisibility(View.VISIBLE);
} else {
chooseAllCorrect.setVisibility(View.GONE);
}
questionTextView.setText(questionText);
// Show answers in UI
List<String> answerTexts = new ArrayList<String>();
for (Answer answer : question.getAnswers()) {
answerTexts.add(answer.getAnswerText());
}
// Multiple choice questions are radio buttons, Multiple select questions
// are checkboxes
if (question.getType() == QuestionType.SINGLE_CHOICE) {
answerList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
answerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.list_item_single_choice, answerTexts));
} else {
answerList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
answerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.list_item_multiple_choice, answerTexts));
}
// anonymous question
if (question.isAnonymous()) {
anonymousTextView.setVisibility(View.VISIBLE);
} else {
anonymousTextView.setVisibility(View.GONE);
}
}
/**
* Blinks with color, plays sound and vibration based on correctness of answer
*/
private void specialEffects(boolean correct) {
// Blink bottom bar with color
if (correct) {
questionLayout.setBackgroundColor(getResources().getColor(R.color.positive));
} else {
questionLayout.setBackgroundColor(getResources().getColor(R.color.negative));
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
questionLayout.setBackgroundColor(getResources().getColor(android.R.color.white));
}
}, 500);
// vibrate
if (!correct) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(300);
}
// play sound
if (correct) {
MediaPlayer.create(this, R.raw.positive).start();
} else {
MediaPlayer.create(this, R.raw.negative).start();
}
}
/**
* Fetch worksheets of selected spreadsheet
*/
private void fetchPoll(final String docId) {
new AppEngineHelper(AppEngineHelper.POLL, docId, true, this,
new HttpListener() {
@Override
public void onSuccess(Object responseData) {
poll = (Poll) responseData;
poll.setCurrentQuestion(Poll.UNKNOWN);
activityHelper.changeTitle(poll.getTitle());
showNotification();
startTimer();
savePollAccess();
}
});
}
/**
* Saves poll into recent polls for easy access later
*/
private void savePollAccess() {
Cursor cursor = getContentResolver().query(PollList.CONTENT_URI, new String[] {
PollList.DOCUMENT_ID
}, null, null, null);
try {
boolean found = false;
while (cursor.moveToNext()) {
if (cursor.getString(0).equals(poll.getDocumentId())) {
found = true;
break;
}
}
if (found) {
ContentValues values = new ContentValues();
values.put(PollList.TITLE, poll.getTitle());
getContentResolver().update(Uri.parse(PollList.ITEM_URI + "/" + poll.getDocumentId()),
values, null, null);
} else {
ContentValues values = new ContentValues();
values.put(PollList.DOCUMENT_ID, poll.getDocumentId());
values.put(PollList.TITLE, poll.getTitle());
getContentResolver().insert(PollList.CONTENT_URI, values);
}
} finally {
cursor.close();
}
}
/**
* Shares poll using ShareActivity
*/
private void sharePoll() {
Intent intent = new Intent(this, ShareActivity.class);
Uri url = Uri.parse(AppEngineHelper.BROKER_URL + "/poll/").buildUpon()
.appendPath(poll.getDocumentId()).build();
intent.putExtra(ShareActivity.EXTRA_URL, url.toString());
intent.putExtra(ShareActivity.EXTRA_POLL_NAME, poll.getTitle());
startActivity(intent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.test.AndroidTestCase;
import java.util.List;
/**
* Tests for the BootReceiver.
*
* @author Youtao Liu
*/
public class BootReceiverTest extends AndroidTestCase {
private static final String SERVICE_NAME = "com.google.android.apps.mytracks.services.TrackRecordingService";
/**
* Tests the behavior when receive notification which is the phone boot.
*/
public void testOnReceive_startService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BOOT_COMPLETED);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is started
assertTrue(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Tests the behavior when receive notification which is not the phone boot.
*/
public void testOnReceive_noStartService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BUG_REPORT);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is not started
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Checks if a service is started in a context.
*
* @param context the context for checking a service
* @param serviceName the service name to find if existed
*/
private boolean isServiceExisted(Context context, String serviceName) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(Integer.MAX_VALUE);
for (int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName componentName = serviceInfo.service;
if (componentName.getClassName().equals(serviceName)) {
return true;
}
}
return false;
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
/**
* Tests for the AntPreference.
*
* @author Youtao Liu
*/
public class AntPreferenceTest extends AndroidTestCase {
public void testNotPaired() {
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 0;
}
};
assertEquals(getContext().getString(R.string.settings_sensor_ant_not_paired),
antPreference.getSummary());
}
public void testPaired() {
int persistInt = 1;
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 1;
}
};
assertEquals(
getContext().getString(R.string.settings_sensor_ant_paired, persistInt),
antPreference.getSummary());
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.maps.SingleColorTrackPathPainter;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.graphics.Path;
import android.location.Location;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*/
public class MapOverlayTest extends AndroidTestCase {
private Canvas canvas;
private MockMyTracksOverlay myTracksOverlay;
private MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
// Set a TrackPathPainter with a MockPath.
myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) {
@Override
public Path newPath() {
return new MockPath();
}
});
mockView = null;
}
public void testAddLocation() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
location.setLatitude(20);
location.setLongitude(30);
myTracksOverlay.addLocation(location);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
// Draw and make sure that we don't lose any point.
myTracksOverlay.draw(canvas, mockView, false);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(2, path.totalPoints);
myTracksOverlay.draw(canvas, mockView, true);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearPoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
// Same after drawing on canvas.
final int locations = 100;
for (int i = 0; i < locations; ++i) {
myTracksOverlay.addLocation(location);
}
assertEquals(locations, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
}
public void testAddWaypoint() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
final int waypoints = 10;
for (int i = 0; i < waypoints; ++i) {
waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearWaypoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
myTracksOverlay.clearWaypoints();
assertEquals(0, myTracksOverlay.getNumWaypoints());
}
public void testDrawing() {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 40; ++i) {
location.setLongitude(20 + i);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
// Shadow.
myTracksOverlay.draw(canvas, mockView, true);
// We don't expect to do anything if
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
// No shadow.
myTracksOverlay.draw(canvas, mockView, false);
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
assertEquals(100, path.totalPoints);
// TODO: Check the points from the path (and the segments).
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Tests {@link DefaultTrackNameFactory}
*
* @author Matthew Simmons
*/
public class DefaultTrackNameFactoryTest extends AndroidTestCase {
private static final long TRACK_ID = 1L;
private static final long START_TIME = 1288213406000L;
public void testDefaultTrackName_date_local() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_local_value);
}
};
assertEquals(StringUtils.formatDateTime(getContext(), START_TIME),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_date_iso_8601() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_iso_8601_value);
}
};
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
DefaultTrackNameFactory.ISO_8601_FORMAT);
assertEquals(simpleDateFormat.format(new Date(START_TIME)),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_number() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_number_value);
}
};
assertEquals(
"Track " + TRACK_ID, defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import org.easymock.Capture;
/**
* Tests for {@link StatusAnnouncerTask}.
* WARNING: I'm not responsible if your eyes start bleeding while reading this
* code. You have been warned. It's still better than no test, though.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Use something other than our hardcoded value
private static final Locale DEFAULT_LOCALE = Locale.KOREAN;
private static final String ANNOUNCEMENT = "I can haz cheeseburger?";
private Locale oldDefaultLocale;
private StatusAnnouncerTask task;
private StatusAnnouncerTask mockTask;
private Capture<OnInitListener> initListenerCapture;
private Capture<PhoneStateListener> phoneListenerCapture;
private TextToSpeechDelegate ttsDelegate;
private TextToSpeechInterface tts;
/**
* Mockable interface that we delegate TTS calls to.
*/
interface TextToSpeechInterface {
int addEarcon(String earcon, String packagename, int resourceId);
int addEarcon(String earcon, String filename);
int addSpeech(String text, String packagename, int resourceId);
int addSpeech(String text, String filename);
boolean areDefaultsEnforced();
String getDefaultEngine();
Locale getLanguage();
int isLanguageAvailable(Locale loc);
boolean isSpeaking();
int playEarcon(String earcon, int queueMode,
HashMap<String, String> params);
int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params);
int setEngineByPackageName(String enginePackageName);
int setLanguage(Locale loc);
int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener);
int setPitch(float pitch);
int setSpeechRate(float speechRate);
void shutdown();
int speak(String text, int queueMode, HashMap<String, String> params);
int stop();
int synthesizeToFile(String text, HashMap<String, String> params,
String filename);
}
/**
* Subclass of {@link TextToSpeech} which delegates calls to the interface
* above.
* The logic here is stupid and the author is ashamed of having to write it
* like this, but basically the issue is that TextToSpeech cannot be mocked
* without running its constructor, its constructor runs async operations
* which call other methods (and then if the methods are part of a mock we'd
* have to set a behavior, but we can't 'cause the object hasn't been fully
* built yet).
* The logic is that calls made during the constructor (when tts is not yet
* set) will go up to the original class, but after tts is set we'll forward
* them all to the mock.
*/
private class TextToSpeechDelegate
extends TextToSpeech implements TextToSpeechInterface {
public TextToSpeechDelegate(Context context, OnInitListener listener) {
super(context, listener);
}
@Override
public int addEarcon(String earcon, String packagename, int resourceId) {
if (tts == null) {
return super.addEarcon(earcon, packagename, resourceId);
}
return tts.addEarcon(earcon, packagename, resourceId);
}
@Override
public int addEarcon(String earcon, String filename) {
if (tts == null) {
return super.addEarcon(earcon, filename);
}
return tts.addEarcon(earcon, filename);
}
@Override
public int addSpeech(String text, String packagename, int resourceId) {
if (tts == null) {
return super.addSpeech(text, packagename, resourceId);
}
return tts.addSpeech(text, packagename, resourceId);
}
@Override
public int addSpeech(String text, String filename) {
if (tts == null) {
return super.addSpeech(text, filename);
}
return tts.addSpeech(text, filename);
}
@Override
public Locale getLanguage() {
if (tts == null) {
return super.getLanguage();
}
return tts.getLanguage();
}
@Override
public int isLanguageAvailable(Locale loc) {
if (tts == null) {
return super.isLanguageAvailable(loc);
}
return tts.isLanguageAvailable(loc);
}
@Override
public boolean isSpeaking() {
if (tts == null) {
return super.isSpeaking();
}
return tts.isSpeaking();
}
@Override
public int playEarcon(String earcon, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playEarcon(earcon, queueMode, params);
}
return tts.playEarcon(earcon, queueMode, params);
}
@Override
public int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playSilence(durationInMs, queueMode, params);
}
return tts.playSilence(durationInMs, queueMode, params);
}
@Override
public int setLanguage(Locale loc) {
if (tts == null) {
return super.setLanguage(loc);
}
return tts.setLanguage(loc);
}
@Override
public int setOnUtteranceCompletedListener(
OnUtteranceCompletedListener listener) {
if (tts == null) {
return super.setOnUtteranceCompletedListener(listener);
}
return tts.setOnUtteranceCompletedListener(listener);
}
@Override
public int setPitch(float pitch) {
if (tts == null) {
return super.setPitch(pitch);
}
return tts.setPitch(pitch);
}
@Override
public int setSpeechRate(float speechRate) {
if (tts == null) {
return super.setSpeechRate(speechRate);
}
return tts.setSpeechRate(speechRate);
}
@Override
public void shutdown() {
if (tts == null) {
super.shutdown();
return;
}
tts.shutdown();
}
@Override
public int speak(
String text, int queueMode, HashMap<String, String> params) {
if (tts == null) {
return super.speak(text, queueMode, params);
}
return tts.speak(text, queueMode, params);
}
@Override
public int stop() {
if (tts == null) {
return super.stop();
}
return tts.stop();
}
@Override
public int synthesizeToFile(String text, HashMap<String, String> params,
String filename) {
if (tts == null) {
return super.synthesizeToFile(text, params, filename);
}
return tts.synthesizeToFile(text, params, filename);
}
}
@UsesMocks({
StatusAnnouncerTask.class,
StringUtils.class,
})
@Override
protected void setUp() throws Exception {
super.setUp();
oldDefaultLocale = Locale.getDefault();
Locale.setDefault(DEFAULT_LOCALE);
// Eww, the effort required just to mock TextToSpeech is insane
final AtomicBoolean listenerCalled = new AtomicBoolean();
OnInitListener blockingListener = new OnInitListener() {
@Override
public void onInit(int status) {
synchronized (this) {
listenerCalled.set(true);
notify();
}
}
};
ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener);
// Wait for all async operations done in the constructor to finish.
synchronized (blockingListener) {
while (!listenerCalled.get()) {
// Releases the synchronized lock until we're woken up.
blockingListener.wait();
}
}
// Phew, done, now we can start forwarding calls
tts = AndroidMock.createMock(TextToSpeechInterface.class);
initListenerCapture = new Capture<OnInitListener>();
phoneListenerCapture = new Capture<PhoneStateListener>();
// Create a partial forwarding mock
mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext());
task = new StatusAnnouncerTask(getContext()) {
@Override
protected TextToSpeech newTextToSpeech(Context ctx,
OnInitListener onInitListener) {
return mockTask.newTextToSpeech(ctx, onInitListener);
}
@Override
protected String getAnnouncement(TripStatistics stats) {
return mockTask.getAnnouncement(stats);
}
@Override
protected void listenToPhoneState(
PhoneStateListener listener, int events) {
mockTask.listenToPhoneState(listener, events);
}
};
}
@Override
protected void tearDown() {
Locale.setDefault(oldDefaultLocale);
}
public void testStart() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setLanguage(DEFAULT_LOCALE))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_languageNotSupported() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED);
expect(tts.setLanguage(Locale.ENGLISH))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_notReady() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.ERROR);
AndroidMock.verify(mockTask, tts);
}
public void testShutdown() {
// First, start
doStart();
AndroidMock.verify(mockTask);
AndroidMock.reset(mockTask);
// Then, shut down
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
mockTask.listenToPhoneState(
same(phoneListener), eq(PhoneStateListener.LISTEN_NONE));
tts.shutdown();
AndroidMock.replay(mockTask, tts);
task.shutdown();
AndroidMock.verify(mockTask, tts);
}
public void testRun() throws Exception {
// Expect service data calls
TripStatistics stats = new TripStatistics();
// Expect announcement building call
expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT);
// Put task in "ready" state
startTask(TextToSpeech.SUCCESS);
// Expect actual announcement call
expect(tts.speak(
eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH),
AndroidMock.<HashMap<String, String>>isNull()))
.andReturn(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(stats);
AndroidMock.verify(mockTask, tts);
}
public void testRun_notReady() throws Exception {
// Put task in "not ready" state
startTask(TextToSpeech.ERROR);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_duringCall() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_ringWhileSpeaking() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(true);
expect(tts.stop()).andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
// Update the state to ringing - this should stop the current announcement.
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
// Run the announcement - this should do nothing.
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_whileRinging() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noService() throws Exception {
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noStats() throws Exception {
// Expect service data calls
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero.
*/
public void testGetAnnounceTime_time_zero() {
long time = 0; // 0 seconds
assertEquals("0 minutes 0 seconds", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one.
*/
public void testGetAnnounceTime_time_one() {
long time = 1 * 1000; // 1 second
assertEquals("0 minutes 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers with the hour unit.
*/
public void testGetAnnounceTime_singular_has_hour() {
long time = (1 * 60 * 60 * 1000) + (1 * 60 * 1000) + (1 * 1000); // 1 hour 1 minute 1 second
assertEquals("1 hour 1 minute", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* with the hour unit.
*/
public void testGetAnnounceTime_plural_has_hour() {
long time = (2 * 60 * 60 * 1000) + (2 * 60 * 1000) + (2 * 1000); // 2 hours 2 minutes 2 seconds
assertEquals("2 hours 2 minutes", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers without the hour unit.
*/
public void testGetAnnounceTime_singular_no_hour() {
long time = (1 * 60 * 1000) + (1 * 1000); // 1 minute 1 second
assertEquals("1 minute 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* without the hour unit.
*/
public void testGetAnnounceTime_plural_no_hour() {
long time = (2 * 60 * 1000) + (2 * 1000); // 2 minutes 2 seconds
assertEquals("2 minutes 2 seconds", task.getAnnounceTime(time));
}
private void startTask(int state) {
AndroidMock.resetToNice(tts);
AndroidMock.replay(tts);
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
ttsInitListener.onInit(state);
AndroidMock.resetToDefault(tts);
}
private void doStart() {
mockTask.listenToPhoneState(capture(phoneListenerCapture),
eq(PhoneStateListener.LISTEN_CALL_STATE));
expect(mockTask.newTextToSpeech(
same(getContext()), capture(initListenerCapture)))
.andStubReturn(ttsDelegate);
AndroidMock.replay(mockTask);
task.start();
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import android.test.AndroidTestCase;
/**
* Tests for {@link StatusAnnouncerFactory}.
* These tests require Donut+ to run.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerFactoryTest extends AndroidTestCase {
public void testCreate() {
PeriodicTaskFactory factory = new StatusAnnouncerFactory();
PeriodicTask task = factory.create(getContext());
assertTrue(task instanceof StatusAnnouncerTask);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProvider;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.IBinder;
import android.test.RenamingDelegatingContext;
import android.test.ServiceTestCase;
import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for the MyTracks track recording service.
*
* @author Bartlomiej Niechwiej
*
* TODO: The original class, ServiceTestCase, has a few limitations, e.g.
* it's not possible to properly shutdown the service, unless tearDown()
* is called, which prevents from testing multiple scenarios in a single
* test (see runFunctionTest for more details).
*/
public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingService> {
private Context context;
private MyTracksProviderUtils providerUtils;
private SharedPreferences sharedPreferences;
/*
* In order to support starting and binding to the service in the same
* unit test, we provide a workaround, as the original class doesn't allow
* to bind after the service has been previously started.
*/
private boolean bound;
private Intent serviceIntent;
public TrackRecordingServiceTest() {
super(TestRecordingService.class);
}
/**
* A context wrapper with the user provided {@link ContentResolver}.
*
* TODO: Move to test utils package.
*/
public static class MockContext extends ContextWrapper {
private final ContentResolver contentResolver;
public MockContext(ContentResolver contentResolver, Context base) {
super(base);
this.contentResolver = contentResolver;
}
@Override
public ContentResolver getContentResolver() {
return contentResolver;
}
}
@Override
protected IBinder bindService(Intent intent) {
if (getService() != null) {
if (bound) {
throw new IllegalStateException(
"Service: " + getService() + " is already bound");
}
bound = true;
serviceIntent = intent.cloneFilter();
return getService().onBind(intent);
} else {
return super.bindService(intent);
}
}
@Override
protected void shutdownService() {
if (bound) {
assertNotNull(getService());
getService().onUnbind(serviceIntent);
bound = false;
}
super.shutdownService();
}
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
// Disable auto resume by default.
updateAutoResumePrefs(0, -1);
// No recording track.
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), -1);
editor.apply();
}
@SmallTest
public void testStartable() {
startService(createStartIntent());
assertNotNull(getService());
}
@MediumTest
public void testBindable() {
IBinder service = bindService(createStartIntent());
assertNotNull(service);
}
@MediumTest
public void testResumeAfterReboot_shouldResume() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We expect to resume the previous track.
assertTrue(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(123, service.getRecordingTrackId());
}
// TODO: shutdownService() has a bug and doesn't set mServiceCreated
// to false, thus preventing from a second call to onCreate().
// Report the bug to Android team. Until then, the following tests
// and checks must be commented out.
//
// TODO: If fixed, remove "disabled" prefix from the test name.
@MediumTest
public void disabledTestResumeAfterReboot_simulateReboot() throws Exception {
updateAutoResumePrefs(0, 10);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Simulate recording a track.
long id = service.startNewTrack();
assertTrue(service.isRecording());
assertEquals(id, service.getRecordingTrackId());
shutdownService();
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
assertTrue(getService().isRecording());
}
@MediumTest
public void testResumeAfterReboot_noRecordingTrack() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), false);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it was stopped.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_expiredTrack() throws Exception {
// Insert a dummy track last updated 20 min ago.
createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it has expired.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_tooManyAttempts() throws Exception {
// Insert a dummy track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Set the number of attempts to max.
updateAutoResumePrefs(
TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because there were already
// too many attempts.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_noTracks() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
// Test if we start in no-recording mode by default.
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_oldTracks() throws Exception {
createDummyTrack(123, -1, false);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_orphanedRecordingTrack() throws Exception {
// Just set recording track to a bogus value.
setRecordingTrack(256);
// Make sure that the service will not start recording and will clear
// the bogus track.
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
/**
* Synchronous/waitable broadcast receiver to be used in testing.
*/
private class BlockingBroadcastReceiver extends BroadcastReceiver {
private static final long MAX_WAIT_TIME_MS = 10000;
private List<Intent> receivedIntents = new ArrayList<Intent>();
public List<Intent> getReceivedIntents() {
return receivedIntents;
}
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("MyTracksTest", "Got broadcast: " + intent);
synchronized (receivedIntents) {
receivedIntents.add(intent);
receivedIntents.notifyAll();
}
}
public boolean waitUntilReceived(int receiveCount) {
long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS;
synchronized (receivedIntents) {
while (receivedIntents.size() < receiveCount) {
try {
// Wait releases synchronized lock until it returns
receivedIntents.wait(500);
} catch (InterruptedException e) {
// Do nothing
}
if (System.currentTimeMillis() > deadline) {
return false;
}
}
}
return true;
}
}
@MediumTest
public void testStartNewTrack_noRecording() throws Exception {
// NOTICE: due to the way Android permissions work, if this fails,
// uninstall the test apk then retry - the test must be installed *after*
// My Tracks (go figure).
// Reference: http://code.google.com/p/android/issues/detail?id=5521
BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver();
String startAction = context.getString(R.string.track_started_broadcast_action);
context.registerReceiver(startReceiver, new IntentFilter(startAction));
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""),
track.getCategory());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Verify that the start broadcast was received.
assertTrue(startReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = startReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(startAction, broadcastIntent.getAction());
assertEquals(id, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(startReceiver);
}
@MediumTest
public void testStartNewTrack_alreadyRecording() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// Starting a new track when there is a recording should just return -1L.
long newTrack = service.startNewTrack();
assertEquals(-1L, newTrack);
assertEquals(123, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(123, service.getRecordingTrackId());
}
@MediumTest
public void testEndCurrentTrack_alreadyRecording() throws Exception {
// See comment above if this fails randomly.
BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver();
String stopAction = context.getString(R.string.track_stopped_broadcast_action);
context.registerReceiver(stopReceiver, new IntentFilter(stopAction));
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// End the current track.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
// Verify that the stop broadcast was received.
assertTrue(stopReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = stopReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(stopAction, broadcastIntent.getAction());
assertEquals(123, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(stopReceiver);
}
@MediumTest
public void testEndCurrentTrack_noRecording() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Ending the current track when there is no recording should not result in any error.
service.endCurrentTrack();
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testIntegration_completeRecordingSession() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
fullRecordingSession();
}
@MediumTest
public void testInsertStatisticsMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertStatisticsMarker_validLocation() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_statistics_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_statistics),
wpt.getName());
assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNotNull(wpt.getStatistics());
// TODO check the rest of the params.
// TODO: Check waypoint 2.
}
@MediumTest
public void testInsertWaypointMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertWaypointMarker_validWaypoint() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_waypoint_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_waypoint),
wpt.getName());
assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNull(wpt.getStatistics());
}
@MediumTest
public void testWithProperties_noAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, 1);
}
@MediumTest
public void testWithProperties_noMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, 5);
}
@MediumTest
public void testWithProperties_noMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, 2);
}
@MediumTest
public void testWithProperties_noSplitFreq() throws Exception {
functionalTest(R.string.split_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByDist() throws Exception {
functionalTest(R.string.split_frequency_key, 5);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByTime() throws Exception {
functionalTest(R.string.split_frequency_key, -2);
}
@MediumTest
public void testWithProperties_noMetricUnits() throws Exception {
functionalTest(R.string.metric_units_key, (Object) null);
}
@MediumTest
public void testWithProperties_metricUnitsEnabled() throws Exception {
functionalTest(R.string.metric_units_key, true);
}
@MediumTest
public void testWithProperties_metricUnitsDisabled() throws Exception {
functionalTest(R.string.metric_units_key, false);
}
@MediumTest
public void testWithProperties_noMinRecordingInterval() throws Exception {
functionalTest(R.string.min_recording_interval_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingInterval()
throws Exception {
functionalTest(R.string.min_recording_interval_key, 3);
}
@MediumTest
public void testWithProperties_noMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, 500);
}
@MediumTest
public void testWithProperties_noSensorType() throws Exception {
functionalTest(R.string.sensor_type_key, (Object) null);
}
@MediumTest
public void testWithProperties_zephyrSensorType() throws Exception {
functionalTest(R.string.sensor_type_key,
context.getString(R.string.sensor_type_value_zephyr));
}
private ITrackRecordingService bindAndGetService(Intent intent) {
ITrackRecordingService service = ITrackRecordingService.Stub.asInterface(
bindService(intent));
assertNotNull(service);
return service;
}
private Track createDummyTrack(long id, long stopTime, boolean isRecording) {
Track dummyTrack = new Track();
dummyTrack.setId(id);
dummyTrack.setName("Dummy Track");
TripStatistics tripStatistics = new TripStatistics();
tripStatistics.setStopTime(stopTime);
dummyTrack.setStatistics(tripStatistics);
addTrack(dummyTrack, isRecording);
return dummyTrack;
}
private void updateAutoResumePrefs(int attempts, int timeoutMins) {
Editor editor = sharedPreferences.edit();
editor.putInt(context.getString(
R.string.auto_resume_track_current_retry_key), attempts);
editor.putInt(context.getString(
R.string.auto_resume_track_timeout_key), timeoutMins);
editor.apply();
}
private Intent createStartIntent() {
Intent startIntent = new Intent();
startIntent.setClass(context, TrackRecordingService.class);
return startIntent;
}
private void addTrack(Track track, boolean isRecording) {
assertTrue(track.getId() >= 0);
providerUtils.insertTrack(track);
assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId());
setRecordingTrack(isRecording ? track.getId() : -1);
}
private void setRecordingTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), id);
editor.apply();
}
// TODO: We support multiple values for readability, however this test's
// base class doesn't properly shutdown the service, so it's not possible
// to pass more than 1 value at a time.
private void functionalTest(int resourceId, Object ...values)
throws Exception {
final String key = context.getString(resourceId);
for (Object value : values) {
// Remove all properties and set the property for the given key.
Editor editor = sharedPreferences.edit();
editor.clear();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value == null) {
// Do nothing, as clear above has already removed this property.
}
editor.apply();
fullRecordingSession();
}
}
private void fullRecordingSession() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Start a track.
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Insert a few points, markers and statistics.
long startTime = System.currentTimeMillis();
for (int i = 0; i < 30; i++) {
Location loc = new Location("gps");
loc.setLongitude(35.0f + i / 10.0f);
loc.setLatitude(45.0f - i / 5.0f);
loc.setAccuracy(5);
loc.setSpeed(10);
loc.setTime(startTime + i * 10000);
loc.setBearing(3.0f);
service.recordLocation(loc);
if (i % 10 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
} else if (i % 7 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
}
}
// Stop the track. Validate if it has correct data.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
TripStatistics tripStatistics = track.getStatistics();
assertNotNull(tripStatistics);
assertTrue(tripStatistics.getStartTime() > 0);
assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.testing.mocking.AndroidMock.expect;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.test.AndroidTestCase;
import java.io.File;
/**
* Tests {@link RemoveTempFilesService}.
*
* @author Sandor Dornbush
*/
public class RemoveTempFilesServiceTest extends AndroidTestCase {
private static final String DIR_NAME = "/tmp";
private static final String FILE_NAME = "foo";
private RemoveTempFilesService service;
@UsesMocks({ File.class, })
protected void setUp() throws Exception {
service = new RemoveTempFilesService();
};
/**
* Tests when the directory doesn't exists.
*/
public void test_noDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(false);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when the directory is empty.
*/
public void test_emptyDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[0]);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when there is a new file and it shouldn't get deleted.
*/
public void test_newFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
expect(file.lastModified()).andStubReturn(System.currentTimeMillis());
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
/**
* Tests when there is an old file and it should get deleted.
*/
public void test_oldFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
// qSet to one hour and 1 millisecond later than the current time
expect(file.lastModified()).andStubReturn(System.currentTimeMillis() - 3600001);
expect(file.delete()).andStubReturn(true);
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(1, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager;
import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class SensorManagerFactoryTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
@Override
protected void setUp() throws Exception {
super.setUp();
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
}
@SmallTest
public void testDefaultSettings() throws Exception {
assertNull(SensorManagerFactory.getInstance().getSensorManager(getContext()));
}
@SmallTest
public void testCreateZephyr() throws Exception {
assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr);
}
@SmallTest
public void testCreateAnt() throws Exception {
assertClassForName(AntDirectSensorManager.class, R.string.sensor_type_value_ant);
}
@SmallTest
public void testCreateAntSRM() throws Exception {
assertClassForName(AntSrmBridgeSensorManager.class, R.string.sensor_type_value_srm_ant_bridge);
}
private void assertClassForName(Class<?> c, int i) {
sharedPreferences.edit()
.putString(getContext().getString(R.string.sensor_type_key),
getContext().getString(i))
.apply();
SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext());
assertNotNull(sm);
assertTrue(c.isInstance(sm));
SensorManagerFactory.getInstance().releaseSensorManager(sm);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntStartupMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0x12,
};
AntStartupMessage message = new AntStartupMessage(rawMessage);
assertEquals(0x12, message.getMessage());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntDefine;
import com.dsi.ant.AntMesg;
import android.test.AndroidTestCase;
public class AntChannelResponseMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0,
AntMesg.MESG_EVENT_ID,
AntDefine.EVENT_RX_SEARCH_TIMEOUT
};
AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId());
assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Laszlo Molnar
*/
public class SensorEventCounterTest extends AndroidTestCase {
@SmallTest
public void testGetEventsPerMinute() {
SensorEventCounter sec = new SensorEventCounter();
assertEquals(0, sec.getEventsPerMinute(0, 0, 0));
assertEquals(0, sec.getEventsPerMinute(1, 1024, 1000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2500));
assertTrue(60 > sec.getEventsPerMinute(2, 1024 * 2, 4000));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntChannelIdMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0, // channel number
0x34, 0x12, // device number
(byte) 0xaa, // device type id
(byte) 0xbb, // transmission type
};
AntChannelIdMessage message = new AntChannelIdMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(0x1234, message.getDeviceNumber());
assertEquals((byte) 0xaa, message.getDeviceTypeId());
assertEquals((byte) 0xbb, message.getTransmissionType());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntMessageTest extends AndroidTestCase {
private static class TestAntMessage extends AntMessage {
public static short decodeShort(byte low, byte high) {
return AntMessage.decodeShort(low, high);
}
}
public void testDecode() {
assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.content.Context;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
public class AntSensorManagerTest extends AndroidTestCase {
private class TestAntSensorManager extends AntSensorManager {
public TestAntSensorManager(Context context) {
super(context);
}
public byte messageId;
public byte[] messageData;
@Override
protected void setupAntSensorChannels() {}
@SuppressWarnings("deprecation")
@Override
public void handleMessage(byte[] rawMessage) {
super.handleMessage(rawMessage);
}
@SuppressWarnings("hiding")
@Override
public boolean handleMessage(byte messageId, byte[] messageData) {
this.messageId = messageId;
this.messageData = messageData;
return true;
}
}
private TestAntSensorManager sensorManager;
@Override
protected void setUp() throws Exception {
super.setUp();
sensorManager = new TestAntSensorManager(getContext());
}
public void testSimple() {
byte[] rawMessage = {
0x03, // length
0x12, // message id
0x11, 0x22, 0x33, // body
};
byte[] expectedBody = { 0x11, 0x22, 0x33 };
sensorManager.handleMessage(rawMessage);
assertEquals((byte) 0x12, sensorManager.messageId);
MoreAsserts.assertEquals(expectedBody, sensorManager.messageData);
}
public void testTooShort() {
byte[] rawMessage = {
0x53, // length
0x12 // message id
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
public void testLengthWrong() {
byte[] rawMessage = {
0x53, // length
0x12, // message id
0x34, // body
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntMesg;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class AntDirectSensorManagerTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
private AntSensorBase heartRateSensor;
private static final byte HEART_RATE_CHANNEL = 0;
private class MockAntDirectSensorManager extends AntDirectSensorManager {
public MockAntDirectSensorManager(Context context) {
super(context);
}
@Override
protected boolean setupChannel(AntSensorBase sensor, byte channel) {
if (channel == HEART_RATE_CHANNEL) {
heartRateSensor = sensor;
return true;
}
return false;
}
}
private AntDirectSensorManager manager;
public void setUp() {
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
manager = new MockAntDirectSensorManager(getContext());
}
@SmallTest
public void testBroadcastData() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
heartRateSensor.setDeviceNumber((short) 42);
byte[] buff = new byte[9];
buff[0] = HEART_RATE_CHANNEL;
buff[8] = (byte) 220;
manager.handleMessage(AntMesg.MESG_BROADCAST_DATA_ID, buff);
Sensor.SensorDataSet sds = manager.getSensorDataSet();
assertNotNull(sds);
assertTrue(sds.hasHeartRate());
assertEquals(Sensor.SensorState.SENDING,
sds.getHeartRate().getState());
assertEquals(220, sds.getHeartRate().getValue());
assertFalse(sds.hasCadence());
assertFalse(sds.hasPower());
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
}
@SmallTest
public void testChannelId() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
byte[] buff = new byte[9];
buff[1] = 43;
manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff);
assertEquals(43, heartRateSensor.getDeviceNumber());
assertEquals(43,
sharedPreferences.getInt(
getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1));
assertNull(manager.getSensorDataSet());
}
@SmallTest
public void testResponseEvent() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
manager.setHeartRate(210);
heartRateSensor.setDeviceNumber((short) 42);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
byte[] buff = new byte[3];
buff[0] = HEART_RATE_CHANNEL;
buff[1] = AntMesg.MESG_UNASSIGN_CHANNEL_ID;
buff[2] = 0; // code
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
heartRateSensor.setDeviceNumber((short) 0);
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState());
}
// TODO: Test timeout too.
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import java.util.Arrays;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class PolarMessageParserTest extends TestCase {
PolarMessageParser parser = new PolarMessageParser();
// A complete and valid Polar HxM packet
// FE08F701D1001104FE08F702D1001104
private final byte[] originalBuf =
{(byte) 0xFE, 0x08, (byte) 0xF7, 0x01, (byte) 0xD1, 0x00, 0x11, 0x04, (byte) 0xFE, 0x08,
(byte) 0xF7, 0x02, (byte) 0xD1, 0x00, 0x11, 0x04};
private byte[] buf;
public void setUp() {
buf = Arrays.copyOf(originalBuf, originalBuf.length);
}
public void testIsValid() {
assertTrue(parser.isValid(buf));
}
public void testIsValid_invalidHeader() {
// Invalidate header.
buf[0] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidCheckbyte() {
// Invalidate checkbyte.
buf[2] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidSequence() {
// Invalidate sequence.
buf[3] = 0x11;
assertFalse(parser.isValid(buf));
}
public void testParseBuffer() {
buf[5] = 70;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(70, sds.getHeartRate().getValue());
}
public void testFindNextAlignment_offset() {
// The first 4 bytes are garbage
buf = new byte[originalBuf.length + 4];
buf[0] = 4;
buf[1] = 2;
buf[2] = 4;
buf[3] = 2;
// Then the valid message.
System.arraycopy(originalBuf, 0, buf, 4, originalBuf.length);
assertEquals(4, parser.findNextAlignment(buf));
}
public void testFindNextAlignment_invalid() {
buf[0] = 0;
assertEquals(-1, parser.findNextAlignment(buf));
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class ZephyrMessageParserTest extends TestCase {
ZephyrMessageParser parser = new ZephyrMessageParser();
public void testIsValid() {
byte[] smallBuf = new byte[59];
assertFalse(parser.isValid(smallBuf));
// A complete and valid Zephyr HxM packet
byte[] buf = { 2,38,55,26,0,49,101,80,0,49,98,100,42,113,120,-53,-24,-60,-123,-61,117,-69,42,-75,74,-78,51,-79,27,-83,28,-88,28,-93,29,-98,25,-103,26,-108,26,-113,59,-118,0,0,0,0,0,0,-22,3,125,1,48,0,96,4,30,0 };
// Make buffer invalid
buf[0] = buf[58] = buf[59] = 0;
assertFalse(parser.isValid(buf));
buf[0] = 0x02;
assertFalse(parser.isValid(buf));
buf[58] = 0x1E;
assertFalse(parser.isValid(buf));
buf[59] = 0x03;
assertTrue(parser.isValid(buf));
}
public void testParseBuffer() {
byte[] buf = new byte[60];
// Heart Rate (-1 =^ 255 unsigned byte)
buf[12] = -1;
// Battery Level
buf[11] = 51;
// Cadence (=^ 255*16 strides/min)
buf[56] = -1;
buf[57] = 15;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getHeartRate().getValue());
assertTrue(sds.hasBatteryLevel());
assertTrue(sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING);
assertEquals(51, sds.getBatteryLevel().getValue());
assertTrue(sds.hasCadence());
assertTrue(sds.getCadence().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getCadence().getValue());
}
public void testFindNextAlignment() {
byte[] buf = new byte[60];
assertEquals(-1, parser.findNextAlignment(buf));
buf[10] = 0x03;
buf[11] = 0x02;
assertEquals(10, parser.findNextAlignment(buf));
}
}
| Java |
// Copyright 2012 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.services;
import android.app.Notification;
import android.app.Service;
import android.test.ServiceTestCase;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* A {@link TrackRecordingService} that can be used with {@link ServiceTestCase}.
* {@link ServiceTestCase} throws a null pointer exception when the service
* calls {@link Service#startForeground(int, android.app.Notification)} and
* {@link Service#stopForeground(boolean)}.
* <p>
* See http://code.google.com/p/android/issues/detail?id=12122
* <p>
* Wrap these two methods in wrappers and override them.
*
* @author Jimmy Shih
*/
public class TestRecordingService extends TrackRecordingService {
private static final String TAG = TestRecordingService.class.getSimpleName();
@Override
protected void startForegroundService(Notification notification) {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, true);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
@Override
protected void stopForegroundService() {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, false);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import android.util.Pair;
/**
* Tests for {@link DescriptionGeneratorImpl}.
*
* @author Jimmy Shih
*/
public class DescriptionGeneratorImplTest extends AndroidTestCase {
private DescriptionGeneratorImpl descriptionGenerator;
@Override
protected void setUp() throws Exception {
descriptionGenerator = new DescriptionGeneratorImpl(getContext());
}
/**
* Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track,
* java.util.Vector, java.util.Vector)}.
*/
public void testGenerateTrackDescription() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(1288721514000L);
track.setStatistics(stats);
track.setCategory("hiking");
String expected = "Created by"
+ " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>"
+ "Total distance: 20.00 km (12.4 mi)<br>"
+ "Total time: 10:00<br>"
+ "Moving time: 05:00<br>"
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
+ "Min pace: 0.17 min/km (0.3 min/mi)<br>"
+ "Max elevation: 550 m (1804 ft)<br>"
+ "Min elevation: -500 m (-1640 ft)<br>"
+ "Elevation gain: 6000 m (19685 ft)<br>"
+ "Max grade: 42 %<br>"
+ "Min grade: 11 %<br>"
+ "Recorded: 11/2/2010 11:11 AM<br>"
+ "Activity type: hiking<br>";
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null));
}
/**
* Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(Waypoint)}.
*/
public void testGenerateWaypointDescription() {
Waypoint waypoint = new Waypoint();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(1288721514000L);
waypoint.setStatistics(stats);
String expected = "Total distance: 20.00 km (12.4 mi)\n"
+ "Total time: 10:00\n"
+ "Moving time: 05:00\n"
+ "Average speed: 120.00 km/h (74.6 mi/h)\n"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)\n"
+ "Max speed: 360.00 km/h (223.7 mi/h)\n"
+ "Average pace: 0.50 min/km (0.8 min/mi)\n"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)\n"
+ "Min pace: 0.17 min/km (0.3 min/mi)\n"
+ "Max elevation: 550 m (1804 ft)\n"
+ "Min elevation: -500 m (-1640 ft)\n"
+ "Elevation gain: 6000 m (19685 ft)\n"
+ "Max grade: 42 %\n"
+ "Min grade: 11 %\n"
+ "Recorded: 11/2/2010 11:11 AM\n";
assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint));
}
/**
* Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder,
* int, String)}.
*/
public void testWriteDistance() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "<br>");
assertEquals("Total distance: 1.10 km (0.7 mi)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int,
* String)}.
*/
public void testWriteTime() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "<br>");
assertEquals("Total time: 00:01<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder,
* int, String)}.
*/
public void testWriteSpeed() {
StringBuilder builder = new StringBuilder();
Pair<Double, Double> speed = descriptionGenerator.writeSpeed(
1.1, builder, R.string.description_average_speed, "\n");
assertEquals(3.96, speed.first);
assertEquals(3.96 * UnitConversions.KM_TO_MI, speed.second);
assertEquals("Average speed: 3.96 km/h (2.5 mi/h)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder,
* int, String)}.
*/
public void testWriteElevation() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "<br>");
assertEquals("Min elevation: 4 m (14 ft)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writePace(Pair, StringBuilder, int,
* String)}.
*/
public void testWritePace() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writePace(
new Pair<Double, Double>(1.1, 2.2), builder, R.string.description_average_pace, "\n");
assertEquals("Average pace: 54.55 min/km (27.3 min/mi)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)}.
*/
public void testWriteGrade() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 4 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with a NaN.
*/
public void testWriteGrade_nan() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with an infinite number.
*/
public void testWriteGrade_infinite() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(
Double.POSITIVE_INFINITY, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)}.
*/
public void testGetPace() {
assertEquals(12.0, descriptionGenerator.getPace(5));
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)} with zero speed.
*/
public void testGetPace_zero() {
assertEquals(0.0, descriptionGenerator.getPace(0));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType;
import android.os.Parcel;
import android.test.AndroidTestCase;
/**
* Tests for the WaypointCreationRequest class.
* {@link WaypointCreationRequest}
*
* @author Sandor Dornbush
*/
public class WaypointCreationRequestTest extends AndroidTestCase {
public void testTypeParceling() {
WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER;
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertNull(copy.getName());
assertNull(copy.getDescription());
assertNull(copy.getIconUrl());
}
public void testAllAttributesParceling() {
WaypointCreationRequest original =
new WaypointCreationRequest(WaypointType.MARKER, "name", "description", "img.png");
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertEquals("name", copy.getName());
assertEquals("description", copy.getDescription());
assertEquals("img.png", copy.getIconUrl());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import android.content.Context;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A unit test for {@link MyTracksProviderUtilsImpl}.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
private Context context;
private MyTracksProviderUtils providerUtils;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
}
public void testLocationIterator_noPoints() {
testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_customFactory() {
final Location location = new Location("test_location");
final AtomicInteger counter = new AtomicInteger();
testIterator(1, 15, 4, false, new LocationFactory() {
@Override
public Location createLocation() {
counter.incrementAndGet();
return location;
}
});
// Make sure we were called exactly as many times as we had track points.
assertEquals(15, counter.get());
}
public void testLocationIterator_nullFactory() {
try {
testIterator(1, 15, 4, false, null);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected.
}
}
public void testLocationIterator_noBatchAscending() {
testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_noBatchDescending() {
testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchAscending() {
testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchDescending() {
testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_largeTrack() {
testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
private List<Location> testIterator(long trackId, int numPoints, int batchSize,
boolean descending, LocationFactory locationFactory) {
long lastPointId = initializeTrack(trackId, numPoints);
((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize);
List<Location> locations = new ArrayList<Location>(numPoints);
LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory);
try {
while (it.hasNext()) {
Location loc = it.next();
assertNotNull(loc);
locations.add(loc);
// Make sure the IDs are returned in the right order.
assertEquals(descending ? lastPointId - locations.size() + 1
: lastPointId - numPoints + locations.size(), it.getLocationId());
}
assertEquals(numPoints, locations.size());
} finally {
it.close();
}
return locations;
}
private long initializeTrack(long id, int numPoints) {
Track track = new Track();
track.setId(id);
track.setName("Test: " + id);
track.setNumberOfPoints(numPoints);
providerUtils.insertTrack(track);
track = providerUtils.getTrack(id);
assertNotNull(track);
Location[] locations = new Location[numPoints];
for (int i = 0; i < numPoints; ++i) {
Location loc = new Location("test");
loc.setLatitude(37.0 + (double) i / 10000.0);
loc.setLongitude(57.0 - (double) i / 10000.0);
loc.setAccuracy((float) i / 100.0f);
loc.setAltitude(i * 2.5);
locations[i] = loc;
}
providerUtils.bulkInsertTrackPoints(locations, numPoints, id);
// Load all inserted locations.
long lastPointId = -1;
int counter = 0;
LocationIterator it = providerUtils.getLocationIterator(id, -1, false,
MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
try {
while (it.hasNext()) {
it.next();
lastPointId = it.getLocationId();
counter++;
}
} finally {
it.close();
}
assertTrue(numPoints == 0 || lastPointId > 0);
assertEquals(numPoints, track.getNumberOfPoints());
assertEquals(numPoints, counter);
return lastPointId;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.SearchEngine.ScoredResult;
import com.google.android.apps.mytracks.content.SearchEngine.SearchQuery;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.content.ContentUris;
import android.location.Location;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Tests for {@link SearchEngine}.
* These are not meant to be quality tests, but instead feature-by-feature tests
* (in other words, they don't test the mixing of different score boostings, just
* each boosting separately)
*
* @author Rodrigo Damazio
*/
public class SearchEngineTest extends AndroidTestCase {
private static final Location HERE = new Location("gps");
private static final long NOW = 1234567890000L; // After OLDEST_ALLOWED_TIMESTAMP
private MyTracksProviderUtils providerUtils;
private SearchEngine engine;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
MockContext context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
engine = new SearchEngine(providerUtils);
}
@Override
protected void tearDown() throws Exception {
providerUtils.deleteAllTracks();
super.tearDown();
}
private long insertTrack(String title, String description, String category, double distance, long hoursAgo) {
Track track = new Track();
track.setName(title);
track.setDescription(description);
track.setCategory(category);
TripStatistics stats = track.getStatistics();
if (hoursAgo > 0) {
// Started twice hoursAgo, so the average time is hoursAgo.
stats.setStartTime(NOW - hoursAgo * 1000L * 60L * 60L * 2);
stats.setStopTime(NOW);
}
int latitude = (int) ((HERE.getLatitude() + distance) * 1E6);
int longitude = (int) ((HERE.getLongitude() + distance) * 1E6);
stats.setBounds(latitude, longitude, latitude, longitude);
Uri uri = providerUtils.insertTrack(track);
return ContentUris.parseId(uri);
}
private long insertTrack(String title, String description, String category) {
return insertTrack(title, description, category, 0, -1);
}
private long insertTrack(String title, double distance) {
return insertTrack(title, "", "", distance, -1);
}
private long insertTrack(String title, long hoursAgo) {
return insertTrack(title, "", "", 0.0, hoursAgo);
}
private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) {
Waypoint waypoint = new Waypoint();
waypoint.setName(title);
waypoint.setDescription(description);
waypoint.setCategory(category);
waypoint.setTrackId(trackId);
Location location = new Location(HERE);
location.setLatitude(location.getLatitude() + distance);
location.setLongitude(location.getLongitude() + distance);
if (hoursAgo >= 0) {
location.setTime(NOW - hoursAgo * 1000L * 60L * 60L);
}
waypoint.setLocation(location);
Uri uri = providerUtils.insertWaypoint(waypoint);
return ContentUris.parseId(uri);
}
private long insertWaypoint(String title, String description, String category) {
return insertWaypoint(title, description, category, 0.0, -1, -1);
}
private long insertWaypoint(String title, double distance) {
return insertWaypoint(title, "", "", distance, -1, -1);
}
private long insertWaypoint(String title, long hoursAgo) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, -1);
}
private long insertWaypoint(String title, long hoursAgo, long trackId) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId);
}
public void testSearchText() {
// Insert 7 tracks (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertTrack("bb", "cc", "dd");
long descriptionMatchId = insertTrack("bb", "aa", "cc");
long categoryMatchId = insertTrack("bb", "cc", "aa");
long titleMatchId = insertTrack("aa", "bb", "cc");
long titleCategoryMatchId = insertTrack("aa", "bb", "ca");
long titleDescriptionMatchId = insertTrack("aa", "ba", "cc");
long allMatchId = insertTrack("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertTrackResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchWaypointText() {
// Insert 7 waypoints (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertWaypoint("bb", "cc", "dd");
long descriptionMatchId = insertWaypoint("bb", "aa", "cc");
long categoryMatchId = insertWaypoint("bb", "cc", "aa");
long titleMatchId = insertWaypoint("aa", "bb", "cc");
long titleCategoryMatchId = insertWaypoint("aa", "bb", "ca");
long titleDescriptionMatchId = insertWaypoint("aa", "ba", "cc");
long allMatchId = insertWaypoint("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertWaypointResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchMixedText() {
// Insert 5 entries (purposefully out of result order):
// - one waypoint which will match by description
// - one waypoint which won't match
// - one waypoint which will match by title
// - one track which won't match
// - one track which will match by title
long descriptionWaypointId = insertWaypoint("bb", "aa", "cc");
insertWaypoint("bb", "cc", "dd");
long titleWaypointId = insertWaypoint("aa", "bb", "cc");
insertTrack("bb", "cc", "dd");
long trackId = insertTrack("aa", "bb", "cc");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertEquals(results.toString(), 3, results.size());
assertTrackResult(trackId, results.get(0));
assertWaypointResult(titleWaypointId, results.get(1));
assertWaypointResult(descriptionWaypointId, results.get(2));
}
public void testSearchTrackDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertTrack("aa", 0.3);
long nearId = insertTrack("ab", 0.1);
long farId = insertTrack("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertTrackResults(results, nearId, farId, farFarAwayId);
}
public void testSearchWaypointDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertWaypoint("aa", 0.3);
long nearId = insertWaypoint("ab", 0.1);
long farId = insertWaypoint("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertWaypointResults(results, nearId, farId, farFarAwayId);
}
public void testSearchTrackRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertTrack("aa", 3);
long recentId = insertTrack("ab", 1);
long oldId = insertTrack("ac", 2);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertTrackResults(results, recentId, oldId, oldestId);
}
public void testSearchWaypointRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertWaypoint("aa", 2);
long recentId = insertWaypoint("ab", 0);
long oldId = insertWaypoint("ac", 1);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertWaypointResults(results, recentId, oldId, oldestId);
}
public void testSearchCurrentTrack() {
// All results match text, but one of them is the current track.
long currentId = insertTrack("ab", 1);
long otherId = insertTrack("aa", 1);
SearchQuery query = new SearchQuery("a", null, currentId, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Current track should be demoted.
assertTrackResults(results, otherId, currentId);
}
public void testSearchCurrentTrackWaypoint() {
// All results match text, but one of them is in the current track.
long otherId = insertWaypoint("aa", 1, 456);
long currentId = insertWaypoint("ab", 1, 123);
SearchQuery query = new SearchQuery("a", null, 123, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Waypoint in current track should be promoted.
assertWaypointResults(results, currentId, otherId);
}
private void assertTrackResult(long trackId, ScoredResult result) {
assertNotNull("Not a track", result.track);
assertNull("Ambiguous result", result.waypoint);
assertEquals(trackId, result.track.getId());
}
private void assertTrackResults(List<ScoredResult> results, long... trackIds) {
String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results;
assertEquals(results.size(), trackIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.track);
assertNull(errMsg, result.waypoint);
assertEquals(errMsg, trackIds[i], result.track.getId());
}
}
private void assertWaypointResult(long waypointId, ScoredResult result) {
assertNotNull("Not a waypoint", result.waypoint);
assertNull("Ambiguous result", result.track);
assertEquals(waypointId, result.waypoint.getId());
}
private void assertWaypointResults(List<ScoredResult> results, long... waypointIds) {
String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results;
assertEquals(results.size(), waypointIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.waypoint);
assertNull(errMsg, result.track);
assertEquals(errMsg, waypointIds[i], result.waypoint.getId());
}
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import static com.google.android.testing.mocking.AndroidMock.anyInt;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.isA;
import static com.google.android.testing.mocking.AndroidMock.leq;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.maps.mytracks.R;
import com.google.android.testing.mocking.AndroidMock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.provider.BaseColumns;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.lang.reflect.Constructor;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.easymock.Capture;
import org.easymock.IAnswer;
/**
* Tests for {@link TrackDataHub}.
*
* @author Rodrigo Damazio
*/
public class TrackDataHubTest extends AndroidTestCase {
private static final long TRACK_ID = 42L;
private static final int TARGET_POINTS = 50;
private MyTracksProviderUtils providerUtils;
private TrackDataHub hub;
private TrackDataListeners listeners;
private DataSourcesWrapper dataSources;
private SharedPreferences prefs;
private TrackDataListener listener1;
private TrackDataListener listener2;
private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture =
new Capture<SharedPreferences.OnSharedPreferenceChangeListener>();
private MockContext context;
private float declination;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class);
dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class);
listeners = new TrackDataListeners();
hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) {
@Override
protected DataSourcesWrapper newDataSources() {
return dataSources;
}
@Override
protected void runInListenerThread(Runnable runnable) {
// Run everything in the same thread.
runnable.run();
}
@Override
protected float getDeclinationFor(Location location, long timestamp) {
return declination;
}
};
listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class);
listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class);
}
@Override
protected void tearDown() throws Exception {
AndroidMock.reset(dataSources);
// Expect everything to be unregistered.
if (preferenceListenerCapture.hasCaptured()) {
dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue());
}
dataSources.removeLocationUpdates(isA(LocationListener.class));
dataSources.unregisterSensorListener(isA(SensorEventListener.class));
dataSources.unregisterContentObserver(isA(ContentObserver.class));
AndroidMock.expectLastCall().times(3);
AndroidMock.replay(dataSources);
hub.stop();
hub = null;
super.tearDown();
}
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
// Now expect an update.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
listener2.onTrackUpdated(track);
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
private static class FixedSizeCursorAnswer implements IAnswer<Cursor> {
private final int size;
public FixedSizeCursorAnswer(int size) {
this.size = size;
}
@Override
public Cursor answer() throws Throwable {
MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID });
for (long i = 1; i <= size; i++) {
cursor.addRow(new Object[] { i });
}
return cursor;
}
}
private static class FixedSizeLocationIterator implements LocationIterator {
private final long startId;
private final Location[] locs;
private final Set<Integer> splitIndexSet = new HashSet<Integer>();
private int currentIdx = -1;
public FixedSizeLocationIterator(long startId, int size) {
this(startId, size, null);
}
public FixedSizeLocationIterator(long startId, int size, int... splitIndices) {
this.startId = startId;
this.locs = new Location[size];
for (int i = 0; i < size; i++) {
Location loc = new Location("gps");
loc.setLatitude(-15.0 + i / 1000.0);
loc.setLongitude(37 + i / 1000.0);
loc.setAltitude(i);
locs[i] = loc;
}
if (splitIndices != null) {
for (int splitIdx : splitIndices) {
splitIndexSet.add(splitIdx);
Location splitLoc = locs[splitIdx];
splitLoc.setLatitude(100.0);
splitLoc.setLongitude(200.0);
}
}
}
public void expectLocationsDelivered(TrackDataListener listener) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else {
listener.onNewTrackPoint(locs[i]);
}
}
}
public void expectSampledLocationsDelivered(
TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else if (i % sampleFrequency == 0) {
listener.onNewTrackPoint(locs[i]);
} else if (includeSampledOut) {
listener.onSampledOutTrackPoint(locs[i]);
}
}
}
@Override
public boolean hasNext() {
return currentIdx < (locs.length - 1);
}
@Override
public Location next() {
currentIdx++;
return locs[currentIdx];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public long getLocationId() {
return startId + currentIdx;
}
@Override
public void close() {
// Do nothing
}
}
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
wpt3 = new Waypoint(),
wpt4 = new Waypoint();
Location loc = new Location("gps");
loc.setLatitude(10.0);
loc.setLongitude(8.0);
wpt1.setLocation(loc);
wpt2.setLocation(loc);
wpt3.setLocation(loc);
wpt4.setLocation(loc);
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(2));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt1)
.andReturn(wpt2);
expectStart();
dataSources.registerContentObserver(
eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener1.onNewWaypointsDone();
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(3));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3);
// Now expect an update.
listener1.clearWaypoints();
listener2.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt2);
listener1.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt3);
listener1.onNewWaypointsDone();
listener2.onNewWaypointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(4));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3)
.andReturn(wpt4);
// Now expect an update.
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt4);
listener2.onNewWaypointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Register a second listener - it will get the same points as the previous one
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should go to both listeners, without clearing.
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(11, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
locationIterator.expectLocationsDelivered(listener2);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister listener1, switch tracks to ensure data is cleared/reloaded.
locationIterator = new FixedSizeLocationIterator(101, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
hub.loadTrack(TRACK_ID + 1);
verifyAndReset();
}
public void testPointsListen_beforeStart() {
}
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again, except only points since unregistered.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(11, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should still be incremental.
locationIterator = new FixedSizeLocationIterator(21, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again after track changed, expect all points.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.loadTrack(TRACK_ID + 1);
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L);
listener1.clearTrackPoints();
listener2.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 4, false);
locationIterator.expectSampledLocationsDelivered(listener2, 4, true);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.POINT_UPDATES));
hub.registerTrackDataListener(listener2,
EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
hub.start();
verifyAndReset();
}
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Deliver 30 points (no sampling happens)
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Now deliver 30 more (incrementally sampled)
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(31, 30);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L);
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Now another 30 (triggers resampling)
locationIterator = new FixedSizeLocationIterator(1, 90);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L);
listener1.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testLocationListen() {
// TODO
}
public void testCompassListen() throws Exception {
AndroidMock.resetToDefault(listener1);
Sensor compass = newSensor();
expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass);
Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>();
dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt());
Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>();
dataSources.requestLocationUpdates(capture(locationListenerCapture));
SensorEvent event = newSensorEvent();
event.sensor = compass;
// First, get a dummy heading update.
listener1.onCurrentHeadingChanged(0.0);
// Then, get a heading update without a known location (thus can't calculate declination).
listener1.onCurrentHeadingChanged(42.0f);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES));
hub.start();
SensorEventListener sensorListener = listenerCapture.getValue();
LocationListener locationListener = locationListenerCapture.getValue();
event.values[0] = 42.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
// Expect the heading update to include declination.
listener1.onCurrentHeadingChanged(52.0);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
listener1.onCurrentLocationChanged(isA(Location.class));
AndroidMock.expectLastCall().anyTimes();
replay();
// Now try injecting a location update, triggering a declination update.
Location location = new Location("gps");
location.setLatitude(10.0);
location.setLongitude(20.0);
location.setAltitude(30.0);
declination = 10.0f;
locationListener.onLocationChanged(location);
sensorListener.onSensorChanged(event);
verifyAndReset();
listener1.onCurrentHeadingChanged(52.0);
replay();
// Now try changing the known declination - it should still return the old declination, since
// updates only happen sparsely.
declination = 20.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
}
private Sensor newSensor() throws Exception {
Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private SensorEvent newSensorEvent() throws Exception {
Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
return constructor.newInstance(3);
}
public void testDisplayPreferencesListen() throws Exception {
String metricUnitsKey = context.getString(R.string.metric_units_key);
String speedKey = context.getString(R.string.report_speed_key);
prefs.edit()
.putBoolean(metricUnitsKey, true)
.putBoolean(speedKey, true)
.apply();
Capture<OnSharedPreferenceChangeListener> listenerCapture =
new Capture<OnSharedPreferenceChangeListener>();
dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture));
expect(listener1.onUnitsChanged(true)).andReturn(false);
expect(listener2.onUnitsChanged(true)).andReturn(false);
expect(listener1.onReportSpeedChanged(true)).andReturn(false);
expect(listener2.onReportSpeedChanged(true)).andReturn(false);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
verifyAndReset();
expect(listener1.onReportSpeedChanged(false)).andReturn(false);
expect(listener2.onReportSpeedChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(speedKey, false)
.apply();
OnSharedPreferenceChangeListener listener = listenerCapture.getValue();
listener.onSharedPreferenceChanged(prefs, speedKey);
AndroidMock.verify(dataSources, providerUtils, listener1, listener2);
AndroidMock.reset(dataSources, providerUtils, listener1, listener2);
expect(listener1.onUnitsChanged(false)).andReturn(false);
expect(listener2.onUnitsChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(metricUnitsKey, false)
.apply();
listener.onSharedPreferenceChanged(prefs, metricUnitsKey);
verifyAndReset();
}
private void expectStart() {
dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture));
}
private void replay() {
AndroidMock.replay(dataSources, providerUtils, listener1, listener2);
}
private void verifyAndReset() {
AndroidMock.verify(listener1, listener2, dataSources, providerUtils);
AndroidMock.reset(listener1, listener2, dataSources, providerUtils);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock class that intercepts {@code Path}'s and records calls to
* {@code #moveTo()} and {@code #lineTo()}.
*/
public class MockPath extends Path {
/** A list of disjoined path segments. */
public final List<List<PointF>> segments = new LinkedList<List<PointF>>();
/** The total number of points in this path. */
public int totalPoints;
private List<PointF> currentSegment;
@Override
public void lineTo(float x, float y) {
super.lineTo(x, y);
Assert.assertNotNull(currentSegment);
currentSegment.add(new PointF(x, y));
totalPoints++;
}
@Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
segments.add(currentSegment =
new ArrayList<PointF>(Arrays.asList(new PointF(x, y))));
totalPoints++;
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import android.graphics.Point;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock {@code Projection} that acts as the identity matrix.
*/
public class MockProjection implements Projection {
@Override
public Point toPixels(GeoPoint in, Point out) {
return out;
}
@Override
public float metersToEquatorPixels(float meters) {
return meters;
}
@Override
public GeoPoint fromPixels(int x, int y) {
return new GeoPoint(y, x);
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorDynamicSpeedTest extends TrackPathPainterTestCase {
public void testDynamicSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new DynamicSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
}
/**
* Tests the method {@link DynamicSpeedTrackPathDescriptor#getSpeedMargin()}
* with zero, normal and illegal value.
*/
public void testGetSpeedMargin() {
String[] actuals = { "0", "50", "99", "" };
// The default value of speedMargin is 25.
int[] expectations = { 0, 50, 99, 25 };
// Test
for (int i = 0; i < expectations.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), actuals[i]);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(expectations[i],
dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences));
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_nullKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_otherKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_trackColorModeDynamicVariationKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
"trackColorModeDynamicVariation",
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
"trackColorModeDynamicVariation");
assertEquals(speedMargin + 2, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of speedMargin is "".
*/
public void testOnSharedPreferenceChanged_emptyValue() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "");
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_dynamic_speed_variation_key));
// The default value of speedMargin is 25.
assertEquals(25, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by wrong track
* id.
*/
public void testNeedsRedraw_WrongTrackId() {
long trackId = -1;
sharedPreferencesEditor.putLong(context.getString(R.string.selected_track_key), trackId);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by different
* averageMovingSpeed.
*/
public void testIsDiffereceSignificant() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
double[] averageMovingSpeeds = { 0, 30, 30, 30 };
double[] newAverageMovingSpeed = { 20, 30,
// Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100) / 2),
// Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
boolean[] expectedValues = { true, false, false, true };
double[] expectedAverageMovingSpeed = { 20, 30, 30,
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
// Test
for (int i = 0; i < newAverageMovingSpeed.length; i++) {
dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]);
assertEquals(expectedValues[i], dynamicSpeedTrackPathDescriptor.isDifferenceSignificant(
averageMovingSpeeds[i], newAverageMovingSpeed[i]));
assertEquals(expectedAverageMovingSpeed[i],
dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed());
}
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorFixedSpeedTest extends TrackPathPainterTestCase {
public void testFixedSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new FixedSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterSingleColorTest extends TrackPathPainterTestCase {
public void testSimpeColorTrackPathPainter() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new SingleColorTrackPathPainter(getContext());
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.MockMyTracksOverlay;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterTestCase extends AndroidTestCase {
protected Canvas canvas;
protected MockMyTracksOverlay myTracksOverlay;
protected MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
mockView = null;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
private int slowDefault;
private int normalDefault;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
// Get the default value
slowDefault = 9;
normalDefault = 15;
}
/**
* Tests the initialization of slowSpeed and normalSpeed in {@link
* DynamicSpeedTrackPathDescriptor#DynamicSpeedTrackPathDescriptor(Context)}.
*/
public void testConstructor() {
String[] slowSpeedsInShPre = { "0", "1", "99", "" };
int[] slowSpeedExpectations = { 0, 1, 99, slowDefault };
String[] normalSpeedsInShPre = { "0", "1", "99", "" };
int[] normalSpeedExpectations = { 0, 1, 99, normalDefault };
for (int i = 0; i < slowSpeedsInShPre.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key), slowSpeedsInShPre[i]);
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
normalSpeedsInShPre[i]);
sharedPreferencesEditor.commit();
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
assertEquals(slowSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_null_key() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not slowSpeed and not normalSpeed.
*/
public void testOnSharedPreferenceChanged_other_key() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is slowSpeed.
*/
public void testOnSharedPreferenceChanged_slowSpeedKey() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_slow_key));
assertEquals(slowSpeed + 2, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed + 2, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is normalSpeed.
*/
public void testOnSharedPreferenceChanged_normalSpeedKey() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 4));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 4));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
assertEquals(slowSpeed + 4, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed + 4, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of slowSpeed and normalSpeed in SharedPreference
* is "". In such situation, the default value should get returned.
*/
public void testOnSharedPreferenceChanged_emptyValue() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key), "");
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key), "");
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
assertEquals(slowDefault, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalDefault, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
/**
* Tests for the MyTracks track path painter factory.
*
* @author Vangelis S.
*/
public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase {
public void testTrackPathPainterFactory() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
Context context = getContext();
SharedPreferences prefs = context.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
if (prefs == null) {
return;
}
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_none,
SingleColorTrackPathPainter.class);
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_fixed,
DynamicSpeedTrackPathPainter.class);
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_dynamic,
DynamicSpeedTrackPathPainter.class);
}
private <T> void testTrackPathPainterFactorySpecific(Context context, SharedPreferences prefs,
int track_color_mode, Class <?> c) {
prefs.edit().putString(context.getString(R.string.track_color_mode_key),
context.getString(track_color_mode)).apply();
int startLocationIdx = 0;
Boolean alwaysVisible = true;
TrackPathPainter painter = TrackPathPainterFactory.getTrackPathPainter(context);
myTracksOverlay.setTrackPathPainter(painter);
assertNotNull(painter);
assertTrue(c.isInstance(painter));
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
// Copyright 2009 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.stats;
import com.google.android.apps.mytracks.Constants;
import android.location.Location;
import junit.framework.TestCase;
/**
* Test the the function of the TripStatisticsBuilder class.
*
* @author Sandor Dornbush
*/
public class TripStatisticsBuilderTest extends TestCase {
private TripStatisticsBuilder builder = null;
@Override
protected void setUp() throws Exception {
super.setUp();
builder = new TripStatisticsBuilder(System.currentTimeMillis());
}
public void testAddLocationSimple() throws Exception {
builder = new TripStatisticsBuilder(1000);
TripStatistics stats = builder.getStatistics();
assertEquals(0.0, builder.getSmoothedElevation());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation());
assertEquals(0.0, stats.getMaxSpeed());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade());
assertEquals(0.0, stats.getTotalElevationGain());
assertEquals(0, stats.getMovingTime());
assertEquals(0.0, stats.getTotalDistance());
for (int i = 0; i < 100; i++) {
Location l = new Location("test");
l.setAccuracy(1.0f);
l.setLongitude(45.0);
// Going up by 5 meters each time.
l.setAltitude(i);
// Moving by .1% of a degree latitude.
l.setLatitude(i * .001);
l.setSpeed(11.1f);
// Each time slice is 10 seconds.
long time = 1000 + 10000 * i;
l.setTime(time);
boolean moving = builder.addLocation(l, time);
assertEquals((i != 0), moving);
stats = builder.getStatistics();
assertEquals(10000 * i, stats.getTotalTime());
assertEquals(10000 * i, stats.getMovingTime());
assertEquals(i, builder.getSmoothedElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(0.0, stats.getMinElevation());
assertEquals(i, stats.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(i, stats.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(11.1f, stats.getMaxSpeed(), 0.1);
}
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(0.009, stats.getMinGrade(), 0.0001);
assertEquals(0.009, stats.getMaxGrade(), 0.0001);
}
// 1 degree = 111 km
// 1 timeslice = 0.001 degree = 111 m
assertEquals(111.0 * i, stats.getTotalDistance(), 100);
}
}
/**
* Test that elevation works if the user is stable.
*/
public void testElevationSimple() throws Exception {
for (double elevation = 0; elevation < 1000; elevation += 10) {
builder = new TripStatisticsBuilder(System.currentTimeMillis());
for (int j = 0; j < 100; j++) {
assertEquals(0.0, builder.updateElevation(elevation));
assertEquals(elevation, builder.getSmoothedElevation());
TripStatistics data = builder.getStatistics();
assertEquals(elevation, data.getMinElevation());
assertEquals(elevation, data.getMaxElevation());
assertEquals(0.0, data.getTotalElevationGain());
}
}
}
public void testElevationGain() throws Exception {
for (double i = 0; i < 1000; i++) {
double expectedGain;
if (i < (Constants.ELEVATION_SMOOTHING_FACTOR - 1)) {
expectedGain = 0;
} else if (i < Constants.ELEVATION_SMOOTHING_FACTOR) {
expectedGain = 0.5;
} else {
expectedGain = 1.0;
}
assertEquals(expectedGain,
builder.updateElevation(i));
assertEquals(i, builder.getSmoothedElevation(), 20);
TripStatistics data = builder.getStatistics();
assertEquals(0.0, data.getMinElevation(), 0.0);
assertEquals(i, data.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR);
assertEquals(i, data.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
}
}
public void testGradeSimple() throws Exception {
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, 100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(1.0, builder.getStatistics().getMinGrade());
}
}
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, -100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(-1.0, builder.getStatistics().getMinGrade());
}
}
}
public void testGradeIgnoreShort() throws Exception {
for (double i = 0; i < 100; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(1, 100);
assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade());
assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade());
}
}
public void testUpdateSpeedIncludeZero() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 0.0, i, 4.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
}
}
public void testUpdateSpeedIngoreErrorCode() {
builder.updateSpeed(12345000, 128.0, 12344000, 0.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
}
public void testUpdateSpeedIngoreLargeAcceleration() {
builder.updateSpeed(12345000, 100.0, 12344000, 1.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
}
public void testUpdateSpeed() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 4.0, i, 4.0);
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(4.0, builder.getStatistics().getMaxSpeed());
}
}
}
}
| Java |
/*
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Test for the DoubleBuffer class.
*
* @author Sandor Dornbush
*/
public class DoubleBufferTest extends TestCase {
/**
* Tests that the constructor leaves the buffer in a valid state.
*/
public void testConstructor() {
DoubleBuffer buffer = new DoubleBuffer(10);
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Simple test with 10 of the same values.
*/
public void testBasic() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 9; i++) {
buffer.setNext(1.0);
assertFalse(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
buffer.setNext(1);
assertTrue(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests with 5 entries of -10 and 5 entries of 10.
*/
public void testSplit() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 5; i++) {
buffer.setNext(-10);
assertFalse(buffer.isFull());
assertEquals(-10.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(-10.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
for (int i = 1; i < 5; i++) {
buffer.setNext(10);
assertFalse(buffer.isFull());
double expectedAverage = ((i * 10.0) - 50.0) / (i + 5);
assertEquals(buffer.toString(),
expectedAverage, buffer.getAverage(), 0.01);
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(expectedAverage, averageAndVariance[0]);
}
buffer.setNext(10);
assertTrue(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(100.0, averageAndVariance[1]);
}
/**
* Tests that reset leaves the buffer in a valid state.
*/
public void testReset() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 100; i++) {
buffer.setNext(i);
}
assertTrue(buffer.isFull());
buffer.reset();
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests that if a lot of items are inserted the smoothing and looping works.
*/
public void testLoop() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 1000; i++) {
buffer.setNext(i);
assertEquals(i >= 9, buffer.isFull());
if (i > 10) {
assertEquals(i - 4.5, buffer.getAverage());
}
}
}
}
| Java |
/**
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
import java.util.Random;
/**
* This class test the ExtremityMonitor class.
*
* @author Sandor Dornbush
*/
public class ExtremityMonitorTest extends TestCase {
public ExtremityMonitorTest(String name) {
super(name);
}
public void testInitialize() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
}
public void testSimple() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
assertFalse(monitor.update(1));
assertFalse(monitor.update(0.5));
}
/**
* Throws a bunch of random numbers between [0,1] at the monitor.
*/
public void testRandom() {
ExtremityMonitor monitor = new ExtremityMonitor();
Random random = new Random(42);
for (int i = 0; i < 1000; i++) {
monitor.update(random.nextDouble());
}
assertTrue(monitor.getMin() < 0.1);
assertTrue(monitor.getMax() < 1.0);
assertTrue(monitor.getMin() >= 0.0);
assertTrue(monitor.getMax() > 0.9);
}
public void testReset() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
monitor.reset();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Tests for {@link TripStatistics}.
* This only tests non-trivial pieces of that class.
*
* @author Rodrigo Damazio
*/
public class TripStatisticsTest extends TestCase {
private TripStatistics statistics;
@Override
protected void setUp() throws Exception {
super.setUp();
statistics = new TripStatistics();
}
public void testSetBounds() {
// This is not a trivial setter, conversion happens in it
statistics.setBounds(12345, -34567, 56789, -98765);
assertEquals(12345, statistics.getLeft());
assertEquals(-34567, statistics.getTop());
assertEquals(56789, statistics.getRight());
assertEquals(-98765, statistics.getBottom());
}
public void testMerge() {
TripStatistics statistics2 = new TripStatistics();
statistics.setStartTime(1000L); // Resulting start time
statistics.setStopTime(2500L);
statistics2.setStartTime(3000L);
statistics2.setStopTime(4000L); // Resulting stop time
statistics.setTotalTime(1500L);
statistics2.setTotalTime(1000L); // Result: 1500+1000
statistics.setMovingTime(700L);
statistics2.setMovingTime(600L); // Result: 700+600
statistics.setTotalDistance(750.0);
statistics2.setTotalDistance(350.0); // Result: 750+350
statistics.setTotalElevationGain(50.0);
statistics2.setTotalElevationGain(850.0); // Result: 850+50
statistics.setMaxSpeed(60.0); // Resulting max speed
statistics2.setMaxSpeed(30.0);
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0); // Resulting min elevation
statistics2.setMaxElevation(3575.0); // Resulting max elevation
statistics2.setMinElevation(2800.0);
statistics.setMaxGrade(15.0);
statistics.setMinGrade(-25.0); // Resulting min grade
statistics2.setMaxGrade(35.0); // Resulting max grade
statistics2.setMinGrade(0.0);
// Resulting bounds: -10000, 35000, 30000, -40000
statistics.setBounds(-10000, 20000, 30000, -40000);
statistics2.setBounds(-5000, 35000, 0, 20000);
statistics.merge(statistics2);
assertEquals(1000L, statistics.getStartTime());
assertEquals(4000L, statistics.getStopTime());
assertEquals(2500L, statistics.getTotalTime());
assertEquals(1300L, statistics.getMovingTime());
assertEquals(1100.0, statistics.getTotalDistance());
assertEquals(900.0, statistics.getTotalElevationGain());
assertEquals(60.0, statistics.getMaxSpeed());
assertEquals(-10000, statistics.getLeft());
assertEquals(30000, statistics.getRight());
assertEquals(35000, statistics.getTop());
assertEquals(-40000, statistics.getBottom());
assertEquals(1200.0, statistics.getMinElevation());
assertEquals(3575.0, statistics.getMaxElevation());
assertEquals(-25.0, statistics.getMinGrade());
assertEquals(35.0, statistics.getMaxGrade());
}
public void testGetAverageSpeed() {
statistics.setTotalDistance(1000.0);
statistics.setTotalTime(50000); // in milliseconds
assertEquals(20.0, statistics.getAverageSpeed());
}
public void testGetAverageMovingSpeed() {
statistics.setTotalDistance(1000.0);
statistics.setMovingTime(20000); // in milliseconds
assertEquals(50.0, statistics.getAverageMovingSpeed());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.ServiceUtils;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import java.io.File;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A unit test for {@link MyTracks} activity.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
private SharedPreferences sharedPreferences;
private TrackRecordingServiceConnection serviceConnection;
public MyTracksTest() {
super(MyTracks.class);
}
@Override
protected void tearDown() throws Exception {
clearSelectedAndRecordingTracks();
waitForIdle();
super.tearDown();
}
public void testInitialization_mainAction() {
// Make sure we can start MyTracks and the activity doesn't start recording.
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
public void testInitialization_viewActionWithNoData() {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
public void testInitialization_viewActionWithValidData() throws Exception {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(File.createTempFile("valid", ".gpx", getActivity().getFilesDir()));
// TODO: Add a valid GPX.
startIntent.setData(uri);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// TODO: Finish this test.
}
public void testInitialization_viewActionWithInvalidData() throws Exception {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(File.createTempFile("invalid", ".gpx", getActivity().getFilesDir()));
startIntent.setData(uri);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// TODO: Finish this test.
}
public void testRecording_startAndStop() throws Exception {
assertInitialized();
// Check if not recording.
clearSelectedAndRecordingTracks();
waitForIdle();
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Start a new track.
getActivity().startRecording();
serviceConnection.bindIfRunning();
long recordingTrackId = awaitRecordingStatus(5000, true);
assertTrue(recordingTrackId >= 0);
// Wait until we are done and make sure that selectedTrack = recordingTrack.
waitForIdle();
assertEquals(recordingTrackId, getSharedPreferences().getLong(
getActivity().getString(R.string.recording_track_key), -1));
selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(recordingTrackId, selectedTrackId);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Watch for MyTracksDetails activity.
ActivityMonitor monitor = getInstrumentation().addMonitor(
TrackDetail.class.getName(), null, false);
// Now, stop the track and make sure that it is still selected, but
// no longer recording.
getActivity().stopRecording();
// Check if we got back MyTracksDetails activity.
Activity activity = getInstrumentation().waitForMonitor(monitor);
assertTrue(activity instanceof TrackDetail);
// TODO: Update track name and other properties and test if they were
// properly saved.
// Simulate a click on Save button.
final Button save = (Button) activity.findViewById(R.id.track_detail_save);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
save.performClick();
}
});
// Check the remaining properties.
recordingTrackId = awaitRecordingStatus(5000, false);
assertEquals(-1, recordingTrackId);
assertEquals(recordingTrackId, getRecordingTrackId());
assertEquals(recordingTrackId, getSharedPreferences().getLong(
getActivity().getString(R.string.recording_track_key), -1));
// Make sure this is the same track as the last recording track ID.
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
private void assertInitialized() {
assertNotNull(getActivity());
serviceConnection = new TrackRecordingServiceConnection(getActivity(), null);
}
/**
* Waits until the UI thread becomes idle.
*/
private void waitForIdle() throws InterruptedException {
// Note: We can't use getInstrumentation().waitForIdleSync() here.
final Object semaphore = new Object();
synchronized (semaphore) {
final AtomicBoolean isIdle = new AtomicBoolean();
getInstrumentation().waitForIdle(new Runnable() {
@Override
public void run() {
synchronized (semaphore) {
isIdle.set(true);
semaphore.notify();
}
}
});
while (!isIdle.get()) {
semaphore.wait();
}
}
}
/**
* Clears {selected,recording}TrackId in the {@link #getSharedPreferences()}.
*/
private void clearSelectedAndRecordingTracks() {
Editor editor = getSharedPreferences().edit();
editor.putLong(getActivity().getString(R.string.selected_track_key), -1);
editor.putLong(getActivity().getString(R.string.recording_track_key), -1);
editor.clear();
editor.apply();
}
/**
* Waits until the recording state changes to the given status.
*
* @param timeout the maximum time to wait, in milliseconds.
* @param isRecording the final status to await.
* @return the recording track ID.
*/
private long awaitRecordingStatus(long timeout, boolean isRecording)
throws TimeoutException, InterruptedException {
long startTime = System.nanoTime();
while (isRecording() != isRecording) {
if (System.nanoTime() - startTime > timeout * 1000000) {
throw new TimeoutException("Timeout while waiting for recording!");
}
Thread.sleep(20);
}
waitForIdle();
assertEquals(isRecording, isRecording());
return getRecordingTrackId();
}
private long getRecordingTrackId() {
return getSharedPreferences().getLong(getActivity().getString(R.string.recording_track_key), -1);
}
private SharedPreferences getSharedPreferences() {
if (sharedPreferences == null) {
sharedPreferences = getActivity().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
}
return sharedPreferences;
}
private boolean isRecording() {
return ServiceUtils.isRecording(getActivity(),
serviceConnection.getServiceIfBound(), getSharedPreferences());
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.testing;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import android.content.Context;
/**
* A fake factory for {@link MyTracksProviderUtils} which always returns a
* predefined instance.
*
* @author Rodrigo Damazio
*/
public class TestingProviderUtilsFactory extends Factory {
private MyTracksProviderUtils instance;
public TestingProviderUtilsFactory(MyTracksProviderUtils instance) {
this.instance = instance;
}
@Override
protected MyTracksProviderUtils newForContext(Context context) {
return instance;
}
public static Factory installWithInstance(MyTracksProviderUtils instance) {
Factory oldFactory = Factory.getInstance();
Factory factory = new TestingProviderUtilsFactory(instance);
MyTracksProviderUtils.Factory.overrideInstance(factory);
return oldFactory;
}
public static void restoreOldFactory(Factory factory) {
MyTracksProviderUtils.Factory.overrideInstance(factory);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings;
import com.google.android.maps.mytracks.R;
import android.graphics.Paint.Style;
import android.test.AndroidTestCase;
/**
* @author Sandor Dornbush
*/
public class ChartValueSeriesTest extends AndroidTestCase {
private ChartValueSeries series;
@Override
protected void setUp() throws Exception {
series = new ChartValueSeries(getContext(),
R.color.elevation_fill,
R.color.elevation_border,
new ZoomSettings(5, new int[] {100}),
R.string.stat_elevation);
}
public void testInitialConditions() {
assertEquals(0, series.getInterval());
assertEquals(1, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(0, series.getMax());
assertEquals(0.0, series.getSpread());
assertEquals(Style.STROKE, series.getPaint().getStyle());
assertEquals(getContext().getString(R.string.stat_elevation),
series.getTitle());
assertTrue(series.isEnabled());
}
public void testEnabled() {
series.setEnabled(false);
assertFalse(series.isEnabled());
}
public void testSmallUpdates() {
series.update(0);
series.update(10);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(3, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(100, series.getMax());
assertEquals(100.0, series.getSpread());
}
public void testBigUpdates() {
series.update(0);
series.update(901);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(5, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(1000, series.getMax());
assertEquals(1000.0, series.getSpread());
}
public void testNotZeroBasedUpdates() {
series.update(500);
series.update(1401);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(5, series.getMaxLabelLength());
assertEquals(500, series.getMin());
assertEquals(1500, series.getMax());
assertEquals(1000.0, series.getSpread());
}
public void testZoomSettings_invalidArgs() {
try {
new ZoomSettings(0, new int[] {10, 50, 100});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, new int[] {});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, new int[] {1, 3, 2});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
}
public void testZoomSettings_minAligned() {
ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100});
assertEquals(10, settings.calculateInterval(0, 15));
assertEquals(10, settings.calculateInterval(0, 50));
assertEquals(50, settings.calculateInterval(0, 111));
assertEquals(50, settings.calculateInterval(0, 250));
assertEquals(100, settings.calculateInterval(0, 251));
assertEquals(100, settings.calculateInterval(0, 10000));
}
public void testZoomSettings_minNotAligned() {
ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100});
assertEquals(50, settings.calculateInterval(5, 55));
assertEquals(10, settings.calculateInterval(10, 60));
assertEquals(50, settings.calculateInterval(7, 250));
assertEquals(100, settings.calculateInterval(7, 257));
assertEquals(100, settings.calculateInterval(11, 10000));
// A regression test.
settings = new ZoomSettings(5, new int[] {5, 10, 20});
assertEquals(10, settings.calculateInterval(-37.14, -11.89));
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Sensor.SensorDataSet;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import com.jayway.android.robotium.solo.Solo;
import android.app.Instrumentation;
import android.location.Location;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ZoomControls;
/**
* Tests {@link ChartActivity}.
*
* @author Youtao Liu
*/
public class ChartActivityTest extends ActivityInstrumentationTestCase2<ChartActivity> {
private Instrumentation instrumentation;
private ChartActivity chartActivity;
private Solo solo;
private View zoomIn;
private View zoomOut;
private int currentZoomLevel;
private final String LOCATION_PROVIDER = "gps";
private final double INITIAL_LONGTITUDE = 22;
private final double INITIAL_LATITUDE = 22;
private final double INITIAL_ALTITUDE = 22;
private final float INITIAL_ACCURACY = 5;
private final float INITIAL_SPEED = 10;
private final float INITIAL_BEARING = 3.0f;
// 10 is same with the default value in ChartView
private final int MAX_ZOOM_LEVEL = 10;
private final int MIN_ZOOM_LEVEL = 1;
// The ratio from meter/second to kilometer/hour, the conversion is 60 * 60 /
// 1000 = 3.6.
private final double METER_PER_SECOND_TO_KILOMETER_PER_HOUR = 3.6;
private final double KILOMETER_TO_METER = 1000.0;
private final double HOURS_PER_UNIT = 60;
public ChartActivityTest() {
super(ChartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
chartActivity = getActivity();
}
/**
* Tests {@link ChartActivity#zoomIn()} and {@link ChartActivity#zoomOut()}.
*/
public void testZoomInAndZoomOut() {
currentZoomLevel = chartActivity.getChartView().getZoomLevel();
chartActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
ZoomControls zoomControls = (ZoomControls) chartActivity.findViewById(R.id.elevation_zoom);
zoomIn = zoomControls.getChildAt(0);
zoomOut = zoomControls.getChildAt(1);
// Invoke following two methods method to initial the display of
// ZoomControls.
zoomControls.setIsZoomInEnabled(chartActivity.getChartView().canZoomIn());
zoomControls.setIsZoomOutEnabled(chartActivity.getChartView().canZoomOut());
// Click zoomIn button to disable.
for (int i = currentZoomLevel; i > MIN_ZOOM_LEVEL; i--) {
zoomIn.performClick();
}
}
});
instrumentation.waitForIdleSync();
assertEquals(false, zoomIn.isEnabled());
assertEquals(true, zoomOut.isEnabled());
chartActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// Click to the second max zoom level
for (int i = MIN_ZOOM_LEVEL; i < MAX_ZOOM_LEVEL - 1; i++) {
zoomOut.performClick();
assertEquals(true, zoomIn.isEnabled());
assertEquals(true, zoomOut.isEnabled());
}
zoomOut.performClick();
}
});
instrumentation.waitForIdleSync();
assertEquals(true, zoomIn.isEnabled());
assertEquals(false, zoomOut.isEnabled());
}
/**
* There are two parts in this test. Tests
* {@link ChartActivity#OnCreateDialog()} which includes the logic to create
* {@link ChartSettingsDialog}.
*/
public void testCreateSettingDialog() {
solo = new Solo(instrumentation, chartActivity);
// Part1, tests {@link ChartActivity#onCreateOptionsMenu()}. Check if
// optional menu is created.
assertNull(chartActivity.getChartSettingsMenuItem());
sendKeys(KeyEvent.KEYCODE_MENU);
assertNotNull(chartActivity.getChartSettingsMenuItem());
// Part2, tests {@link ChartActivity#onOptionsItemSelected()}. Clicks on the
// "Chart settings", and then verify that the dialog contains the
// "By distance" text.
solo.clickOnText(chartActivity.getString(R.string.menu_chart_view_chart_settings));
instrumentation.waitForIdleSync();
assertTrue(solo.searchText(chartActivity.getString(R.string.chart_settings_by_distance)));
}
/**
* Tests the logic to get the incorrect values of sensor in {@link
* ChartActivity#fillDataPoint(Location location, double result[])}.
*/
public void testFillDataPoint_sensorIncorrect() {
MyTracksLocation myTracksLocation = getMyTracksLocation();
// No input.
double[] point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
// Input incorrect state.
// Creates SensorData.
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
// Creates SensorDataSet.
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
.setHeartRate(heartRateData).build();
myTracksLocation.setSensorData(sensorDataSet);
// Test.
point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
}
/**
* Tests the logic to get the correct values of sensor in {@link
* ChartActivity#fillDataPoint(Location location, double result[])}.
*/
public void testFillDataPoint_sensorCorrect() {
MyTracksLocation myTracksLocation = getMyTracksLocation();
// No input.
double[] point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
// Creates SensorData.
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
// Creates SensorDataSet.
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
.setHeartRate(heartRateData).build();
myTracksLocation.setSensorData(sensorDataSet);
// Test.
point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(20.0, point[3]);
assertEquals(20.0, point[4]);
assertEquals(20.0, point[5]);
}
/**
* Tests the logic to get the value of metric Distance in
* {@link #fillDataPoint}.
*/
public void testFillDataPoint_distanceMetric() {
// By distance.
chartActivity.getChartView().setMode(ChartView.Mode.BY_DISTANCE);
// Resets last location and writes first location.
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
// The second is a same location, just different time.
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals(0.0, point[0]);
// The third location is a new location, and use metric.
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
myTracksLocation3.setLatitude(23);
point = fillDataPointTestHelper(myTracksLocation3, false);
// Computes the distance between Latitude 22 and 23.
float[] results = new float[4];
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
double distance1 = results[0];
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
// The fourth location is a new location, and use metric.
MyTracksLocation myTracksLocation4 = getMyTracksLocation();
myTracksLocation4.setLatitude(24);
point = fillDataPointTestHelper(myTracksLocation4, false);
// Computes the distance between Latitude 23 and 24.
Location.distanceBetween(myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(),
myTracksLocation4.getLatitude(), myTracksLocation4.getLongitude(), results);
double distance2 = results[0];
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
}
/**
* Tests the logic to get the value of imperial Distance in
* {@link #fillDataPoint}.
*/
public void testFillDataPoint_distanceImperial() {
// Setups to use imperial.
chartActivity.onUnitsChanged(false);
// The first is a same location, just different time.
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
// The second location is a new location, and use imperial.
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setLatitude(23);
point = fillDataPointTestHelper(myTracksLocation2, false);
/*
* Computes the distance between Latitude 22 and 23. And for we set using
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
*/
float[] results = new float[4];
Location.distanceBetween(myTracksLocation1.getLatitude(), myTracksLocation1.getLongitude(),
myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(), results);
double distance1 = results[0] * UnitConversions.KM_TO_MI;
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
// The third location is a new location, and use imperial.
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
myTracksLocation3.setLatitude(24);
point = fillDataPointTestHelper(myTracksLocation3, false);
/*
* Computes the distance between Latitude 23 and 24. And for we set using
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
*/
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
double distance2 = results[0] * UnitConversions.KM_TO_MI;
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
}
/**
* Tests the logic to get the values of time in {@link #fillDataPoint}.
*/
public void testFillDataPoint_time() {
// By time
chartActivity.getChartView().setMode(ChartView.Mode.BY_TIME);
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
long timeSpan = 222;
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setTime(myTracksLocation1.getTime() + timeSpan);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals((double) timeSpan, point[0]);
}
/**
* Tests the logic to get the value of elevation in
* {@link ChartActivity#fillDataPoint} by one and two points.
*/
public void testFillDataPoint_elevation() {
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
/*
* At first, clear old points of elevation, so give true to the second
* parameter. Then only one value INITIALLONGTITUDE in buffer.
*/
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(INITIAL_ALTITUDE, point[1]);
/*
* Send another value to buffer, now there are two values, INITIALALTITUDE
* and INITIALALTITUDE * 2.
*/
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setAltitude(INITIAL_ALTITUDE * 2);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals((INITIAL_ALTITUDE + INITIAL_ALTITUDE * 2) / 2.0, point[1]);
}
/**
* Tests the logic to get the value of speed in
* {@link ChartActivity#fillDataPoint}. In this test, firstly remove all
* points in memory, and then fill in two points one by one. The speed values
* of these points are 129, 130.
*/
public void testFillDataPoint_speed() {
// Set max speed to make the speed of points are valid.
chartActivity.setTrackMaxSpeed(200.0);
/*
* At first, clear old points of speed, so give true to the second
* parameter. It will not be filled in to the speed buffer.
*/
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
myTracksLocation1.setSpeed(129);
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[2]);
/*
* Tests the logic when both metricUnits and reportSpeed are true.This
* location will be filled into speed buffer.
*/
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
// Add a time span here to make sure the second point is valid, the value
// 222 here is doesn't matter.
myTracksLocation2.setTime(myTracksLocation1.getTime() + 222);
myTracksLocation2.setSpeed(130);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals(130.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR, point[2]);
}
/**
* Tests the logic to compute speed when use Imperial.
*/
public void testFillDataPoint_speedImperial() {
// Setups to use imperial.
chartActivity.onUnitsChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(132);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(132.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR * UnitConversions.KM_TO_MI,
point[2]);
}
/**
* Tests the logic to get pace value when reportSpeed is false.
*/
public void testFillDataPoint_pace_nonZeroSpeed() {
// Setups reportSpeed to false.
chartActivity.onReportSpeedChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(134);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(HOURS_PER_UNIT / (134.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR), point[2]);
}
/**
* Tests the logic to get pace value when reportSpeed is false and average
* speed is zero.
*/
public void testFillDataPoint_pace_zeroSpeed() {
// Setups reportSpeed to false.
chartActivity.onReportSpeedChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(0);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(Double.NaN, point[2]);
}
/**
* Simulates a MyTracksLocation for test.
*
* @return a simulated location.
*/
private MyTracksLocation getMyTracksLocation() {
// Initial Location
Location loc = new Location(LOCATION_PROVIDER);
loc.setLongitude(INITIAL_LONGTITUDE);
loc.setLatitude(INITIAL_LATITUDE);
loc.setAltitude(INITIAL_ALTITUDE);
loc.setAccuracy(INITIAL_ACCURACY);
loc.setSpeed(INITIAL_SPEED);
loc.setTime(System.currentTimeMillis());
loc.setBearing(INITIAL_BEARING);
SensorDataSet sd = SensorDataSet.newBuilder().build();
MyTracksLocation myTracksLocation = new MyTracksLocation(loc, sd);
return myTracksLocation;
}
/**
* Helper method to test fillDataPoint.
*
* @param location location to fill
* @param operation a flag to do some operations
* @return data of this location
*/
private double[] fillDataPointTestHelper(Location location, boolean isNeedClear) {
if (isNeedClear) {
chartActivity.clearTrackPoints();
}
double[] point = new double[6];
chartActivity.fillDataPoint(location, point);
return point;
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import android.content.Context;
import android.graphics.Rect;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock version of {@code MapOverlay} that does not use
* {@class MapView}.
*/
public class MockMyTracksOverlay extends MapOverlay {
private Projection mockProjection;
public MockMyTracksOverlay(Context context) {
super(context);
mockProjection = new MockProjection();
}
@Override
public Projection getMapProjection(MapView mapView) {
return mockProjection;
}
@Override
public Rect getMapViewRect(MapView mapView) {
return new Rect(0, 0, 100, 100);
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.ChartView.Mode;
import com.google.android.maps.mytracks.R;
import android.test.ActivityInstrumentationTestCase2;
/**
* Tests the {@link ChartSettingsDialog}.
*
* @author Youtao Liu
*/
public class ChartSettingsDialogTest extends ActivityInstrumentationTestCase2<ChartActivity> {
private ChartSettingsDialog chartSettingsDialog;
public ChartSettingsDialogTest() {
super(ChartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
chartSettingsDialog = new ChartSettingsDialog(getActivity());
chartSettingsDialog.show();
}
/**
* Tests the {@link ChartSettingsDialog#setMode} and check the result by
* {@link ChartSettingsDialog#getMode}. Gets all modes of Mode, then set and
* get each mode.
*/
public void testSetMode() {
Mode[] modes = Mode.values();
for (Mode mode : modes) {
chartSettingsDialog.setMode(mode);
assertEquals(mode, chartSettingsDialog.getMode());
}
}
/**
* Tests the {@link ChartSettingsDialog#setDisplaySpeed}.
*/
public void testSetDisplaySpeed() {
chartSettingsDialog.setDisplaySpeed(true);
assertEquals(getActivity().getString(R.string.stat_speed),
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
chartSettingsDialog.setDisplaySpeed(false);
assertEquals(getActivity().getString(R.string.stat_pace),
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
}
/**
* Tests the {@link ChartSettingsDialog#setSeriesEnabled} and check the result
* by {@link ChartSettingsDialog#isSeriesEnabled}.
*/
public void testSetSeriesEnabled() {
for (int i = 0; i < ChartView.NUM_SERIES; i++) {
chartSettingsDialog.setSeriesEnabled(i, true);
assertEquals(true, chartSettingsDialog.getSeries()[i].isChecked());
assertEquals(true, chartSettingsDialog.isSeriesEnabled(i));
chartSettingsDialog.setSeriesEnabled(i, false);
assertEquals(false, chartSettingsDialog.getSeries()[i].isChecked());
assertEquals(false, chartSettingsDialog.isSeriesEnabled(i));
}
}
} | Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import java.util.Vector;
import junit.framework.TestCase;
/**
* Tests for the Chart URL generator.
*
* @author Sandor Dornbush
*/
public class ChartURLGeneratorTest extends TestCase {
public void testgetChartUrl() {
Vector<Double> distances = new Vector<Double>();
Vector<Double> elevations = new Vector<Double>();
Track t = new Track();
TripStatistics stats = t.getStatistics();
stats.setMinElevation(0);
stats.setMaxElevation(2000);
stats.setTotalDistance(100);
distances.add(0.0);
elevations.add(10.0);
distances.add(10.0);
elevations.add(300.0);
distances.add(20.0);
elevations.add(800.0);
distances.add(50.0);
elevations.add(1900.0);
distances.add(75.0);
elevations.add(1200.0);
distances.add(90.0);
elevations.add(700.0);
distances.add(100.0);
elevations.add(70.0);
String chart = ChartURLGenerator.getChartUrl(distances,
elevations,
t,
"Title",
true);
assertEquals(
"http://chart.apis.google.com/chart?&chs=600x350&cht=lxy&"
+ "chtt=Title&chxt=x,y&chxr=0,0,0,0|1,0.0,2100.0,300&chco=009A00&"
+ "chm=B,00AA00,0,0,0&chg=100000,14.285714285714286,1,0&"
+ "chd=e:AAGZMzf.v.5l..,ATJJYY55kkVVCI",
chart);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.Constants;
import android.os.Environment;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
/**
* Tests for {@link FileUtils}.
*
* @author Rodrigo Damazio
*/
public class FileUtilsTest extends TestCase {
private FileUtils fileUtils;
private Set<String> existingFiles;
@Override
protected void setUp() throws Exception {
super.setUp();
existingFiles = new HashSet<String>();
fileUtils = new FileUtils() {
@Override
protected boolean fileExists(File directory, String fullName) {
return existingFiles.contains(fullName);
}
};
}
public void testBuildExternalDirectoryPath() {
String expectedName = Environment.getExternalStorageDirectory()
+ File.separator
+ Constants.SDCARD_TOP_DIR
+ File.separator
+ "a"
+ File.separator
+ "b"
+ File.separator
+ "c";
String dirName = fileUtils.buildExternalDirectoryPath("a", "b", "c");
assertEquals(expectedName, dirName);
}
/**
* Tests sanitize filename.
*/
public void testSanitizeFileName() {
String name = "Swim\10ming-^across:/the/ pacific (ocean).";
String expected = "Swim_ming-^across_the_ pacific (ocean)_";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
/**
* Tests characters in other languages, like Chinese and Russian, are allowed.
*/
public void testSanitizeFileName_i18n() {
String name = "您好-привет";
String expected = "您好-привет";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
/**
* Tests special FAT32 characters are allowed.
*/
public void testSanitizeFileName_special_characters() {
String name = "$%'-_@~`!(){}^#&+,;=[] ";
String expected = "$%'-_@~`!(){}^#&+,;=[] ";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
/**
* Testing collapsing multiple underscores characters.
*/
public void testSanitizeFileName_collapse() {
String name = "hello//there";
String expected = "hello_there";
assertEquals(expected, fileUtils.sanitizeFileName(name));
}
public void testTruncateFileName() {
File directory = new File("/dir1/dir2/");
String suffix = ".gpx";
char[] name = new char[FileUtils.MAX_FAT32_PATH_LENGTH];
for (int i = 0; i < name.length; i++) {
name[i] = 'a';
}
String nameString = new String(name);
String truncated = fileUtils.truncateFileName(directory, nameString, suffix);
for (int i = 0; i < truncated.length(); i++) {
assertEquals('a', truncated.charAt(i));
}
assertEquals(FileUtils.MAX_FAT32_PATH_LENGTH,
new File(directory, truncated + suffix).getPath().length());
}
public void testBuildUniqueFileName_someExist() {
existingFiles = new HashSet<String>();
existingFiles.add("Filename.ext");
existingFiles.add("Filename(1).ext");
existingFiles.add("Filename(2).ext");
existingFiles.add("Filename(3).ext");
existingFiles.add("Filename(4).ext");
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename(5).ext", filename);
}
public void testBuildUniqueFileName_oneExists() {
existingFiles.add("Filename.ext");
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename(1).ext", filename);
}
public void testBuildUniqueFileName_noneExists() {
String filename = fileUtils.buildUniqueFileName(new File("/dir/"), "Filename", "ext");
assertEquals("Filename.ext", filename);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import junit.framework.TestCase;
/**
* Tests for {@link StringUtils}.
*
* @author Rodrigo Damazio
*/
public class StringUtilsTest extends TestCase {
public void testParseXmlDateTime() {
assertParseXmlDateTime("2010-05-04T03:02:01",
2010, 5, 4, 3, 2, 1, 0);
}
public void testParseXmlDateTime_fractional() {
assertParseXmlDateTime("2010-05-04T03:02:01.3",
2010, 5, 4, 3, 2, 1, 300);
assertParseXmlDateTime("2010-05-04T03:02:01.35",
2010, 5, 4, 3, 2, 1, 350);
assertParseXmlDateTime("2010-05-04T03:02:01.352",
2010, 5, 4, 3, 2, 1, 352);
assertParseXmlDateTime("2010-05-04T03:02:01.3525",
2010, 5, 4, 3, 2, 1, 352);
}
public void testParseXmlDateTime_timezone() {
assertParseXmlDateTime("2010-05-04T03:02:01Z",
2010, 5, 4, 3, 2, 1, 0);
assertParseXmlDateTime("2010-05-04T03:02:01+00:00",
2010, 5, 4, 3, 2, 1, 0);
assertParseXmlDateTime("2010-05-04T03:02:01-00:00",
2010, 5, 4, 3, 2, 1, 0);
assertParseXmlDateTime("2010-05-04T03:02:01+01:00",
2010, 5, 4, 2, 2, 1, 0);
assertParseXmlDateTime("2010-05-04T03:02:01+10:30",
2010, 5, 3, 16, 32, 1, 0);
assertParseXmlDateTime("2010-05-04T03:02:01-09:30",
2010, 5, 4, 12, 32, 1, 0);
assertParseXmlDateTime("2010-05-04T03:02:01-05:00",
2010, 5, 4, 8, 2, 1, 0);
}
public void testParseXmlDateTime_fractionalAndTimezone() {
assertParseXmlDateTime("2010-05-04T03:02:01.352Z",
2010, 5, 4, 3, 2, 1, 352);
assertParseXmlDateTime("2010-05-04T03:02:01.47+00:00",
2010, 5, 4, 3, 2, 1, 470);
assertParseXmlDateTime("2010-05-04T03:02:01.5791+03:00",
2010, 5, 4, 0, 2, 1, 579);
assertParseXmlDateTime("2010-05-04T03:02:01.8-05:30",
2010, 5, 4, 8, 32, 1, 800);
}
private void assertParseXmlDateTime(String dateTime,
int year, int month, int day, int hour, int min, int second, int millis) {
long timestamp = StringUtils.parseXmlDateTime(dateTime);
GregorianCalendar calendar =
new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.set(year, month - 1, day, hour, min, second);
calendar.set(GregorianCalendar.MILLISECOND, millis);
assertEquals(calendar.getTimeInMillis(), timestamp);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import junit.framework.TestCase;
/**
* A unit test for {@link ChartsExtendedEncoder}.
*
* @author Bartlomiej Niechwiej
*/
public class ChartsExtendedEncoderTest extends TestCase {
public void testGetEncodedValue_validArguments() {
// Valid arguments.
assertEquals("AK", ChartsExtendedEncoder.getEncodedValue(10));
assertEquals("JO", ChartsExtendedEncoder.getEncodedValue(590));
assertEquals("AA", ChartsExtendedEncoder.getEncodedValue(0));
// 64^2 = 4096.
assertEquals("..", ChartsExtendedEncoder.getEncodedValue(4095));
}
public void testGetEncodedValue_invalidArguments() {
// Invalid arguments.
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(4096));
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(1234564096));
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-10));
assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-12324435));
}
public void testGetSeparator() {
assertEquals(",", ChartsExtendedEncoder.getSeparator());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.sendtogoogle;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
/**
* Tests the {@link UploadServiceChooserActivity}.
*
* @author Youtao Liu
*/
public class UploadServiceChooserActivityTest extends
ActivityInstrumentationTestCase2<UploadServiceChooserActivity> {
private Instrumentation instrumentation;
private UploadServiceChooserActivity uploadServiceChooserActivity;
public UploadServiceChooserActivityTest() {
super(UploadServiceChooserActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
}
/**
* Tests the logic to control display all send options. This test cover code
* in method {@link UploadServiceChooserActivity#onCreateDialog()},
* {@link UploadServiceChooserActivity#updateStateBySendRequest()} and
* {@link UploadServiceChooserActivity#updateStateBySelection()}.
*/
public void testOnCreateDialog_displayAll() {
// Initials activity to display all send items.
initialActivity(true, true, true);
instrumentation.waitForIdleSync();
assertTrue(getMapsCheckBox().isShown());
assertTrue(getFusionTablesCheckBox().isShown());
assertTrue(getDocsCheckBox().isShown());
assertTrue(getCancelButton().isEnabled());
// Clicks to disable all send items.
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
public void run() {
if (getMapsCheckBox().isChecked()) {
getMapsCheckBox().performClick();
}
if (getFusionTablesCheckBox().isChecked()) {
getFusionTablesCheckBox().performClick();
}
if (getDocsCheckBox().isChecked()) {
getDocsCheckBox().performClick();
}
}
});
instrumentation.waitForIdleSync();
assertTrue(getMapsCheckBox().isShown());
assertTrue(getFusionTablesCheckBox().isShown());
assertTrue(getDocsCheckBox().isShown());
assertTrue(getCancelButton().isEnabled());
assertFalse(getNewMapRadioButton().isShown());
assertFalse(getExistingMapRadioButton().isShown());
assertFalse(getSendButton().isEnabled());
}
/**
* Tests the logic to check the send to Google Maps option. This test cover
* code in method {@link UploadServiceChooserActivity#onCreateDialog()},
* {@link UploadServiceChooserActivity#updateStateBySendRequest()} and
* {@link UploadServiceChooserActivity#updateStateBySelection()}.
*/
public void testOnCreateDialog_displayOne() {
// Initials activity to display all send items.
initialActivity(true, false, false);
instrumentation.waitForIdleSync();
assertTrue(getMapsCheckBox().isShown());
assertTrue(getCancelButton().isEnabled());
// Clicks to enable this items.
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
public void run() {
if (!getMapsCheckBox().isChecked()) {
getMapsCheckBox().performClick();
}
}
});
instrumentation.waitForIdleSync();
assertTrue(getMapsCheckBox().isShown());
assertTrue(getNewMapRadioButton().isShown());
assertTrue(getExistingMapRadioButton().isShown());
assertTrue(getSendButton().isEnabled());
assertTrue(getCancelButton().isEnabled());
}
/**
* Tests the logic to control display none. This test cover code in method
* {@link UploadServiceChooserActivity#onCreateDialog()},
* {@link UploadServiceChooserActivity#updateStateBySendRequest()} and
* {@link UploadServiceChooserActivity#updateStateBySelection()}.
*/
public void testOnCreateDialog_displayNone() {
initialActivity(false, false, false);
assertFalse(getMapsCheckBox().isShown());
assertFalse(getFusionTablesCheckBox().isShown());
assertFalse(getDocsCheckBox().isShown());
assertFalse(getSendButton().isEnabled());
assertTrue(getCancelButton().isEnabled());
}
/**
* Tests the logic to initial state of check box to unchecked. This test cover
* code in method {@link UploadServiceChooserActivity#onCreateDialog()},
* {@link UploadServiceChooserActivity#initState()}.
*/
public void testOnCreateDialog_initStateUnchecked() {
initialActivity(true, true, true);
// Initial all values to false in SharedPreferences.
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
false);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), false);
editor.commit();
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
public void run() {
uploadServiceChooserActivity.initState();
}
});
instrumentation.waitForIdleSync();
assertFalse(getMapsCheckBox().isChecked());
assertFalse(getFusionTablesCheckBox().isChecked());
assertFalse(getDocsCheckBox().isChecked());
}
/**
* Tests the logic to initial state of check box to checked. This test cover
* code in method {@link UploadServiceChooserActivity#onCreateDialog()},
* {@link UploadServiceChooserActivity#initState()}.
*/
public void testOnCreateDialog_initStateChecked() {
initialActivity(true, true, true);
// Initial all values to true in SharedPreferences.
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.pick_existing_map_key), true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true);
editor.commit();
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
public void run() {
uploadServiceChooserActivity.initState();
}
});
instrumentation.waitForIdleSync();
assertTrue(getMapsCheckBox().isChecked());
assertTrue(getFusionTablesCheckBox().isChecked());
assertTrue(getDocsCheckBox().isChecked());
assertTrue(getExistingMapRadioButton().isChecked());
assertFalse(getNewMapRadioButton().isChecked());
}
/**
* Tests the logic of saveState when click send button. This test cover code
* in method {@link UploadServiceChooserActivity#saveState()},
* {@link UploadServiceChooserActivity#initState()} ,
* {@link UploadServiceChooserActivity#sendMaps()},
* {@link UploadServiceChooserActivity#sendFusionTables()}, and
* {@link UploadServiceChooserActivity#sendDocs()}.
*/
public void testOnCreateDialog_saveState() {
initialActivity(true, true, true);
// Initial all values to true in SharedPreferences.
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true);
editor.commit();
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
public void run() {
uploadServiceChooserActivity.initState();
}
});
instrumentation.waitForIdleSync();
uploadServiceChooserActivity.saveState();
// All values in SharedPreferences must be changed.
assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key),
false));
assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key),
false));
assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key),
false));
}
/**
* Tests the logic of startNextActivity when click send button. This test
* cover code in method
* {@link UploadServiceChooserActivity#startNextActivity()} ,
* {@link UploadServiceChooserActivity#initState()} ,
* {@link UploadServiceChooserActivity#sendMaps()},
* {@link UploadServiceChooserActivity#sendFusionTables()}, and
* {@link UploadServiceChooserActivity#sendDocs()}.
*/
public void testOnCreateDialog_startNextActivity() {
initialActivity(true, true, true);
// Initial all values to true or false in SharedPreferences.
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true);
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
false);
editor.commit();
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
public void run() {
uploadServiceChooserActivity.initState();
}
});
instrumentation.waitForIdleSync();
uploadServiceChooserActivity.startNextActivity();
// All values in SendRequest must be same as set above.
assertTrue(uploadServiceChooserActivity.getSendRequest().isSendMaps());
assertTrue(uploadServiceChooserActivity.getSendRequest().isSendDocs());
assertFalse(uploadServiceChooserActivity.getSendRequest().isSendFusionTables());
}
/**
* Initials a activity to be tested.
*
* @param showMaps
* @param showFusionTables
* @param showDocs
*/
private void initialActivity(boolean showMaps, boolean showFusionTables, boolean showDocs) {
Intent intent = new Intent();
intent.putExtra(SendRequest.SEND_REQUEST_KEY, new SendRequest(1L, showMaps, showFusionTables,
showDocs));
setActivityIntent(intent);
uploadServiceChooserActivity = this.getActivity();
}
private Button getSendButton() {
return (Button) uploadServiceChooserActivity.getDialog()
.findViewById(R.id.send_google_send_now);
}
Button getCancelButton() {
return (Button) uploadServiceChooserActivity.getDialog().findViewById(R.id.send_google_cancel);
}
private CheckBox getMapsCheckBox() {
return (CheckBox) uploadServiceChooserActivity.getDialog().findViewById(R.id.send_google_maps);
}
private CheckBox getFusionTablesCheckBox() {
return (CheckBox) uploadServiceChooserActivity.getDialog().findViewById(
R.id.send_google_fusion_tables);
}
private CheckBox getDocsCheckBox() {
return (CheckBox) uploadServiceChooserActivity.getDialog().findViewById(R.id.send_google_docs);
}
private RadioButton getNewMapRadioButton() {
return (RadioButton) uploadServiceChooserActivity.getDialog().findViewById(
R.id.send_google_new_map);
}
private RadioButton getExistingMapRadioButton() {
return (RadioButton) uploadServiceChooserActivity.getDialog().findViewById(
R.id.send_google_existing_map);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.sendtogoogle;
import android.accounts.Account;
import android.os.Parcel;
import android.os.Parcelable;
import android.test.AndroidTestCase;
/**
* Tests the {@link SendRequest}.
*
* @author Youtao Liu
*/
public class SendRequestTest extends AndroidTestCase {
private SendRequest sendRequest;
final static private String ACCOUNTNAME = "testAccount1";
final static private String ACCOUNTYPE = "testType1";
final static private String MAPID = "mapId1";
@Override
protected void setUp() throws Exception {
super.setUp();
sendRequest = new SendRequest(1, true, true, true);
}
/**
* Tests the method {@link SendRequest#getTrackId()}. The value should be set
* to 1 when it is initialed in setup method.
*/
public void testGetTrackId() {
assertEquals(1, sendRequest.getTrackId());
}
/**
* Tests the method {@link SendRequest#isShowMaps()}. The value should be set
* to true when it is initialed in setup method.
*/
public void testIsShowMaps() {
assertEquals(true, sendRequest.isShowMaps());
}
/**
* Tests the method {@link SendRequest#isShowFusionTables()}. The value should
* be set to true when it is initialed in setup method.
*/
public void testIsShowFusionTables() {
assertEquals(true, sendRequest.isShowFusionTables());
}
/**
* Tests the method {@link SendRequest#isShowDocs()}. The value should be set
* to true when it is initialed in setup method.
*/
public void testIsShowDocs() {
assertEquals(true, sendRequest.isShowDocs());
}
public void testIsShowAll() {
assertEquals(true, sendRequest.isShowAll());
sendRequest = new SendRequest(1, false, true, true);
assertEquals(false, sendRequest.isShowAll());
sendRequest = new SendRequest(1, true, false, true);
assertEquals(false, sendRequest.isShowAll());
sendRequest = new SendRequest(1, true, true, false);
assertEquals(false, sendRequest.isShowAll());
sendRequest = new SendRequest(1, false, true, false);
assertEquals(false, sendRequest.isShowAll());
sendRequest = new SendRequest(1, false, false, false);
assertEquals(false, sendRequest.isShowAll());
}
public void testIsSendMaps() {
assertEquals(false, sendRequest.isSendMaps());
sendRequest.setSendMaps(true);
assertEquals(true, sendRequest.isSendMaps());
}
public void testIsSendFusionTables() {
assertEquals(false, sendRequest.isSendFusionTables());
sendRequest.setSendFusionTables(true);
assertEquals(true, sendRequest.isSendFusionTables());
}
/**
* Tests the method {@link SendRequest#isSendDocs()}. The value should be set
* to false which is its default value when it is initialed in setup method.
*/
public void testIsSendDocs() {
assertEquals(false, sendRequest.isSendDocs());
sendRequest.setSendDocs(true);
assertEquals(true, sendRequest.isSendDocs());
}
/**
* Tests the method {@link SendRequest#isNewMap()}. The value should be set to
* false which is its default value when it is initialed in setup method.
*/
public void testIsNewMap() {
assertEquals(false, sendRequest.isNewMap());
sendRequest.setNewMap(true);
assertEquals(true, sendRequest.isNewMap());
}
/**
* Tests the method {@link SendRequest#getAccount()}. The value should be set
* to null which is its default value when it is initialed in setup method.
*/
public void testGetAccount() {
assertEquals(null, sendRequest.getAccount());
Account account = new Account(ACCOUNTNAME, ACCOUNTYPE);
sendRequest.setAccount(account);
assertEquals(account, sendRequest.getAccount());
}
/**
* Tests the method {@link SendRequest#getMapId()}. The value should be set to
* null which is its default value when it is initialed in setup method.
*/
public void testGetMapId() {
assertEquals(null, sendRequest.getMapId());
sendRequest.setMapId("1");
assertEquals("1", "1");
}
/**
* Tests the method {@link SendRequest#isMapsSuccess()}. The value should be
* set to false which is its default value when it is initialed in setup
* method.
*/
public void testIsMapsSuccess() {
assertEquals(false, sendRequest.isMapsSuccess());
sendRequest.setMapsSuccess(true);
assertEquals(true, sendRequest.isMapsSuccess());
}
/**
* Tests the method {@link SendRequest#isFusionTablesSuccess()}. The value
* should be set to false which is its default value when it is initialed in
* setup method.
*/
public void testIsFusionTablesSuccess() {
assertEquals(false, sendRequest.isFusionTablesSuccess());
sendRequest.setFusionTablesSuccess(true);
assertEquals(true, sendRequest.isFusionTablesSuccess());
}
/**
* Tests the method {@link SendRequest#isDocsSuccess()}. The value should be
* set to false which is its default value when it is initialed in setup
* method.
*/
public void testIsDocsSuccess() {
assertEquals(false, sendRequest.isDocsSuccess());
sendRequest.setDocsSuccess(true);
assertEquals(true, sendRequest.isDocsSuccess());
}
/**
* Tests {@link SendRequest#SendRequest(Parcel in)} when all values are true.
*/
public void testCreateFromParcel_true() {
Parcel sourceParcel = Parcel.obtain();
sourceParcel.setDataPosition(0);
sourceParcel.writeLong(2);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
Account account = new Account(ACCOUNTNAME, ACCOUNTYPE);
sourceParcel.writeParcelable(account, 0);
sourceParcel.writeString(MAPID);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.writeByte((byte) 1);
sourceParcel.setDataPosition(0);
sendRequest = SendRequest.CREATOR.createFromParcel(sourceParcel);
assertEquals(2, sendRequest.getTrackId());
assertEquals(true, sendRequest.isShowMaps());
assertEquals(true, sendRequest.isShowFusionTables());
assertEquals(true, sendRequest.isShowDocs());
assertEquals(true, sendRequest.isSendMaps());
assertEquals(true, sendRequest.isSendFusionTables());
assertEquals(true, sendRequest.isSendDocs());
assertEquals(true, sendRequest.isNewMap());
assertEquals(account, sendRequest.getAccount());
assertEquals(MAPID, sendRequest.getMapId());
assertEquals(true, sendRequest.isMapsSuccess());
assertEquals(true, sendRequest.isFusionTablesSuccess());
assertEquals(true, sendRequest.isDocsSuccess());
}
/**
* Tests {@link SendRequest#SendRequest(Parcel in)} when all values are false.
*/
public void testCreateFromParcel_false() {
Parcel sourceParcel = Parcel.obtain();
sourceParcel.setDataPosition(0);
sourceParcel.writeLong(4);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
Account account = new Account(ACCOUNTNAME, ACCOUNTYPE);
sourceParcel.writeParcelable(account, 0);
sourceParcel.writeString(MAPID);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.writeByte((byte) 0);
sourceParcel.setDataPosition(0);
sendRequest = SendRequest.CREATOR.createFromParcel(sourceParcel);
assertEquals(4, sendRequest.getTrackId());
assertEquals(false, sendRequest.isShowMaps());
assertEquals(false, sendRequest.isShowFusionTables());
assertEquals(false, sendRequest.isShowDocs());
assertEquals(false, sendRequest.isSendMaps());
assertEquals(false, sendRequest.isSendFusionTables());
assertEquals(false, sendRequest.isSendDocs());
assertEquals(false, sendRequest.isNewMap());
assertEquals(account, sendRequest.getAccount());
assertEquals(MAPID, sendRequest.getMapId());
assertEquals(false, sendRequest.isMapsSuccess());
assertEquals(false, sendRequest.isFusionTablesSuccess());
assertEquals(false, sendRequest.isDocsSuccess());
}
/**
* Tests {@link SendRequest#writeToParcel(Parcel in)} when all input values
* are true or affirmative.
*/
public void testWriteToParcel_allTrue() {
sendRequest = new SendRequest(1, false, false, false);
Parcel parcelWrite1st = Parcel.obtain();
parcelWrite1st.setDataPosition(0);
sendRequest.writeToParcel(parcelWrite1st, 1);
parcelWrite1st.setDataPosition(0);
long trackId = parcelWrite1st.readLong();
boolean showMaps = parcelWrite1st.readByte() == 1;
boolean showFusionTables = parcelWrite1st.readByte() == 1;
boolean showDocs = parcelWrite1st.readByte() == 1;
boolean sendMaps = parcelWrite1st.readByte() == 1;
boolean sendFusionTables = parcelWrite1st.readByte() == 1;
boolean sendDocs = parcelWrite1st.readByte() == 1;
boolean newMap = parcelWrite1st.readByte() == 1;
Parcelable account = parcelWrite1st.readParcelable(null);
String mapId = parcelWrite1st.readString();
boolean mapsSuccess = parcelWrite1st.readByte() == 1;
boolean fusionTablesSuccess = parcelWrite1st.readByte() == 1;
boolean docsSuccess = parcelWrite1st.readByte() == 1;
assertEquals(1, trackId);
assertEquals(false, showMaps);
assertEquals(false, showFusionTables);
assertEquals(false, showDocs);
assertEquals(false, sendMaps);
assertEquals(false, sendFusionTables);
assertEquals(false, sendDocs);
assertEquals(false, newMap);
assertEquals(null, account);
assertEquals(null, mapId);
assertEquals(false, mapsSuccess);
assertEquals(false, fusionTablesSuccess);
assertEquals(false, docsSuccess);
}
/**
* Tests {@link SendRequest#writeToParcel(Parcel in)} when all input values
* are false or negative.
*/
public void testWriteToParcel_allFalse() {
sendRequest = new SendRequest(4, true, true, true);
sendRequest.setSendMaps(true);
sendRequest.setSendFusionTables(true);
sendRequest.setSendDocs(true);
sendRequest.setNewMap(true);
Account accountNew = new Account(ACCOUNTNAME + "2", ACCOUNTYPE + "2");
sendRequest.setAccount(accountNew);
sendRequest.setMapId(MAPID);
sendRequest.setMapsSuccess(true);
sendRequest.setFusionTablesSuccess(true);
sendRequest.setDocsSuccess(true);
Parcel parcelWrite2nd = Parcel.obtain();
parcelWrite2nd.setDataPosition(0);
sendRequest.writeToParcel(parcelWrite2nd, 1);
parcelWrite2nd.setDataPosition(0);
long trackId = parcelWrite2nd.readLong();
boolean showMaps = parcelWrite2nd.readByte() == 1;
boolean showFusionTables = parcelWrite2nd.readByte() == 1;
boolean showDocs = parcelWrite2nd.readByte() == 1;
boolean sendMaps = parcelWrite2nd.readByte() == 1;
boolean sendFusionTables = parcelWrite2nd.readByte() == 1;
boolean sendDocs = parcelWrite2nd.readByte() == 1;
boolean newMap = parcelWrite2nd.readByte() == 1;
Parcelable account = parcelWrite2nd.readParcelable(null);
String mapId = parcelWrite2nd.readString();
boolean mapsSuccess = parcelWrite2nd.readByte() == 1;
boolean fusionTablesSuccess = parcelWrite2nd.readByte() == 1;
boolean docsSuccess = parcelWrite2nd.readByte() == 1;
assertEquals(4, trackId);
assertEquals(true, showMaps);
assertEquals(true, showFusionTables);
assertEquals(true, showDocs);
assertEquals(true, sendMaps);
assertEquals(true, sendFusionTables);
assertEquals(true, sendDocs);
assertEquals(true, newMap);
assertEquals(accountNew, account);
assertEquals(MAPID, mapId);
assertEquals(true, mapsSuccess);
assertEquals(true, fusionTablesSuccess);
assertEquals(true, docsSuccess);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.docs;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient.WorksheetEntry;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.wireless.gdata.data.Entry;
import android.test.AndroidTestCase;
/**
* Tests {@link SendDocsUtils}.
*
* @author Jimmy Shih
*/
public class SendDocsUtilsTest extends AndroidTestCase {
private static final long TIME = 1288721514000L;
/**
* Tests {@link SendDocsUtils#getEntryId(Entry)} with a valid id.
*/
public void testGetEntryId_valid() {
Entry entry = new Entry();
entry.setId("https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123");
assertEquals("123", SendDocsUtils.getEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getEntryId(Entry)} with an invalid id.
*/
public void testGetEntryId_invalid() {
Entry entry = new Entry();
entry.setId("123");
assertEquals(null, SendDocsUtils.getEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} with a valid id.
*/
public void testGetNewSpreadsheetId_valid_id() {
assertEquals("123", SendDocsUtils.getNewSpreadsheetId(
"<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>"));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an open
* tag, <id>.
*/
public void testGetNewSpreadsheetId_no_open_tag() {
assertEquals(null, SendDocsUtils.getNewSpreadsheetId(
"https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>"));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an end tag,
* </id>.
*/
public void testGetNewSpreadsheetId_no_end_tag() {
assertEquals(null, SendDocsUtils.getNewSpreadsheetId(
"<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123"));
}
/**
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without the url
* prefix,
* https://docs.google.com/feeds/documents/private/full/spreadsheet%3A.
*/
public void testGetNewSpreadsheetId_no_prefix() {
assertEquals(null, SendDocsUtils.getNewSpreadsheetId("<id>123</id>"));
}
/**
* Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a
* valid entry.
*/
public void testGetWorksheetEntryId_valid() {
WorksheetEntry entry = new WorksheetEntry();
entry.setId("/123");
assertEquals("123", SendDocsUtils.getWorksheetEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a
* invalid entry.
*/
public void testGetWorksheetEntryId_invalid() {
WorksheetEntry entry = new WorksheetEntry();
entry.setId("123");
assertEquals(null, SendDocsUtils.getWorksheetEntryId(entry));
}
/**
* Tests {@link SendDocsUtils#getRowContent(Track, boolean,
* android.content.Context)} with metric units.
*/
public void testGetRowContent_metric() throws Exception {
Track track = getTrack();
String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' "
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA["
+ StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
+ "<gsx:distance><![CDATA[20.00]]></gsx:distance>"
+ "<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>"
+ "<gsx:averagespeed><![CDATA[14,400.00]]></gsx:averagespeed>"
+ "<gsx:averagemovingspeed><![CDATA[18,000.00]]>" + "</gsx:averagemovingspeed>"
+ "<gsx:maxspeed><![CDATA[5,400.00]]></gsx:maxspeed>"
+ "<gsx:speedunit><![CDATA[km/h]]></gsx:speedunit>"
+ "<gsx:elevationgain><![CDATA[6,000]]></gsx:elevationgain>"
+ "<gsx:minelevation><![CDATA[-500]]></gsx:minelevation>"
+ "<gsx:maxelevation><![CDATA[550]]></gsx:maxelevation>"
+ "<gsx:elevationunit><![CDATA[m]]></gsx:elevationunit>" + "<gsx:map>"
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>"
+ "</entry>";
assertEquals(expectedData, SendDocsUtils.getRowContent(track, true, getContext()));
}
/**
* Tests {@link SendDocsUtils#getRowContent(Track, boolean,
* android.content.Context)} with imperial units.
*/
public void testGetRowContent_imperial() throws Exception {
Track track = getTrack();
String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' "
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA["
+ StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
+ "<gsx:distance><![CDATA[12.43]]></gsx:distance>"
+ "<gsx:distanceunit><![CDATA[mi]]></gsx:distanceunit>"
+ "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>"
+ "<gsx:averagemovingspeed><![CDATA[11,184.68]]>" + "</gsx:averagemovingspeed>"
+ "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>"
+ "<gsx:speedunit><![CDATA[mi/h]]></gsx:speedunit>"
+ "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>"
+ "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>"
+ "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>"
+ "<gsx:elevationunit><![CDATA[ft]]></gsx:elevationunit>" + "<gsx:map>"
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>"
+ "</entry>";
assertEquals(expectedData, SendDocsUtils.getRowContent(track, false, getContext()));
}
/**
* Gets a track for testing {@link SendDocsUtils#getRowContent(Track, boolean,
* android.content.Context)}.
*/
private Track getTrack() {
TripStatistics stats = new TripStatistics();
stats.setStartTime(TIME);
stats.setTotalTime(5000);
stats.setMovingTime(4000);
stats.setTotalDistance(20000);
stats.setMaxSpeed(1500);
stats.setTotalElevationGain(6000);
stats.setMinElevation(-500);
stats.setMaxElevation(550);
Track track = new Track();
track.setName("trackName");
track.setDescription("trackDescription");
track.setMapId("trackMapId");
track.setStatistics(stats);
return track;
}
/**
* Tests {@link SendDocsUtils#appendTag(StringBuilder, String, String)} with
* repeated calls.
*/
public void testAppendTag() {
StringBuilder stringBuilder = new StringBuilder();
SendDocsUtils.appendTag(stringBuilder, "name1", "value1");
assertEquals("<gsx:name1><![CDATA[value1]]></gsx:name1>", stringBuilder.toString());
SendDocsUtils.appendTag(stringBuilder, "name2", "value2");
assertEquals(
"<gsx:name1><![CDATA[value1]]></gsx:name1><gsx:name2><![CDATA[value2]]></gsx:name2>",
stringBuilder.toString());
}
/**
* Tests {@link SendDocsUtils#getDistance(double, boolean)} with metric units.
*/
public void testGetDistance_metric() {
assertEquals("1.22", SendDocsUtils.getDistance(1222.3, true));
}
/**
* Tests {@link SendDocsUtils#getDistance(double, boolean)} with imperial
* units.
*/
public void testGetDistance_imperial() {
assertEquals("0.76", SendDocsUtils.getDistance(1222.3, false));
}
/**
* Tests {@link SendDocsUtils#getSpeed(double, boolean)} with metric units.
*/
public void testGetSpeed_metric() {
assertEquals("15.55", SendDocsUtils.getSpeed(4.32, true));
}
/**
* Tests {@link SendDocsUtils#getSpeed(double, boolean)} with imperial units.
*/
public void testGetSpeed_imperial() {
assertEquals("9.66", SendDocsUtils.getSpeed(4.32, false));
}
/**
* Tests {@link SendDocsUtils#getElevation(double, boolean)} with metric
* units.
*/
public void testGetElevation_metric() {
assertEquals("3", SendDocsUtils.getElevation(3.456, true));
}
/**
* Tests {@link SendDocsUtils#getElevation(double, boolean)} with imperial
* units.
*/
public void testGetElevation_imperial() {
assertEquals("11", SendDocsUtils.getElevation(3.456, false));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.content.ContentValues;
import android.net.Uri;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import junit.framework.TestCase;
/**
* Tests for {@link DatabaseImporter}.
*
* @author Rodrigo Damazio
*/
public class DatabaseImporterTest extends TestCase {
private static final Uri DESTINATION_URI = Uri.parse("http://www.google.com/");
private static final int TEST_BULK_SIZE = 10;
private ArrayList<ContentValues> insertedValues;
private class TestableDatabaseImporter extends DatabaseImporter {
public TestableDatabaseImporter(boolean readNullFields) {
super(DESTINATION_URI, null, readNullFields, TEST_BULK_SIZE);
}
@Override
protected void doBulkInsert(ContentValues[] values) {
insertedValues.ensureCapacity(insertedValues.size() + values.length);
// We need to make a copy of the values since the objects are re-used
for (ContentValues contentValues : values) {
insertedValues.add(new ContentValues(contentValues));
}
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
insertedValues = new ArrayList<ContentValues>();
}
public void testImportAllRows() throws Exception {
testImportAllRows(false);
}
public void testImportAllRows_readNullFields() throws Exception {
testImportAllRows(true);
}
private void testImportAllRows(boolean readNullFields) throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
writeFullHeader(writer);
// Add the number of rows
writer.writeInt(2);
// Add a row with all fields present
writer.writeLong(0x7F);
writer.writeInt(42);
writer.writeBoolean(true);
writer.writeUTF("lolcat");
writer.writeFloat(3.1415f);
writer.writeDouble(2.72);
writer.writeLong(123456789L);
writer.writeInt(4);
writer.writeBytes("blob");
// Add a row with some missing fields
writer.writeLong(0x15);
writer.writeInt(42);
if (readNullFields) writer.writeBoolean(false);
writer.writeUTF("lolcat");
if (readNullFields) writer.writeFloat(0.0f);
writer.writeDouble(2.72);
if (readNullFields) writer.writeLong(0L);
if (readNullFields) writer.writeInt(0); // empty blob
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(readNullFields);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
assertEquals(2, insertedValues.size());
// Verify the first row
ContentValues value = insertedValues.get(0);
assertEquals(value.toString(), 7, value.size());
assertValue(42, "col1", value);
assertValue(true, "col2", value);
assertValue("lolcat", "col3", value);
assertValue(3.1415f, "col4", value);
assertValue(2.72, "col5", value);
assertValue(123456789L, "col6", value);
assertBlobValue("blob", "col7", value);
// Verify the second row
value = insertedValues.get(1);
assertEquals(value.toString(), 3, value.size());
assertValue(42, "col1", value);
assertValue("lolcat", "col3", value);
assertValue(2.72, "col5", value);
}
public void testImportAllRows_noRows() throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
writeFullHeader(writer);
// Add the number of rows
writer.writeInt(0);
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(false);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
assertTrue(insertedValues.isEmpty());
}
public void testImportAllRows_emptyRows() throws Exception {
testImportAllRowsWithEmptyRows(false);
}
public void testImportAllRows_emptyRowsWithNulls() throws Exception {
testImportAllRowsWithEmptyRows(true);
}
private void testImportAllRowsWithEmptyRows(boolean readNullFields) throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
writeFullHeader(writer);
// Add the number of rows
writer.writeInt(3);
// Add 2 rows with no fields
for (int i = 0; i < 2; i++) {
writer.writeLong(0);
if (readNullFields) {
writer.writeInt(0);
writer.writeBoolean(false);
writer.writeUTF("");
writer.writeFloat(0.0f);
writer.writeDouble(0.0);
writer.writeLong(0L);
writer.writeInt(0); // empty blob
}
}
// Add a row with some missing fields
writer.writeLong(0x15);
writer.writeInt(42);
if (readNullFields) writer.writeBoolean(false);
writer.writeUTF("lolcat");
if (readNullFields) writer.writeFloat(0.0f);
writer.writeDouble(2.72);
if (readNullFields) writer.writeLong(0L);
if (readNullFields) writer.writeInt(0); // empty blob
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(readNullFields);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
assertEquals(insertedValues.toString(), 3, insertedValues.size());
ContentValues value = insertedValues.get(0);
assertEquals(value.toString(), 0, value.size());
value = insertedValues.get(1);
assertEquals(value.toString(), 0, value.size());
// Verify the third row (only one with values)
value = insertedValues.get(2);
assertEquals(value.toString(), 3, value.size());
assertFalse(value.containsKey("col2"));
assertFalse(value.containsKey("col4"));
assertFalse(value.containsKey("col6"));
assertValue(42, "col1", value);
assertValue("lolcat", "col3", value);
assertValue(2.72, "col5", value);
}
public void testImportAllRows_bulks() throws Exception {
// Create a fake data stream to be read
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outputStream);
// Add the header
writer.writeInt(2);
writer.writeUTF("col1");
writer.writeByte(ContentTypeIds.INT_TYPE_ID);
writer.writeUTF("col2");
writer.writeByte(ContentTypeIds.STRING_TYPE_ID);
// Add lots of rows (so the insertions are split in multiple bulks)
int numRows = TEST_BULK_SIZE * 5 / 2;
writer.writeInt(numRows);
for (int i = 0; i < numRows; i++) {
writer.writeLong(3);
writer.writeInt(i);
writer.writeUTF(Integer.toString(i * 2));
}
writer.flush();
// Do the importing
DatabaseImporter importer = new TestableDatabaseImporter(false);
byte[] dataBytes = outputStream.toByteArray();
importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes)));
// Verify the rows
assertEquals(numRows, insertedValues.size());
for (int i = 0; i < numRows; i++) {
ContentValues value = insertedValues.get(i);
assertEquals(value.toString(), 2, value.size());
assertValue(i, "col1", value);
assertValue(Integer.toString(i * 2), "col2", value);
}
}
private void writeFullHeader(DataOutputStream writer) throws IOException {
// Add the header
writer.writeInt(7);
writer.writeUTF("col1");
writer.writeByte(ContentTypeIds.INT_TYPE_ID);
writer.writeUTF("col2");
writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID);
writer.writeUTF("col3");
writer.writeByte(ContentTypeIds.STRING_TYPE_ID);
writer.writeUTF("col4");
writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID);
writer.writeUTF("col5");
writer.writeByte(ContentTypeIds.DOUBLE_TYPE_ID);
writer.writeUTF("col6");
writer.writeByte(ContentTypeIds.LONG_TYPE_ID);
writer.writeUTF("col7");
writer.writeByte(ContentTypeIds.BLOB_TYPE_ID);
}
private <T> void assertValue(T expectedValue, String name, ContentValues values) {
@SuppressWarnings("unchecked")
T value = (T) values.get(name);
assertNotNull(value);
assertEquals(expectedValue, value);
}
private void assertBlobValue(String expectedValue, String name, ContentValues values ){
byte[] blob = values.getAsByteArray(name);
assertEquals(expectedValue, new String(blob));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.backup;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
/**
* Tests for {@link PreferenceBackupHelper}.
*
* @author Rodrigo Damazio
*/
public class PreferenceBackupHelperTest extends TestCase {
private Map<String, ?> preferenceValues;
private SharedPreferences preferences;
private PreferenceBackupHelper preferenceBackupHelper;
/**
* Mock shared preferences editor which does not persist state.
*/
private class MockPreferenceEditor implements SharedPreferences.Editor {
private Map<String, Object> newPreferences = new HashMap<String, Object>(preferenceValues);
@Override
public Editor clear() {
newPreferences.clear();
return this;
}
@Override
public boolean commit() {
apply();
return true;
}
@Override
public void apply() {
preferenceValues = newPreferences;
}
@Override
public Editor putBoolean(String key, boolean value) {
return put(key, value);
}
@Override
public Editor putFloat(String key, float value) {
return put(key, value);
}
@Override
public Editor putInt(String key, int value) {
return put(key, value);
}
@Override
public Editor putLong(String key, long value) {
return put(key, value);
}
@Override
public Editor putString(String key, String value) {
return put(key, value);
}
public Editor putStringSet(String key, Set<String> value) {
return put(key, value);
}
private <T> Editor put(String key, T value) {
newPreferences.put(key, value);
return this;
}
@Override
public Editor remove(String key) {
newPreferences.remove(key);
return this;
}
}
/**
* Mock shared preferences which does not persist state.
*/
private class MockPreferences implements SharedPreferences {
@Override
public boolean contains(String key) {
return preferenceValues.containsKey(key);
}
@Override
public Editor edit() {
return new MockPreferenceEditor();
}
@Override
public Map<String, ?> getAll() {
return preferenceValues;
}
@Override
public boolean getBoolean(String key, boolean defValue) {
return get(key, defValue);
}
@Override
public float getFloat(String key, float defValue) {
return get(key, defValue);
}
@Override
public int getInt(String key, int defValue) {
return get(key, defValue);
}
@Override
public long getLong(String key, long defValue) {
return get(key, defValue);
}
@Override
public String getString(String key, String defValue) {
return get(key, defValue);
}
public Set<String> getStringSet(String key, Set<String> defValue) {
return get(key, defValue);
}
@Override
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
private <T> T get(String key, T defValue) {
Object value = preferenceValues.get(key);
if (value == null) return defValue;
return (T) value;
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
preferenceValues = new HashMap<String, Object>();
preferences = new MockPreferences();
preferenceBackupHelper = new PreferenceBackupHelper();
}
public void testExportImportPreferences() throws Exception {
// Populate with some initial values
Editor editor = preferences.edit();
editor.clear();
editor.putBoolean("bool1", true);
editor.putBoolean("bool2", false);
editor.putFloat("flt1", 3.14f);
editor.putInt("int1", 42);
editor.putLong("long1", 123456789L);
editor.putString("str1", "lolcat");
editor.apply();
// Export it
byte[] exported = preferenceBackupHelper.exportPreferences(preferences);
// Mess with the previous values
editor = preferences.edit();
editor.clear();
editor.putString("str2", "Shouldn't be there after restore");
editor.putBoolean("bool2", true);
editor.apply();
// Import it back
preferenceBackupHelper.importPreferences(exported, preferences);
assertFalse(preferences.contains("str2"));
assertTrue(preferences.getBoolean("bool1", false));
assertFalse(preferences.getBoolean("bool2", true));
assertEquals(3.14f, preferences.getFloat("flt1", 0.0f));
assertEquals(42, preferences.getInt("int1", 0));
assertEquals(123456789L, preferences.getLong("long1", 0));
assertEquals("lolcat", preferences.getString("str1", ""));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.database.MatrixCursor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
/**
* Tests for {@link DatabaseDumper}.
*
* @author Rodrigo Damazio
*/
public class DatabaseDumperTest extends TestCase {
/**
* This class is the same as {@link MatrixCursor}, except this class
* implements {@link #getBlob} ({@link MatrixCursor} leaves it
* unimplemented).
*/
private class BlobAwareMatrixCursor extends MatrixCursor {
public BlobAwareMatrixCursor(String[] columnNames) {
super(columnNames);
}
@Override public byte[] getBlob(int columnIndex) {
return getString(columnIndex).getBytes();
}
}
private static final String[] COLUMN_NAMES = {
"intCol", "longCol", "floatCol", "doubleCol", "stringCol", "boolCol", "blobCol"
};
private static final byte[] COLUMN_TYPES = {
ContentTypeIds.INT_TYPE_ID, ContentTypeIds.LONG_TYPE_ID,
ContentTypeIds.FLOAT_TYPE_ID, ContentTypeIds.DOUBLE_TYPE_ID,
ContentTypeIds.STRING_TYPE_ID, ContentTypeIds.BOOLEAN_TYPE_ID,
ContentTypeIds.BLOB_TYPE_ID
};
private static final String[][] FAKE_DATA = {
{ "42", "123456789", "3.1415", "2.72", "lolcat", "1", "blob" },
{ null, "123456789", "3.1415", "2.72", "lolcat", "1", "blob" },
{ "42", null, "3.1415", "2.72", "lolcat", "1", "blob" },
{ "42", "123456789", null, "2.72", "lolcat", "1", "blob" },
{ "42", "123456789", "3.1415", null, "lolcat", "1", "blob" },
{ "42", "123456789", "3.1415", "2.72", null, "1", "blob" },
{ "42", "123456789", "3.1415", "2.72", "lolcat", null, "blob" },
{ "42", "123456789", "3.1415", "2.72", "lolcat", "1", null },
};
private static final long[] EXPECTED_FIELD_SETS = {
0x7F, 0x7E, 0x7D, 0x7B, 0x77, 0x6F, 0x5F, 0x3F
};
private BlobAwareMatrixCursor cursor;
@Override
protected void setUp() throws Exception {
super.setUp();
// Add fake data to the cursor
cursor = new BlobAwareMatrixCursor(COLUMN_NAMES);
for (String[] row : FAKE_DATA) {
cursor.addRow(row);
}
}
public void testWriteAllRows_noNulls() throws Exception {
testWriteAllRows(false);
}
public void testWriteAllRows_withNulls() throws Exception {
testWriteAllRows(true);
}
private void testWriteAllRows(boolean hasNullFields) throws Exception {
// Dump it
DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, hasNullFields);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outStream );
dumper.writeAllRows(cursor, writer);
// Read the results
byte[] result = outStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(result);
DataInputStream reader = new DataInputStream(inputStream);
// Verify the header
assertHeader(reader);
// Verify the number of rows
assertEquals(FAKE_DATA.length, reader.readInt());
// Row 0 -- everything populated
assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 1 -- no int
assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong());
if (hasNullFields) reader.readInt();
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 2 -- no long
assertEquals(EXPECTED_FIELD_SETS[2], reader.readLong());
assertEquals(42, reader.readInt());
if (hasNullFields) reader.readLong();
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 3 -- no float
assertEquals(EXPECTED_FIELD_SETS[3], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
if (hasNullFields) reader.readFloat();
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 4 -- no double
assertEquals(EXPECTED_FIELD_SETS[4], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
if (hasNullFields) reader.readDouble();
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 5 -- no string
assertEquals(EXPECTED_FIELD_SETS[5], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
if (hasNullFields) reader.readUTF();
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 6 -- no boolean
assertEquals(EXPECTED_FIELD_SETS[6], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
if (hasNullFields) reader.readBoolean();
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 7 -- no blob
assertEquals(EXPECTED_FIELD_SETS[7], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
if (hasNullFields) {
int length = reader.readInt();
readBlob(reader, length);
}
}
public void testFewerRows() throws Exception {
// Dump only the first two rows
DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, false);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
DataOutputStream writer = new DataOutputStream(outStream);
dumper.writeHeaders(cursor, 2, writer);
cursor.moveToFirst();
dumper.writeOneRow(cursor, writer);
cursor.moveToNext();
dumper.writeOneRow(cursor, writer);
// Read the results
byte[] result = outStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(result);
DataInputStream reader = new DataInputStream(inputStream);
// Verify the header
assertHeader(reader);
// Verify the number of rows
assertEquals(2, reader.readInt());
// Row 0
assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong());
assertEquals(42, reader.readInt());
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
// Row 1
assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong());
// Null field not read
assertEquals(123456789L, reader.readLong());
assertEquals(3.1415f, reader.readFloat());
assertEquals(2.72, reader.readDouble());
assertEquals("lolcat", reader.readUTF());
assertTrue(reader.readBoolean());
assertEquals(4, reader.readInt());
assertEquals("blob", readBlob(reader, 4));
}
private void assertHeader(DataInputStream reader) throws IOException {
assertEquals(COLUMN_NAMES.length, reader.readInt());
for (int i = 0; i < COLUMN_NAMES.length; i++) {
assertEquals(COLUMN_NAMES[i], reader.readUTF());
assertEquals(COLUMN_TYPES[i], reader.readByte());
}
}
private String readBlob(InputStream reader, int length) throws Exception {
if (length == 0) {
return "";
}
byte[] blob = new byte[length];
assertEquals(length, reader.read(blob));
return new String(blob);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.maps;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.gdata.maps.MapsFeature;
import com.google.android.maps.GeoPoint;
import android.location.Location;
import java.util.ArrayList;
import junit.framework.TestCase;
/**
* Tests {@link SendMapsUtils}.
*
* @author Jimmy Shih
*/
public class SendMapsUtilsTest extends TestCase {
/**
* Tests {@link SendMapsUtils#getMapUrl(Track)} with null track.
*/
public void testGetMapUrl_null_track() {
assertEquals(null, SendMapsUtils.getMapUrl(null));
}
/**
* Tests {@link SendMapsUtils#getMapUrl(Track)} with null map id.
*/
public void testGetMapUrl_null_map_id() {
Track track = new Track();
track.setMapId(null);
assertEquals(null, SendMapsUtils.getMapUrl(track));
}
/**
* Tests {@link SendMapsUtils#getMapUrl(Track)} with a valid track.
*/
public void testGetMapUrl_valid_track() {
Track track = new Track();
track.setMapId("123");
assertEquals("https://maps.google.com/maps/ms?msa=0&msid=123", SendMapsUtils.getMapUrl(track));
}
/**
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
* GeoPoint)} with a title.
*/
public void testBuildMapsMarkerFeature_with_title() {
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
"name", "this\nmap\ndescription", "url", new GeoPoint(123, 456));
assertEquals(MapsFeature.MARKER, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("name", mapFeature.getTitle());
assertEquals("this<br>map<br>description", mapFeature.getDescription());
assertEquals("url", mapFeature.getIconUrl());
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
* GeoPoint)} with an empty title.
*/
public void testBuildMapsMarkerFeature_empty_title() {
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
"", "description", "url", new GeoPoint(123, 456));
assertEquals(MapsFeature.MARKER, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals("description", mapFeature.getDescription());
assertEquals("url", mapFeature.getIconUrl());
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
* GeoPoint)} with a null title.
*/
public void testBuildMapsMarkerFeature_null_title() {
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
null, "description", "url", new GeoPoint(123, 456));
assertEquals(MapsFeature.MARKER, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals("description", mapFeature.getDescription());
assertEquals("url", mapFeature.getIconUrl());
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
* title.
*/
public void testBuildMapsLineFeature_with_title() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
locations.add(location);
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("name", locations);
assertEquals(MapsFeature.LINE, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("name", mapFeature.getTitle());
assertEquals(0x80FF0000, mapFeature.getColor());
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with an
* empty title.
*/
public void testBuildMapsLineFeature_empty_title() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
locations.add(location);
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("", locations);
assertEquals(MapsFeature.LINE, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals(0x80FF0000, mapFeature.getColor());
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
* null title.
*/
public void testBuildMapsLineFeature_null_title() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
locations.add(location);
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature(null, locations);
assertEquals(MapsFeature.LINE, mapFeature.getType());
assertNotNull(mapFeature.getAndroidId());
assertEquals("-", mapFeature.getTitle());
assertEquals(0x80FF0000, mapFeature.getColor());
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
}
/**
* Test {@link SendMapsUtils#getGeoPoint(Location)}.
*/
public void testGeoPoint() {
Location location = new Location("test");
location.setLatitude(50);
location.setLongitude(100);
GeoPoint geoPoint = SendMapsUtils.getGeoPoint(location);
assertEquals(50000000, geoPoint.getLatitudeE6());
assertEquals(100000000, geoPoint.getLongitudeE6());
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.file;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.TracksColumns;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import com.google.android.apps.mytracks.io.file.GpxImporter;
import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.content.ContentUris;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.test.AndroidTestCase;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.SimpleTimeZone;
import javax.xml.parsers.ParserConfigurationException;
import org.easymock.Capture;
import org.easymock.IArgumentMatcher;
import org.xml.sax.SAXException;
/**
* Tests for the GPX importer.
*
* @author Steffen Horlacher
*/
public class GpxImporterTest extends AndroidTestCase {
private static final String TRACK_NAME = "blablub";
private static final String TRACK_DESC = "s'Laebe isch koi Schlotzer";
private static final String TRACK_LAT_1 = "48.768364";
private static final String TRACK_LON_1 = "9.177886";
private static final String TRACK_ELE_1 = "324.0";
private static final String TRACK_TIME_1 = "2010-04-22T18:21:00Z";
private static final String TRACK_LAT_2 = "48.768374";
private static final String TRACK_LON_2 = "9.177816";
private static final String TRACK_ELE_2 = "333.0";
private static final String TRACK_TIME_2 = "2010-04-22T18:21:50.123";
private static final SimpleDateFormat DATE_FORMAT1 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
private static final SimpleDateFormat DATE_FORMAT2 =
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
static {
// We can't omit the timezones in the test, otherwise it'll use the local
// timezone and fail depending on where the test runner is.
SimpleTimeZone utc = new SimpleTimeZone(0, "UTC");
DATE_FORMAT1.setTimeZone(utc);
DATE_FORMAT2.setTimeZone(utc);
}
// TODO: use real files from different sources with more track points.
private static final String VALID_TEST_GPX = "<gpx><trk><name><![CDATA["
+ TRACK_NAME + "]]></name><desc><![CDATA[" + TRACK_DESC
+ "]]></desc><trkseg>" + "<trkpt lat=\"" + TRACK_LAT_1 + "\" lon=\""
+ TRACK_LON_1 + "\"><ele>" + TRACK_ELE_1 + "</ele><time>" + TRACK_TIME_1
+ "</time></trkpt> +" + "<trkpt lat=\"" + TRACK_LAT_2 + "\" lon=\""
+ TRACK_LON_2 + "\"><ele>" + TRACK_ELE_2 + "</ele><time>" + TRACK_TIME_2
+ "</time></trkpt>" + "</trkseg></trk></gpx>";
// invalid xml
private static final String INVALID_XML_TEST_GPX = VALID_TEST_GPX.substring(
0, VALID_TEST_GPX.length() - 50);
private static final String INVALID_LOCATION_TEST_GPX = VALID_TEST_GPX
.replaceAll(TRACK_LAT_1, "1000.0");
private static final String INVALID_TIME_TEST_GPX = VALID_TEST_GPX
.replaceAll(TRACK_TIME_1, "invalid");
private static final String INVALID_ALTITUDE_TEST_GPX = VALID_TEST_GPX
.replaceAll(TRACK_ELE_1, "invalid");
private static final String INVALID_LATITUDE_TEST_GPX = VALID_TEST_GPX
.replaceAll(TRACK_LAT_1, "invalid");
private static final String INVALID_LONGITUDE_TEST_GPX = VALID_TEST_GPX
.replaceAll(TRACK_LON_1, "invalid");
private static final long TRACK_ID = 1;
private static final long TRACK_POINT_ID_1 = 1;
private static final long TRACK_POINT_ID_2 = 2;
private static final Uri TRACK_ID_URI = ContentUris.appendId(
TracksColumns.CONTENT_URI.buildUpon(), TRACK_ID).build();
private MyTracksProviderUtils providerUtils;
private Factory oldProviderUtilsFactory;
@UsesMocks(MyTracksProviderUtils.class)
@Override
protected void setUp() throws Exception {
super.setUp();
providerUtils = AndroidMock.createMock(MyTracksProviderUtils.class);
oldProviderUtilsFactory =
TestingProviderUtilsFactory.installWithInstance(providerUtils);
}
@Override
protected void tearDown() throws Exception {
TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory);
super.tearDown();
}
/**
* Test import success.
*/
public void testImportSuccess() throws Exception {
Capture<Track> trackParam = new Capture<Track>();
Location loc1 = new Location(LocationManager.GPS_PROVIDER);
loc1.setTime(DATE_FORMAT2.parse(TRACK_TIME_1).getTime());
loc1.setLatitude(Double.parseDouble(TRACK_LAT_1));
loc1.setLongitude(Double.parseDouble(TRACK_LON_1));
loc1.setAltitude(Double.parseDouble(TRACK_ELE_1));
Location loc2 = new Location(LocationManager.GPS_PROVIDER);
loc2.setTime(DATE_FORMAT1.parse(TRACK_TIME_2).getTime());
loc2.setLatitude(Double.parseDouble(TRACK_LAT_2));
loc2.setLongitude(Double.parseDouble(TRACK_LON_2));
loc2.setAltitude(Double.parseDouble(TRACK_ELE_2));
expect(providerUtils.insertTrack(AndroidMock.capture(trackParam)))
.andReturn(TRACK_ID_URI);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2);
// A flush happens after the first insertion to get the starting point ID,
// which is why we get two calls
expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc1),
eq(1), eq(TRACK_ID))).andReturn(1);
expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc2),
eq(1), eq(TRACK_ID))).andReturn(1);
providerUtils.updateTrack(AndroidMock.capture(trackParam));
AndroidMock.replay(providerUtils);
InputStream is = new ByteArrayInputStream(VALID_TEST_GPX.getBytes());
GpxImporter.importGPXFile(is, providerUtils);
AndroidMock.verify(providerUtils);
// verify track parameter
Track track = trackParam.getValue();
assertEquals(TRACK_NAME, track.getName());
assertEquals(TRACK_DESC, track.getDescription());
assertEquals(DATE_FORMAT2.parse(TRACK_TIME_1).getTime(), track.getStatistics()
.getStartTime());
assertNotSame(-1, track.getStartId());
assertNotSame(-1, track.getStopId());
}
/**
* Test with invalid location - track should be deleted.
*/
public void testImportLocationFailure() throws ParserConfigurationException, IOException {
testInvalidXML(INVALID_LOCATION_TEST_GPX);
}
/**
* Test with invalid time - track should be deleted.
*/
public void testImportTimeFailure() throws ParserConfigurationException, IOException {
testInvalidXML(INVALID_TIME_TEST_GPX);
}
/**
* Test with invalid xml - track should be deleted.
*/
public void testImportXMLFailure() throws ParserConfigurationException, IOException {
testInvalidXML(INVALID_XML_TEST_GPX);
}
/**
* Test with invalid altitude - track should be deleted.
*/
public void testImportInvalidAltitude() throws ParserConfigurationException, IOException {
testInvalidXML(INVALID_ALTITUDE_TEST_GPX);
}
/**
* Test with invalid latitude - track should be deleted.
*/
public void testImportInvalidLatitude() throws ParserConfigurationException, IOException {
testInvalidXML(INVALID_LATITUDE_TEST_GPX);
}
/**
* Test with invalid longitude - track should be deleted.
*/
public void testImportInvalidLongitude() throws ParserConfigurationException, IOException {
testInvalidXML(INVALID_LONGITUDE_TEST_GPX);
}
private void testInvalidXML(String xml) throws ParserConfigurationException,
IOException {
expect(providerUtils.insertTrack((Track) AndroidMock.anyObject()))
.andReturn(TRACK_ID_URI);
expect(providerUtils.bulkInsertTrackPoints((Location[]) AndroidMock.anyObject(),
AndroidMock.anyInt(), AndroidMock.anyLong())).andStubReturn(1);
expect(providerUtils.getLastLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1);
providerUtils.deleteTrack(TRACK_ID);
AndroidMock.replay(providerUtils);
InputStream is = new ByteArrayInputStream(xml.getBytes());
try {
GpxImporter.importGPXFile(is, providerUtils);
} catch (SAXException e) {
// expected exception
}
AndroidMock.verify(providerUtils);
}
/**
* Workaround because of capture bug 2617107 in easymock:
* http://sourceforge.net
* /tracker/?func=detail&aid=2617107&group_id=82958&atid=567837
*/
private static class LocationsMatcher implements IArgumentMatcher {
private final Location[] matchLocs;
private LocationsMatcher(Location[] expected) {
this.matchLocs = expected;
}
public static Location[] eqLoc(Location[] expected) {
IArgumentMatcher matcher = new LocationsMatcher(expected);
AndroidMock.reportMatcher(matcher);
return null;
}
public static Location[] eqLoc(Location expected) {
return eqLoc(new Location[] { expected});
}
@Override
public void appendTo(StringBuffer buf) {
buf.append("eqLoc(").append(Arrays.toString(matchLocs)).append(")");
}
@Override
public boolean matches(Object obj) {
if (! (obj instanceof Location[])) { return false; }
Location[] locs = (Location[]) obj;
if (locs.length < matchLocs.length) { return false; }
// Only check the first elements (those that will be taken into account)
for (int i = 0; i < matchLocs.length; i++) {
if (!locationsMatch(locs[i], matchLocs[i])) {
return false;
}
}
return true;
}
private boolean locationsMatch(Location loc1, Location loc2) {
return (loc1.getTime() == loc2.getTime()) &&
(loc1.getLatitude() == loc2.getLatitude()) &&
(loc1.getLongitude() == loc2.getLongitude()) &&
(loc1.getAltitude() == loc2.getAltitude());
}
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file;
import com.google.android.apps.mytracks.content.DescriptionGenerator;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import android.location.Location;
import java.util.List;
import java.util.Vector;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Tests for the KML track exporter.
*
* @author Rodrigo Damazio
*/
public class KmlTrackWriterTest extends TrackFormatWriterTest {
private static final String FULL_TRACK_DESCRIPTION = "full track description";
/**
* A fake version of {@link DescriptionGenerator} which returns a fixed track
* description, thus not depending on the context.
*/
private class MockDescriptionGenerator implements DescriptionGenerator {
@Override
public String generateTrackDescription(
Track trackToDescribe, Vector<Double> distances, Vector<Double> elevations) {
assertSame(KmlTrackWriterTest.super.track, trackToDescribe);
assertTrue(distances.isEmpty());
assertTrue(elevations.isEmpty());
return FULL_TRACK_DESCRIPTION;
}
@Override
public String generateWaypointDescription(Waypoint waypoint) {
return null;
}
}
public void testXmlOutput() throws Exception {
KmlTrackWriter writer = new KmlTrackWriter(new MockDescriptionGenerator());
String result = writeTrack(writer);
Document doc = parseXmlDocument(result);
Element kmlTag = getChildElement(doc, "kml");
Element docTag = getChildElement(kmlTag, "Document");
assertEquals(TRACK_NAME, getChildTextValue(docTag, "name"));
assertEquals(TRACK_DESCRIPTION, getChildTextValue(docTag, "description"));
// There are 5 placemarks - start, segments, end, waypoint 1, waypoint 2
List<Element> placemarkTags = getChildElements(docTag, "Placemark", 5);
assertTagIsPlacemark(placemarkTags.get(0),
"(Start)", TRACK_DESCRIPTION, location1);
assertTagIsPlacemark(placemarkTags.get(2),
"(End)", FULL_TRACK_DESCRIPTION, location4);
assertTagIsPlacemark(placemarkTags.get(3),
WAYPOINT1_NAME, WAYPOINT1_DESCRIPTION, location2);
assertTagIsPlacemark(placemarkTags.get(4),
WAYPOINT2_NAME, WAYPOINT2_DESCRIPTION, location3);
Element trackPlacemarkTag = placemarkTags.get(1);
assertEquals(TRACK_NAME, getChildTextValue(trackPlacemarkTag, "name"));
assertEquals(TRACK_DESCRIPTION,
getChildTextValue(trackPlacemarkTag, "description"));
Element geometryTag = getChildElement(trackPlacemarkTag, "MultiGeometry");
List<Element> segmentTags = getChildElements(geometryTag, "LineString", 2);
assertTagHasPoints(segmentTags.get(0), location1, location2);
assertTagHasPoints(segmentTags.get(1), location3, location4);
}
/**
* Asserts that the given XML tag is a placemark with the given properties.
*
* @param tag the tag to analyze
* @param name the expected name for the placemark
* @param description the expected description for the placemark
* @param location the expected location of the placemark
*/
private void assertTagIsPlacemark(Element tag, String name,
String description, Location location) {
assertEquals(name, getChildTextValue(tag, "name"));
assertEquals(description, getChildTextValue(tag, "description"));
Element pointTag = getChildElement(tag, "Point");
String expectedCoords =
location.getLongitude() + "," + location.getLatitude();
String actualCoords = getChildTextValue(pointTag, "coordinates");
assertEquals(expectedCoords, actualCoords);
}
/**
* Asserts that the given tag has a "coordinates" subtag with the given
* locations.
*
* @param tag the tag to analyze
* @param locs the locations to expect in the coordinates
*/
private void assertTagHasPoints(Element tag, Location... locs) {
StringBuilder expectedBuilder = new StringBuilder();
for (Location loc : locs) {
expectedBuilder.append(loc.getLongitude());
expectedBuilder.append(',');
expectedBuilder.append(loc.getLatitude());
expectedBuilder.append(',');
expectedBuilder.append(loc.getAltitude());
expectedBuilder.append(' ');
}
String expectedCoordinates = expectedBuilder.toString().trim();
String actualCoordinates = getChildTextValue(tag, "coordinates").trim();
assertEquals(expectedCoordinates, actualCoordinates);
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import android.test.AndroidTestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Base class for track format writer tests, which sets up a fake track and
* gives auxiliary methods for verifying XML output.
*
* @author Rodrigo Damazio
*/
public abstract class TrackFormatWriterTest extends AndroidTestCase {
// All the user-provided strings have "]]>" to ensure that proper escaping is
// being done.
protected static final String TRACK_NAME = "Home]]>";
protected static final String TRACK_DESCRIPTION = "The long ]]> journey home";
protected static final String WAYPOINT1_NAME = "point]]>1";
protected static final String WAYPOINT1_DESCRIPTION = "point 1]]>description";
protected static final String WAYPOINT2_NAME = "point]]>2";
protected static final String WAYPOINT2_DESCRIPTION = "point 2]]>description";
private static final int BUFFER_SIZE = 10240;
protected static final long TRACK_ID = 12345L;
protected Track track;
protected MyTracksLocation location1, location2, location3, location4;
protected Waypoint wp1, wp2;
@Override
protected void setUp() throws Exception {
super.setUp();
track = new Track();
track.setId(TRACK_ID);
track.setName(TRACK_NAME);
track.setDescription(TRACK_DESCRIPTION);
location1 = new MyTracksLocation("mock");
location2 = new MyTracksLocation("mock");
location3 = new MyTracksLocation("mock");
location4 = new MyTracksLocation("mock");
populateLocations(location1, location2, location3, location4);
wp1 = new Waypoint();
wp2 = new Waypoint();
wp1.setLocation(location2);
wp1.setName(WAYPOINT1_NAME);
wp1.setDescription(WAYPOINT1_DESCRIPTION);
wp2.setLocation(location3);
wp2.setName(WAYPOINT2_NAME);
wp2.setDescription(WAYPOINT2_DESCRIPTION);
}
/**
* Populates the given locations with coordinates and time.
*/
protected void populateLocations(MyTracksLocation... locs) {
for (int i = 0; i < locs.length; i++) {
MyTracksLocation loc = locs[i];
loc.setAltitude(i * 5000000);
loc.setLatitude(i);
loc.setLongitude(-i);
loc.setTime(10000000 + i * 1000);
Sensor.SensorData.Builder hr = Sensor.SensorData.newBuilder()
.setValue(100 + i)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder()
.setValue(400 + i)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorDataSet sds =
Sensor.SensorDataSet.newBuilder().setHeartRate(hr.build())
.setPower(power)
.build();
loc.setSensorData(sds);
}
}
/**
* Makes the right sequence of calls to the writer in order to write the fake
* track in {@link #track}.
*
* @param writer the writer to write to
* @return the written contents
*/
protected String writeTrack(TrackFormatWriter writer) throws Exception {
OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE);
writer.prepare(track, output);
writer.writeHeader();
writer.writeBeginTrack(location1);
writer.writeOpenSegment();
writer.writeLocation(location1);
writer.writeLocation(location2);
writer.writeCloseSegment();
writer.writeOpenSegment();
writer.writeLocation(location3);
writer.writeLocation(location4);
writer.writeCloseSegment();
writer.writeEndTrack(location4);
writer.writeWaypoint(wp1);
writer.writeWaypoint(wp2);
writer.writeFooter();
writer.close();
return output.toString();
}
/**
* Gets the text data contained inside a tag.
*
* @param parent the parent of the tag containing the text
* @param elementName the name of the tag containing the text
* @return the text contents
*/
protected String getChildTextValue(Element parent, String elementName) {
Element child = getChildElement(parent, elementName);
assertTrue(child.hasChildNodes());
NodeList children = child.getChildNodes();
int length = children.getLength();
assertTrue(length > 0);
// The children may be a sucession of text elements, just concatenate them
String result = "";
for (int i = 0; i < length; i++) {
Text textNode = (Text) children.item(i);
result += textNode.getNodeValue();
}
return result;
}
/**
* Returns all child elements of a given parent which have the given name.
*
* @param parent the parent to get children from
* @param elementName the element name to look for
* @param expectedChildren the number of children we're expected to find
* @return a list of the found elements
*/
protected List<Element> getChildElements(Node parent, String elementName,
int expectedChildren) {
assertTrue(parent.hasChildNodes());
NodeList children = parent.getChildNodes();
int length = children.getLength();
List<Element> result = new ArrayList<Element>();
for (int i = 0; i < length; i++) {
Node childNode = children.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE
&& childNode.getNodeName().equalsIgnoreCase(elementName)) {
result.add((Element) childNode);
}
}
assertTrue(children.toString(), result.size() == expectedChildren);
return result;
}
/**
* Returns the single child element of the given parent with the given type.
*
* @param parent the parent to get a child from
* @param elementName the name of the child to look for
* @return the child element
*/
protected Element getChildElement(Node parent, String elementName) {
return getChildElements(parent, elementName, 1).get(0);
}
/**
* Parses the given XML contents and returns a DOM {@link Document} for it.
*/
protected Document parseXmlDocument(String contents)
throws FactoryConfigurationError, ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setCoalescing(true);
// TODO: Somehow do XML validation on Android
// builderFactory.setValidating(true);
builderFactory.setNamespaceAware(true);
builderFactory.setIgnoringComments(true);
builderFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(
new InputSource(new StringReader(contents)));
return doc;
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.util.FileUtils;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Tests for the GPX track exporter.
*
* @author Sandor Dornbush
*/
public class TcxTrackWriterTest extends TrackFormatWriterTest {
public void testXmlOutput() throws Exception {
TrackFormatWriter writer = new TcxTrackWriter(getContext());
String result = writeTrack(writer);
Document doc = parseXmlDocument(result);
Element root = getChildElement(doc, "TrainingCenterDatabase");
Element activitiesTag = getChildElement(root, "Activities");
Element activityTag = getChildElement(activitiesTag, "Activity");
Element lapTag = getChildElement(activityTag, "Lap");
List<Element> segmentTags = getChildElements(lapTag, "Track", 2);
Element segment1Tag = segmentTags.get(0);
Element segment2Tag = segmentTags.get(1);
List<Element> seg1PointTags = getChildElements(segment1Tag, "Trackpoint", 2);
List<Element> seg2PointTags = getChildElements(segment2Tag, "Trackpoint", 2);
assertTagsMatchPoints(seg1PointTags, location1, location2);
assertTagsMatchPoints(seg2PointTags, location3, location4);
}
/**
* Asserts that the given tags describe the given points, in the same order.
*/
private void assertTagsMatchPoints(List<Element> tags, MyTracksLocation... locs) {
assertEquals(locs.length, tags.size());
for (int i = 0; i < locs.length; i++) {
Element tag = tags.get(i);
MyTracksLocation loc = locs[i];
assertTagMatchesLocation(tag, loc);
}
}
/**
* Asserts that the given tag describes the given location.
*/
private void assertTagMatchesLocation(Element tag, MyTracksLocation loc) {
Element posTag = getChildElement(tag, "Position");
assertEquals(Double.toString(loc.getLatitude()),
getChildTextValue(posTag, "LatitudeDegrees"));
assertEquals(Double.toString(loc.getLongitude()),
getChildTextValue(posTag, "LongitudeDegrees"));
assertEquals(FileUtils.FILE_TIMESTAMP_FORMAT.format(loc.getTime()),
getChildTextValue(tag, "Time"));
assertEquals(Double.toString(loc.getAltitude()),
getChildTextValue(tag, "AltitudeMeters"));
assertTrue(loc.getSensorDataSet() != null);
Sensor.SensorDataSet sds = loc.getSensorDataSet();
List<Element> bpm = getChildElements(tag, "HeartRateBpm", 1);
assertEquals(Integer.toString(sds.getHeartRate().getValue()),
getChildTextValue(bpm.get(0), "Value"));
List<Element> ext = getChildElements(tag, "Extensions", 1);
List<Element> tpx = getChildElements(ext.get(0), "TPX", 1);
assertEquals(Integer.toString(sds.getPower().getValue()),
getChildTextValue(tpx.get(0), "Watts"));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.file;
import java.io.File;
/**
* A simple, fake {@link TrackWriter} subclass with all methods mocked out.
* Tests are expected to override {@link #writeTrack} and/or
* {@link #writeTrackAsync}, at the very least.
*
* @author Matthew Simmons
*
*/
public class MockTrackWriter implements TrackWriter {
public OnCompletionListener onCompletionListener;
public OnWriteListener onWriteListener;
@Override
public void setOnCompletionListener(OnCompletionListener onCompletionListener) {
this.onCompletionListener = onCompletionListener;
}
@Override
public void setOnWriteListener(OnWriteListener onWriteListener) {
this.onWriteListener = onWriteListener;
}
@Override
public void setDirectory(File directory) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public String getAbsolutePath() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void writeTrackAsync() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void writeTrack() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void stopWriteTrack() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean wasSuccess() {
return false;
}
@Override
public int getErrorMessage() {
return 0;
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file;
import com.google.android.apps.mytracks.io.file.GpxTrackWriter;
import com.google.android.apps.mytracks.io.file.TrackFormatWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.util.List;
/**
* Tests for the GPX track exporter.
*
* @author Rodrigo Damazio
*/
public class GpxTrackWriterTest extends TrackFormatWriterTest {
public void testXmlOutput() throws Exception {
TrackFormatWriter writer = new GpxTrackWriter();
String result = writeTrack(writer);
Document doc = parseXmlDocument(result);
Element gpxTag = getChildElement(doc, "gpx");
Element trackTag = getChildElement(gpxTag, "trk");
assertEquals(TRACK_NAME, getChildTextValue(trackTag, "name"));
assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackTag, "desc"));
assertEquals(Long.toString(TRACK_ID),
getChildTextValue(trackTag, "number"));
List<Element> segmentTags = getChildElements(trackTag, "trkseg", 2);
List<Element> segPointTags = getChildElements(segmentTags.get(0), "trkpt", 2);
assertTagMatchesLocation(segPointTags.get(0),
"0", "0", "1970-01-01T02:46:40Z", "0");
assertTagMatchesLocation(segPointTags.get(1),
"1", "-1", "1970-01-01T02:46:41Z", "5000000");
segPointTags = getChildElements(segmentTags.get(1), "trkpt", 2);
assertTagMatchesLocation(segPointTags.get(0),
"2", "-2", "1970-01-01T02:46:42Z", "10000000");
assertTagMatchesLocation(segPointTags.get(1),
"3", "-3", "1970-01-01T02:46:43Z", "15000000");
List<Element> waypointTags = getChildElements(gpxTag, "wpt", 2);
Element wptTag = waypointTags.get(0);
assertEquals(WAYPOINT1_NAME, getChildTextValue(wptTag, "name"));
assertEquals(WAYPOINT1_DESCRIPTION, getChildTextValue(wptTag, "desc"));
assertTagMatchesLocation(wptTag,
"1", "-1", "1970-01-01T02:46:41Z", "5000000");
wptTag = waypointTags.get(1);
assertEquals(WAYPOINT2_NAME, getChildTextValue(wptTag, "name"));
assertEquals(WAYPOINT2_DESCRIPTION, getChildTextValue(wptTag, "desc"));
assertTagMatchesLocation(wptTag,
"2", "-2", "1970-01-01T02:46:42Z", "10000000");
}
/**
* Asserts that the given tag describes the location given by the
* Strings lat, lon, time, and ele.
*/
private void assertTagMatchesLocation(Element tag, String lat,
String lon, String time, String ele) {
assertEquals(lat, tag.getAttribute("lat"));
assertEquals(lon, tag.getAttribute("lon"));
assertEquals(time, getChildTextValue(tag, "time"));
assertEquals(ele, getChildTextValue(tag, "ele"));
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file;
/**
* Tests for the CSV track exporter.
*
* @author Rodrigo Damazio
*/
public class CsvTrackWriterTest extends TrackFormatWriterTest {
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.file;
import android.app.ProgressDialog;
import android.test.ActivityInstrumentationTestCase2;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
/**
* Tests {@link WriteProgressController}.
*
* @author Matthew Simmons
*/
public class WriteProgressControllerTest extends ActivityInstrumentationTestCase2<SaveActivity> {
public WriteProgressControllerTest() {
super(SaveActivity.class);
}
private static void assertProgress(ProgressDialog dialog, int expectedProgress,
int expectedMax) {
assertEquals(expectedProgress, dialog.getProgress());
assertEquals(expectedMax, dialog.getMax());
}
public void testSimple() throws Exception {
final AtomicReference<ProgressDialog> dialogRef = new AtomicReference<ProgressDialog>();
final AtomicReference<Boolean> controllerDoneRef = new AtomicReference<Boolean>();
final Semaphore writerDone = new Semaphore(0);
TrackWriter mockWriter = new MockTrackWriter() {
@Override
public void writeTrackAsync() {
onWriteListener.onWrite(1000, 10000);
assertProgress(dialogRef.get(), 1000, 10000);
onCompletionListener.onComplete();
writerDone.release();
}
};
final WriteProgressController controller = new WriteProgressController(
getActivity(), mockWriter, SaveActivity.PROGRESS_DIALOG);
controller.setOnCompletionListener(new WriteProgressController.OnCompletionListener() {
@Override
public void onComplete() {
controllerDoneRef.set(true);
}
});
/*
* The WriteProgressController constructor calls the mockWriter's
* setOnCompletionListener method with a listener that dismisses the
* progress dialog. However, this unit test only tests the
* WriteProgressController and doesn't actually show any progress dialog.
* Thus after the WriteProgressController is setup, we need to call the
* mockWriter's setOnCompletionListener method again with an listener that
* doesn't dismiss dialog.
*/
mockWriter.setOnCompletionListener(new TrackWriter.OnCompletionListener() {
@Override
public void onComplete() {
controller.getOnCompletionListener().onComplete();
}
});
dialogRef.set(controller.createProgressDialog());
controller.startWrite();
// wait for the writer to finish
writerDone.acquire();
assertTrue(controllerDoneRef.get());
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file;
import static org.easymock.EasyMock.expect;
import com.google.android.apps.mytracks.content.MyTracksProvider;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.easymock.IArgumentMatcher;
import org.easymock.IMocksControl;
/**
* Tests for the track writer.
*
* @author Rodrigo Damazio
*/
public class TrackWriterTest extends AndroidTestCase {
/**
* {@link TrackWriterImpl} subclass which mocks out methods called from
* {@link TrackWriterImpl#openFile}.
*/
private static final class OpenFileTrackWriter extends TrackWriterImpl {
private final ByteArrayOutputStream stream;
private final boolean canWrite;
/**
* Constructor.
*
* @param stream the stream to return from
* {@link TrackWriterImpl#newOutputStream}, or null to throw a
* {@link FileNotFoundException}
* @param canWrite the value that {@link TrackWriterImpl#canWriteFile} will
* return
*/
private OpenFileTrackWriter(Context context,
MyTracksProviderUtils providerUtils, Track track,
TrackFormatWriter writer, ByteArrayOutputStream stream,
boolean canWrite) {
super(context, providerUtils, track, writer);
this.stream = stream;
this.canWrite = canWrite;
// The directory is set in the canWriteFile. However, this class
// overwrites canWriteFile, thus needs to set it.
setDirectory(new File("/"));
}
@Override
protected boolean canWriteFile() {
return canWrite;
}
@Override
protected OutputStream newOutputStream(String fileName)
throws FileNotFoundException {
assertEquals(FULL_TRACK_NAME, fileName);
if (stream == null) {
throw new FileNotFoundException();
}
return stream;
}
}
/**
* {@link TrackWriterImpl} subclass which mocks out methods called from
* {@link TrackWriterImpl#writeTrack}.
*/
private final class WriteTracksTrackWriter extends TrackWriterImpl {
private final boolean openResult;
/**
* Constructor.
*
* @param openResult the return value for {@link TrackWriterImpl#openFile}
*/
private WriteTracksTrackWriter(Context context,
MyTracksProviderUtils providerUtils, Track track,
TrackFormatWriter writer, boolean openResult) {
super(context, providerUtils, track, writer);
this.openResult = openResult;
}
@Override
protected boolean openFile() {
openFileCalls++;
return openResult;
}
@Override
void writeDocument() {
writeDocumentCalls++;
}
@Override
protected void runOnUiThread(Runnable runnable) {
runnable.run();
}
}
private static final long TRACK_ID = 1234567L;
private static final String EXTENSION = "ext";
private static final String TRACK_NAME = "Swimming across the pacific";
private static final String FULL_TRACK_NAME =
"Swimming across the pacific.ext";
private Track track;
private TrackFormatWriter formatWriter;
private TrackWriterImpl writer;
private IMocksControl mocksControl;
private MyTracksProviderUtils providerUtils;
private Factory oldProviderUtilsFactory;
// State used in specific tests
private int writeDocumentCalls;
private int openFileCalls;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
Context context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils);
mocksControl = EasyMock.createStrictControl();
formatWriter = mocksControl.createMock(TrackFormatWriter.class);
expect(formatWriter.getExtension()).andStubReturn(EXTENSION);
track = new Track();
track.setName(TRACK_NAME);
track.setId(TRACK_ID);
}
@Override
protected void tearDown() throws Exception {
TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory);
super.tearDown();
}
public void testWriteTrack() {
writer = new WriteTracksTrackWriter(getContext(), providerUtils, track,
formatWriter, true);
// Expect the completion listener to be run
TrackWriter.OnCompletionListener completionListener
= mocksControl.createMock(TrackWriter.OnCompletionListener.class);
completionListener.onComplete();
mocksControl.replay();
writer.setOnCompletionListener(completionListener);
writer.writeTrack();
assertEquals(1, writeDocumentCalls);
assertEquals(1, openFileCalls);
mocksControl.verify();
}
public void testWriteTrack_cancelled() throws Exception {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
writer = new OpenFileTrackWriter(
getContext(), providerUtils, track, formatWriter, stream, true);
formatWriter.prepare(track, stream);
final Location[] locs = {
new Location("fake0"),
new Location("fake1"),
};
fillLocations(locs);
assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID));
formatWriter.writeHeader();
formatWriter.writeBeginTrack(locEq(locs[0]));
formatWriter.writeOpenSegment();
formatWriter.writeLocation(locEq(locs[0]));
//EasyMock.expectLastCall().andThrow(new InterruptedException());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
throw new InterruptedException();
}
});
mocksControl.replay();
writer.writeTrack();
mocksControl.verify();
assertFalse(writer.wasSuccess());
assertEquals(R.string.sd_card_canceled, writer.getErrorMessage());
}
public void testWriteTrack_openFails() {
writer = new WriteTracksTrackWriter(getContext(), providerUtils, track,
formatWriter, false);
// Expect the completion listener to be run
TrackWriter.OnCompletionListener completionListener
= mocksControl.createMock(TrackWriter.OnCompletionListener.class);
completionListener.onComplete();
mocksControl.replay();
writer.setOnCompletionListener(completionListener);
writer.writeTrack();
assertEquals(0, writeDocumentCalls);
assertEquals(1, openFileCalls);
mocksControl.verify();
}
public void testOpenFile() {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
writer = new OpenFileTrackWriter(
getContext(), providerUtils, track, formatWriter, stream, true);
formatWriter.prepare(track, stream);
mocksControl.replay();
assertTrue(writer.openFile());
mocksControl.verify();
}
public void testOpenFile_cantWrite() {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
writer = new OpenFileTrackWriter(
getContext(), providerUtils, track, formatWriter, stream, false);
mocksControl.replay();
assertFalse(writer.openFile());
mocksControl.verify();
}
public void testOpenFile_streamError() {
writer = new OpenFileTrackWriter(
getContext(), providerUtils, track, formatWriter, null, true);
mocksControl.replay();
assertFalse(writer.openFile());
mocksControl.verify();
}
public void testWriteDocument_emptyTrack() throws Exception {
writer = new TrackWriterImpl(getContext(), providerUtils, track, formatWriter);
// Set expected mock behavior
formatWriter.writeHeader();
formatWriter.writeFooter();
formatWriter.close();
mocksControl.replay();
writer.writeDocument();
assertTrue(writer.wasSuccess());
mocksControl.verify();
}
public void testWriteDocument() throws Exception {
writer = new TrackWriterImpl(getContext(), providerUtils, track, formatWriter);
final Location[] locs = {
new Location("fake0"),
new Location("fake1"),
new Location("fake2"),
new Location("fake3"),
new Location("fake4"),
new Location("fake5")
};
Waypoint[] wps = { new Waypoint(), new Waypoint(), new Waypoint() };
// Fill locations with valid values
fillLocations(locs);
// Make location 3 invalid
locs[2].setLatitude(100);
assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID));
for (int i = 0; i < wps.length; ++i) {
Waypoint wpt = wps[i];
wpt.setTrackId(TRACK_ID);
assertNotNull(providerUtils.insertWaypoint(wpt));
wpt.setId(i + 1);
}
formatWriter.writeHeader();
// Expect reading/writing of the waypoints (except the first)
formatWriter.writeWaypoint(wptEq(wps[1]));
formatWriter.writeWaypoint(wptEq(wps[2]));
// Begin the track
formatWriter.writeBeginTrack(locEq(locs[0]));
// Write locations 1-2
formatWriter.writeOpenSegment();
formatWriter.writeLocation(locEq(locs[0]));
formatWriter.writeLocation(locEq(locs[1]));
formatWriter.writeCloseSegment();
// Location 3 is not written - it's invalid
// Write locations 4-6
formatWriter.writeOpenSegment();
formatWriter.writeLocation(locEq(locs[3]));
formatWriter.writeLocation(locEq(locs[4]));
formatWriter.writeLocation(locEq(locs[5]));
formatWriter.writeCloseSegment();
// End the track
formatWriter.writeEndTrack(locEq(locs[5]));
formatWriter.writeFooter();
formatWriter.close();
mocksControl.replay();
writer.writeDocument();
assertTrue(writer.wasSuccess());
mocksControl.verify();
}
private static Waypoint wptEq(final Waypoint wpt) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object wptObj2) {
if (wptObj2 == null || wpt == null) return wpt == wptObj2;
Waypoint wpt2 = (Waypoint) wptObj2;
return wpt.getId() == wpt2.getId();
}
@Override
public void appendTo(StringBuffer buffer) {
buffer.append("wptEq(");
buffer.append(wpt);
buffer.append(")");
}
});
return null;
}
private static Location locEq(final Location loc) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object locObj2) {
if (locObj2 == null || loc == null) return loc == locObj2;
Location loc2 = (Location) locObj2;
return loc.hasAccuracy() == loc2.hasAccuracy()
&& (!loc.hasAccuracy() || loc.getAccuracy() == loc2.getAccuracy())
&& loc.hasAltitude() == loc2.hasAltitude()
&& (!loc.hasAltitude() || loc.getAltitude() == loc2.getAltitude())
&& loc.hasBearing() == loc2.hasBearing()
&& (!loc.hasBearing() || loc.getBearing() == loc2.getBearing())
&& loc.hasSpeed() == loc2.hasSpeed()
&& (!loc.hasSpeed() || loc.getSpeed() == loc2.getSpeed())
&& loc.getLatitude() == loc2.getLatitude()
&& loc.getLongitude() == loc2.getLongitude()
&& loc.getTime() == loc2.getTime();
}
@Override
public void appendTo(StringBuffer buffer) {
buffer.append("locEq(");
buffer.append(loc);
buffer.append(")");
}
});
return null;
}
private void fillLocations(Location... locs) {
assertTrue(locs.length < 90);
for (int i = 0; i < locs.length; i++) {
Location location = locs[i];
location.setLatitude(i + 1);
location.setLongitude(i + 1);
location.setTime(i + 1000);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.io.fusiontables;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.location.Location;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import junit.framework.TestCase;
/**
* Tests {@link SendFusionTablesUtils}.
*
* @author Jimmy Shih
*/
public class SendFusionTablesUtilsTest extends TestCase {
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null track.
*/
public void testGetMapUrl_null_track() {
assertEquals(null, SendFusionTablesUtils.getMapUrl(null));
}
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null table id.
*/
public void testGetMapUrl_null_table_id() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6);
track.setStatistics(stats);
track.setTableId(null);
assertEquals(null, SendFusionTablesUtils.getMapUrl(track));
}
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null stats.
*/
public void testGetMapUrl_null_stats() {
Track track = new Track();
track.setStatistics(null);
track.setTableId("123");
assertEquals(null, SendFusionTablesUtils.getMapUrl(track));
}
/**
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with a valid track.
*/
public void testGetMapUrl_valid_track() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6);
track.setStatistics(stats);
track.setTableId("123");
assertEquals(
"https://www.google.com/fusiontables/embedviz?"
+ "viz=MAP&q=select+col0,+col1,+col2,+col3+from+123+&h=false&lat=7.500000&lng=75.000000"
+ "&z=15&t=1&l=col2", SendFusionTablesUtils.getMapUrl(track));
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* no value.
*/
public void testFormatSqlValues_no_value() {
assertEquals("()", SendFusionTablesUtils.formatSqlValues());
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* an empty string.
*/
public void testFormatSqlValues_empty_string() {
assertEquals("(\'\')", SendFusionTablesUtils.formatSqlValues(""));
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* one value.
*/
public void testFormatSqlValues_one_value() {
assertEquals("(\'first\')", SendFusionTablesUtils.formatSqlValues("first"));
}
/**
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
* two values.
*/
public void testFormatSqlValues_two_values() {
assertEquals(
"(\'first\',\'second\')", SendFusionTablesUtils.formatSqlValues("first", "second"));
}
/**
* Tests {@link SendFusionTablesUtils#escapeSqlString(String)} with a value
* containing several single quotes.
*/
public void testEscapeSqValuel() {
String value = "let's'";
assertEquals("let''s''", SendFusionTablesUtils.escapeSqlString(value));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a null
* point.
*/
public void testGetKmlPoint_null_point() {
assertEquals(
"<Point><coordinates></coordinates></Point>", SendFusionTablesUtils.getKmlPoint(null));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a valid
* point.
*/
public void testGetKmlPoint_valid_point() {
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.setAltitude(30.3);
assertEquals("<Point><coordinates>10.1,20.2,30.3</coordinates></Point>",
SendFusionTablesUtils.getKmlPoint(location));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with a null
* locations.
*/
public void testKmlLineString_null_locations() {
assertEquals("<LineString><coordinates></coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(null));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with no
* location.
*/
public void testKmlLineString_no_location() {
ArrayList<Location> locations = new ArrayList<Location>();
assertEquals("<LineString><coordinates></coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(locations));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with one
* location.
*/
public void testKmlLineString_one_location() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.setAltitude(30.3);
locations.add(location);
assertEquals("<LineString><coordinates>10.1,20.2,30.3</coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(locations));
}
/**
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with two
* locations.
*/
public void testKmlLineString_two_locations() {
ArrayList<Location> locations = new ArrayList<Location>();
Location location1 = new Location("test");
location1.setLongitude(10.1);
location1.setLatitude(20.2);
location1.setAltitude(30.3);
locations.add(location1);
Location location2 = new Location("test");
location2.setLongitude(1.1);
location2.setLatitude(2.2);
location2.removeAltitude();
locations.add(location2);
assertEquals("<LineString><coordinates>10.1,20.2,30.3 1.1,2.2</coordinates></LineString>",
SendFusionTablesUtils.getKmlLineString(locations));
}
/**
* Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
* with no altitude.
*/
public void testAppendLocation_no_altitude() {
StringBuilder builder = new StringBuilder();
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.removeAltitude();
SendFusionTablesUtils.appendLocation(location, builder);
assertEquals("10.1,20.2", builder.toString());
}
/**
* Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
* with altitude.
*/
public void testAppendLocation_has_altitude() {
StringBuilder builder = new StringBuilder();
Location location = new Location("test");
location.setLongitude(10.1);
location.setLatitude(20.2);
location.setAltitude(30.3);
SendFusionTablesUtils.appendLocation(location, builder);
assertEquals("10.1,20.2,30.3", builder.toString());
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a null
* inputstream.
*/
public void testGetTableId_null() {
assertEquals(null, SendFusionTablesUtils.getTableId(null));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an
* inputstream containing no data.
*/
public void testGetTableId_no_data() {
InputStream inputStream = new ByteArrayInputStream(new byte[0]);
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an empty
* inputstream.
*/
public void testGetTableId_empty() {
String string = "";
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an one
* line inputstream.
*/
public void testGetTableId_one_line() {
String string = "tableid";
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an
* inputstream not containing "tableid".
*/
public void testGetTableId_no_table_id() {
String string = "error\n123";
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
}
/**
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a valid
* inputstream.
*/
public void testGetTableId() {
String string = "tableid\n123";
InputStream inputStream = null;
inputStream = new ByteArrayInputStream(string.getBytes());
assertEquals("123", SendFusionTablesUtils.getTableId(inputStream));
}
} | Java |
package com.dsi.ant.exception;
public class AntInterfaceException extends Exception
{
/**
*
*/
private static final long serialVersionUID = -7278855366167722274L;
public AntInterfaceException()
{
this("Unknown ANT Interface error");
}
public AntInterfaceException(String string)
{
super(string);
}
}
| Java |
package com.dsi.ant.exception;
import android.os.RemoteException;
public class AntRemoteException extends AntInterfaceException
{
/**
*
*/
private static final long serialVersionUID = 8950974759973459561L;
public AntRemoteException(RemoteException e)
{
this("ANT Interface error, ANT Radio Service remote error: "+e.toString(), e);
}
public AntRemoteException(String string, RemoteException e)
{
super(string);
this.initCause(e);
}
}
| Java |
package com.dsi.ant.exception;
public class AntServiceNotConnectedException extends AntInterfaceException
{
/**
*
*/
private static final long serialVersionUID = -2085081032170129309L;
public AntServiceNotConnectedException()
{
this("ANT Interface error, ANT Radio Service not connected.");
}
public AntServiceNotConnectedException(String string)
{
super(string);
}
}
| Java |
/*
* Copyright 2011 Dynastream Innovations Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.dsi.ant;
/**
* Defines version numbers
*
* @hide
*/
public class Version {
//////////////////////////////////////////////
// Library Version Information
//////////////////////////////////////////////
public static final int ANT_LIBRARY_VERSION_CODE = 6;
public static final int ANT_LIBRARY_VERSION_MAJOR = 2;
public static final int ANT_LIBRARY_VERSION_MINOR = 0;
public static final String ANT_LIBRARY_VERSION_NAME = String.valueOf(ANT_LIBRARY_VERSION_MAJOR) + "." + String.valueOf(ANT_LIBRARY_VERSION_MINOR);
} | Java |
/*
* Copyright 2010 Dynastream Innovations Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.dsi.ant;
/**
* The Android Ant API is not finalized, and *will* change. Use at your
* own risk.
*
* Public API for controlling the Ant Service.
* AntDefines contains definitions commonly used in ANT messaging.
*
* @hide
*/
public class AntDefine {
//////////////////////////////////////////////
// Valid Configuration Values
//////////////////////////////////////////////
public static final byte MIN_BIN = 0;
public static final byte MAX_BIN = 10;
public static final short MIN_DEVICE_ID = 0;
public static final short MAX_DEVICE_ID = (short)65535;
public static final short MIN_BUFFER_THRESHOLD = 0;
public static final short MAX_BUFFER_THRESHOLD = 996;
//////////////////////////////////////////////
// ANT Message Payload Size
//////////////////////////////////////////////
public static final byte ANT_STANDARD_DATA_PAYLOAD_SIZE =((byte)8);
//////////////////////////////////////////////
// ANT LIBRARY Extended Data Message Fields
// NOTE: You must check the extended message
// bitfield first to find out which fields
// are present before accessing them!
//////////////////////////////////////////////
public static final byte ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE =((byte)4);
//public static final byte ANT_EXT_STRING_SIZE =((byte)19); // this is the additional buffer space required required for setting USB Descriptor strings
public static final byte ANT_EXT_STRING_SIZE =((byte)0); // changed to 0 as we will not be dealing with ANT USB parts.
//////////////////////////////////////////////
// ANT Extended Data Message Bifield Definitions
//////////////////////////////////////////////
public static final byte ANT_EXT_MESG_BITFIELD_DEVICE_ID =((byte)0x80); // first field after bitfield
public static final byte ANT_EXT_MESG_BITFIELD_RSSI =((byte)0x40); // next field after ID, if there is one
public static final byte ANT_EXT_MESG_BITFIELD_TIME_STAMP =((byte)0x20); // next field after RSSI, if there is one
// 4 bits free reserved set to 0
public static final byte ANT_EXT_MESG_BIFIELD_EXTENSION =((byte)0x01);
// extended message input bitfield defines
public static final byte ANT_EXT_MESG_BITFIELD_OVERWRITE_SHARED_ADR =((byte)0x10);
public static final byte ANT_EXT_MESG_BITFIELD_TRANSMISSION_TYPE =((byte)0x08);
//////////////////////////////////////////////
// ID Definitions
//////////////////////////////////////////////
public static final byte ANT_ID_SIZE =((byte)4);
public static final byte ANT_ID_TRANS_TYPE_OFFSET =((byte)3);
public static final byte ANT_ID_DEVICE_TYPE_OFFSET =((byte)2);
public static final byte ANT_ID_DEVICE_NUMBER_HIGH_OFFSET =((byte)1);
public static final byte ANT_ID_DEVICE_NUMBER_LOW_OFFSET =((byte)0);
public static final byte ANT_ID_DEVICE_TYPE_PAIRING_FLAG =((byte)0x80);
public static final byte ANT_TRANS_TYPE_SHARED_ADDR_MASK =((byte)0x03);
public static final byte ANT_TRANS_TYPE_1_BYTE_SHARED_ADDRESS =((byte)0x02);
public static final byte ANT_TRANS_TYPE_2_BYTE_SHARED_ADDRESS =((byte)0x03);
//////////////////////////////////////////////
// Assign Channel Parameters
//////////////////////////////////////////////
public static final byte PARAMETER_RX_NOT_TX =((byte)0x00);
public static final byte PARAMETER_TX_NOT_RX =((byte)0x10);
public static final byte PARAMETER_SHARED_CHANNEL =((byte)0x20);
public static final byte PARAMETER_NO_TX_GUARD_BAND =((byte)0x40);
public static final byte PARAMETER_ALWAYS_RX_WILD_CARD_SEARCH_ID =((byte)0x40); //Pre-AP2
public static final byte PARAMETER_RX_ONLY =((byte)0x40);
//////////////////////////////////////////////
// Ext. Assign Channel Parameters
//////////////////////////////////////////////
public static final byte EXT_PARAM_ALWAYS_SEARCH =((byte)0x01);
public static final byte EXT_PARAM_FREQUENCY_AGILITY =((byte)0x04);
//////////////////////////////////////////////
// Radio TX Power Definitions
//////////////////////////////////////////////
public static final byte RADIO_TX_POWER_LVL_MASK =((byte)0x03);
public static final byte RADIO_TX_POWER_LVL_0 =((byte)0x00); //(formerly: RADIO_TX_POWER_MINUS20DB); lowest
public static final byte RADIO_TX_POWER_LVL_1 =((byte)0x01); //(formerly: RADIO_TX_POWER_MINUS10DB);
public static final byte RADIO_TX_POWER_LVL_2 =((byte)0x02); //(formerly: RADIO_TX_POWER_MINUS5DB);
public static final byte RADIO_TX_POWER_LVL_3 =((byte)0x03); //(formerly: RADIO_TX_POWER_0DB); highest
//////////////////////////////////////////////
// Channel Status
//////////////////////////////////////////////
public static final byte STATUS_CHANNEL_STATE_MASK =((byte)0x03);
public static final byte STATUS_UNASSIGNED_CHANNEL =((byte)0x00);
public static final byte STATUS_ASSIGNED_CHANNEL =((byte)0x01);
public static final byte STATUS_SEARCHING_CHANNEL =((byte)0x02);
public static final byte STATUS_TRACKING_CHANNEL =((byte)0x03);
//////////////////////////////////////////////
// Standard capabilities defines
//////////////////////////////////////////////
public static final byte CAPABILITIES_NO_RX_CHANNELS =((byte)0x01);
public static final byte CAPABILITIES_NO_TX_CHANNELS =((byte)0x02);
public static final byte CAPABILITIES_NO_RX_MESSAGES =((byte)0x04);
public static final byte CAPABILITIES_NO_TX_MESSAGES =((byte)0x08);
public static final byte CAPABILITIES_NO_ACKD_MESSAGES =((byte)0x10);
public static final byte CAPABILITIES_NO_BURST_TRANSFER =((byte)0x20);
//////////////////////////////////////////////
// Advanced capabilities defines
//////////////////////////////////////////////
public static final byte CAPABILITIES_OVERUN_UNDERRUN =((byte)0x01); // Support for this functionality has been dropped
public static final byte CAPABILITIES_NETWORK_ENABLED =((byte)0x02);
public static final byte CAPABILITIES_AP1_VERSION_2 =((byte)0x04); // This Version of the AP1 does not support transmit and only had a limited release
public static final byte CAPABILITIES_SERIAL_NUMBER_ENABLED =((byte)0x08);
public static final byte CAPABILITIES_PER_CHANNEL_TX_POWER_ENABLED =((byte)0x10);
public static final byte CAPABILITIES_LOW_PRIORITY_SEARCH_ENABLED =((byte)0x20);
public static final byte CAPABILITIES_SCRIPT_ENABLED =((byte)0x40);
public static final byte CAPABILITIES_SEARCH_LIST_ENABLED =((byte)0x80);
//////////////////////////////////////////////
// Advanced capabilities 2 defines
//////////////////////////////////////////////
public static final byte CAPABILITIES_LED_ENABLED =((byte)0x01);
public static final byte CAPABILITIES_EXT_MESSAGE_ENABLED =((byte)0x02);
public static final byte CAPABILITIES_SCAN_MODE_ENABLED =((byte)0x04);
public static final byte CAPABILITIES_RESERVED =((byte)0x08);
public static final byte CAPABILITIES_PROX_SEARCH_ENABLED =((byte)0x10);
public static final byte CAPABILITIES_EXT_ASSIGN_ENABLED =((byte)0x20);
public static final byte CAPABILITIES_FREE_1 =((byte)0x40);
public static final byte CAPABILITIES_FIT1_ENABLED =((byte)0x80);
//////////////////////////////////////////////
// Advanced capabilities 3 defines
//////////////////////////////////////////////
public static final byte CAPABILITIES_SENSRCORE_ENABLED =((byte)0x01);
public static final byte CAPABILITIES_RESERVED_1 =((byte)0x02);
public static final byte CAPABILITIES_RESERVED_2 =((byte)0x04);
public static final byte CAPABILITIES_RESERVED_3 =((byte)0x08);
//////////////////////////////////////////////
// Burst Message Sequence
//////////////////////////////////////////////
public static final byte CHANNEL_NUMBER_MASK =((byte)0x1F);
public static final byte SEQUENCE_NUMBER_MASK =((byte)0xE0);
public static final byte SEQUENCE_NUMBER_ROLLOVER =((byte)0x60);
public static final byte SEQUENCE_FIRST_MESSAGE =((byte)0x00);
public static final byte SEQUENCE_LAST_MESSAGE =((byte)0x80);
public static final byte SEQUENCE_NUMBER_INC =((byte)0x20);
//////////////////////////////////////////////
// Control Message Flags
//////////////////////////////////////////////
public static final byte BROADCAST_CONTROL_BYTE =((byte)0x00);
public static final byte ACKNOWLEDGED_CONTROL_BYTE =((byte)0xA0);
//////////////////////////////////////////////
// Response / Event Codes
//////////////////////////////////////////////
public static final byte RESPONSE_NO_ERROR =((byte)0x00);
public static final byte NO_EVENT =((byte)0x00);
public static final byte EVENT_RX_SEARCH_TIMEOUT =((byte)0x01);
public static final byte EVENT_RX_FAIL =((byte)0x02);
public static final byte EVENT_TX =((byte)0x03);
public static final byte EVENT_TRANSFER_RX_FAILED =((byte)0x04);
public static final byte EVENT_TRANSFER_TX_COMPLETED =((byte)0x05);
public static final byte EVENT_TRANSFER_TX_FAILED =((byte)0x06);
public static final byte EVENT_CHANNEL_CLOSED =((byte)0x07);
public static final byte EVENT_RX_FAIL_GO_TO_SEARCH =((byte)0x08);
public static final byte EVENT_CHANNEL_COLLISION =((byte)0x09);
public static final byte EVENT_TRANSFER_TX_START =((byte)0x0A); // a pending transmit transfer has begun
public static final byte EVENT_CHANNEL_ACTIVE =((byte)0x0F);
public static final byte EVENT_TRANSFER_TX_NEXT_MESSAGE =((byte)0x11); // only enabled in FIT1
public static final byte CHANNEL_IN_WRONG_STATE =((byte)0x15); // returned on attempt to perform an action from the wrong channel state
public static final byte CHANNEL_NOT_OPENED =((byte)0x16); // returned on attempt to communicate on a channel that is not open
public static final byte CHANNEL_ID_NOT_SET =((byte)0x18); // returned on attempt to open a channel without setting the channel ID
public static final byte CLOSE_ALL_CHANNELS =((byte)0x19); // returned when attempting to start scanning mode, when channels are still open
public static final byte TRANSFER_IN_PROGRESS =((byte)0x1F); // returned on attempt to communicate on a channel with a TX transfer in progress
public static final byte TRANSFER_SEQUENCE_NUMBER_ERROR =((byte)0x20); // returned when sequence number is out of order on a Burst transfer
public static final byte TRANSFER_IN_ERROR =((byte)0x21);
public static final byte TRANSFER_BUSY =((byte)0x22);
public static final byte INVALID_MESSAGE_CRC =((byte)0x26); // returned if there is a framing error on an incomming message
public static final byte MESSAGE_SIZE_EXCEEDS_LIMIT =((byte)0x27); // returned if a data message is provided that is too large
public static final byte INVALID_MESSAGE =((byte)0x28); // returned when the message has an invalid parameter
public static final byte INVALID_NETWORK_NUMBER =((byte)0x29); // returned when an invalid network number is provided
public static final byte INVALID_LIST_ID =((byte)0x30); // returned when the provided list ID or size exceeds the limit
public static final byte INVALID_SCAN_TX_CHANNEL =((byte)0x31); // returned when attempting to transmit on channel 0 when in scan mode
public static final byte INVALID_PARAMETER_PROVIDED =((byte)0x33); // returned when an invalid parameter is specified in a configuration message
public static final byte EVENT_SERIAL_QUE_OVERFLOW =((byte)0x34);
public static final byte EVENT_QUE_OVERFLOW =((byte)0x35); // ANT event que has overflowed and lost 1 or more events
public static final byte EVENT_CLK_ERROR =((byte)0x36); // debug event for XOSC16M on LE1
public static final byte SCRIPT_FULL_ERROR =((byte)0x40); // error writing to script, memory is full
public static final byte SCRIPT_WRITE_ERROR =((byte)0x41); // error writing to script, bytes not written correctly
public static final byte SCRIPT_INVALID_PAGE_ERROR =((byte)0x42); // error accessing script page
public static final byte SCRIPT_LOCKED_ERROR =((byte)0x43); // the scripts are locked and can't be dumped
public static final byte NO_RESPONSE_MESSAGE =((byte)0x50); // returned to the Command_SerialMessageProcess function, so no reply message is generated
public static final byte RETURN_TO_MFG =((byte)0x51); // default return to any mesg when the module determines that the mfg procedure has not been fully completed
public static final byte FIT_ACTIVE_SEARCH_TIMEOUT =((byte)0x60); // Fit1 only event added for timeout of the pairing state after the Fit module becomes active
public static final byte FIT_WATCH_PAIR =((byte)0x61); // Fit1 only
public static final byte FIT_WATCH_UNPAIR =((byte)0x62); // Fit1 only
public static final byte USB_STRING_WRITE_FAIL =((byte)0x70);
// Internal only events below this point
public static final byte INTERNAL_ONLY_EVENTS =((byte)0x80);
public static final byte EVENT_RX =((byte)0x80); // INTERNAL: Event for a receive message
public static final byte EVENT_NEW_CHANNEL =((byte)0x81); // INTERNAL: EVENT for a new active channel
public static final byte EVENT_PASS_THRU =((byte)0x82); // INTERNAL: Event to allow an upper stack events to pass through lower stacks
public static final byte EVENT_BLOCKED =((byte)0xFF); // INTERNAL: Event to replace any event we do not wish to go out, will also zero the size of the Tx message
///////////////////////////////////////////////////////
// Script Command Codes
///////////////////////////////////////////////////////
public static final byte SCRIPT_CMD_FORMAT =((byte)0x00);
public static final byte SCRIPT_CMD_DUMP =((byte)0x01);
public static final byte SCRIPT_CMD_SET_DEFAULT_SECTOR =((byte)0x02);
public static final byte SCRIPT_CMD_END_SECTOR =((byte)0x03);
public static final byte SCRIPT_CMD_END_DUMP =((byte)0x04);
public static final byte SCRIPT_CMD_LOCK =((byte)0x05);
///////////////////////////////////////////////////////
// Reset Mesg Codes
///////////////////////////////////////////////////////
public static final byte RESET_FLAGS_MASK =((byte)0xE0);
public static final byte RESET_SUSPEND =((byte)0x80); // this must follow bitfield def
public static final byte RESET_SYNC =((byte)0x40); // this must follow bitfield def
public static final byte RESET_CMD =((byte)0x20); // this must follow bitfield def
public static final byte RESET_WDT =((byte)0x02);
public static final byte RESET_RST =((byte)0x01);
public static final byte RESET_POR =((byte)0x00);
} | Java |
/*
* Copyright 2010 Dynastream Innovations Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.dsi.ant;
import com.dsi.ant.exception.AntInterfaceException;
import com.dsi.ant.exception.AntRemoteException;
import com.dsi.ant.exception.AntServiceNotConnectedException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import java.util.Arrays;
/**
* Public API for controlling the Ant Service. AntInterface is a proxy
* object for controlling the Ant Service via IPC. Creating a AntInterface
* object will create a binding with the Ant service.
*
* @hide
*/
public class AntInterface {
/** The Log Tag. */
public static final String TAG = "ANTInterface";
/** Enable debug logging. */
public static boolean DEBUG = false;
/** Search string to find ANT Radio Proxy Service in the Android Marketplace */
private static final String MARKET_SEARCH_TEXT_DEFAULT = "ANT Radio Service Dynastream Innovations Inc";
/** Name of the ANT Radio shared library */
private static final String ANT_LIBRARY_NAME = "com.dsi.ant.antradio_library";
/** Inter-process communication with the ANT Radio Proxy Service. */
private static IAnt_6 sAntReceiver = null;
/** Singleton instance of this class. */
private static AntInterface INSTANCE;
/** Used when obtaining a reference to the singleton instance. */
private static Object INSTANCE_LOCK = new Object();
/** The context to use. */
private Context sContext = null;
/** Listens to changes to service connection status. */
private ServiceListener sServiceListener;
/** Is the ANT Radio Proxy Service connected. */
private static boolean sServiceConnected = false;
/** The version code (eg. 1) of ANTLib used by the ANT application service */
private static int mServiceLibraryVersionCode = 0;
/** Has support for ANT already been checked */
private static boolean mCheckedAntSupported = false;
/** Is ANT supported on this device */
private static boolean mAntSupported = false;
/**
* An interface for notifying AntInterface IPC clients when they have
* been connected to the ANT service.
*
* @see ServiceEvent
*/
public interface ServiceListener
{
/**
* Called to notify the client when this proxy object has been
* connected to the ANT service. Clients must wait for
* this callback before making IPC calls on the ANT
* service.
*/
public void onServiceConnected();
/**
* Called to notify the client that this proxy object has been
* disconnected from the ANT service. Clients must not
* make IPC calls on the ANT service after this callback.
* This callback will currently only occur if the application hosting
* the BluetoothAg service, but may be called more often in future.
*/
public void onServiceDisconnected();
}
//Constructor
/**
* Instantiates a new ant interface.
*
* @param context the context
* @param listener the listener
* @since 1.0
*/
private AntInterface(Context context, ServiceListener listener)
{
// This will be around as long as this process is
sContext = context;
sServiceListener = listener;
}
/**
* Gets the single instance of AntInterface, creating it if it doesn't exist.
* Only the initial request for an instance will have context and listener set to the requested objects.
*
* @param context the context used to bind to the remote service.
* @param listener the listener to be notified of status changes.
* @return the AntInterface instance.
* @since 1.0
*/
public static AntInterface getInstance(Context context,ServiceListener listener)
{
if(DEBUG) Log.d(TAG, "getInstance");
synchronized (INSTANCE_LOCK)
{
if(!hasAntSupport(context))
{
if(DEBUG) Log.d(TAG, "getInstance: ANT not supported");
return null;
}
if (INSTANCE == null)
{
if(DEBUG) Log.d(TAG, "getInstance: Creating new instance");
INSTANCE = new AntInterface(context,listener);
}
else
{
if(DEBUG) Log.d(TAG, "getInstance: Using existing instance");
}
if(!sServiceConnected)
{
if(DEBUG) Log.d(TAG, "getInstance: No connection to proxy service, attempting connection");
if(!INSTANCE.initService())
{
Log.e(TAG, "getInstance: No connection to proxy service");
INSTANCE.destroy();
INSTANCE = null;
}
}
return INSTANCE;
}
}
/**
* Go to market.
*
* @param pContext the context
* @param pSearchText the search text
* @since 1.2
*/
public static void goToMarket(Context pContext, String pSearchText)
{
if(null == pSearchText)
{
goToMarket(pContext);
}
else
{
if(DEBUG) Log.i(TAG, "goToMarket: Search text = "+ pSearchText);
Intent goToMarket = null;
goToMarket = new Intent(Intent.ACTION_VIEW,Uri.parse("http://market.android.com/search?q=" + pSearchText));
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pContext.startActivity(goToMarket);
}
}
/**
* Go to market.
*
* @param pContext the context
* @since 1.2
*/
public static void goToMarket(Context pContext)
{
if(DEBUG) Log.d(TAG, "goToMarket");
goToMarket(pContext, MARKET_SEARCH_TEXT_DEFAULT);
}
/**
* Class for interacting with the ANT interface.
*/
private final ServiceConnection sIAntConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName pClassName, IBinder pService) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
if(DEBUG) Log.d(TAG, "sIAntConnection onServiceConnected()");
sAntReceiver = IAnt_6.Stub.asInterface(pService);
sServiceConnected = true;
// Notify the attached application if it is registered
if (sServiceListener != null)
{
sServiceListener.onServiceConnected();
}
else
{
if(DEBUG) Log.d(TAG, "sIAntConnection onServiceConnected: No service listener registered");
}
}
public void onServiceDisconnected(ComponentName pClassName) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
if(DEBUG) Log.d(TAG, "sIAntConnection onServiceDisconnected()");
sAntReceiver = null;
sServiceConnected = false;
mServiceLibraryVersionCode = 0;
// Notify the attached application if it is registered
if (sServiceListener != null)
{
sServiceListener.onServiceDisconnected();
}
else
{
if(DEBUG) Log.d(TAG, "sIAntConnection onServiceDisconnected: No service listener registered");
}
// Try and rebind to the service
INSTANCE.releaseService();
INSTANCE.initService();
}
};
/**
* Binds this activity to the ANT service.
*
* @return true, if successful
*/
private boolean initService() {
if(DEBUG) Log.d(TAG, "initService() entered");
boolean ret = false;
if(!sServiceConnected)
{
ret = sContext.bindService(new Intent(IAnt_6.class.getName()), sIAntConnection, Context.BIND_AUTO_CREATE);
if(DEBUG) Log.i(TAG, "initService(): Bound with ANT service: " + ret);
}
else
{
if(DEBUG) Log.d(TAG, "initService: already initialised service");
ret = true;
}
return ret;
}
/** Unbinds this activity from the ANT service. */
private void releaseService() {
if(DEBUG) Log.d(TAG, "releaseService() entered");
// TODO Make sure can handle multiple calls to onDestroy
if(sServiceConnected)
{
sContext.unbindService(sIAntConnection);
sServiceConnected = false;
}
if(DEBUG) Log.d(TAG, "releaseService() unbound.");
}
/**
* True if this activity can communicate with the ANT service.
*
* @return true, if service is connected
* @since 1.2
*/
public boolean isServiceConnected()
{
return sServiceConnected;
}
/**
* Destroy.
*
* @return true, if successful
* @since 1.0
*/
public boolean destroy()
{
if(DEBUG) Log.d(TAG, "destroy");
releaseService();
INSTANCE = null;
return true;
}
////-------------------------------------------------
/**
* Enable.
*
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void enable() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.enable())
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Disable.
*
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void disable() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.disable())
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Checks if is enabled.
*
* @return true, if is enabled.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public boolean isEnabled() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.isEnabled();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT tx message.
*
* @param message the message
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTTxMessage(byte[] message) throws AntInterfaceException
{
if(DEBUG) Log.d(TAG, "ANTTxMessage");
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTTxMessage(message))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT reset system.
*
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTResetSystem() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTResetSystem())
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT unassign channel.
*
* @param channelNumber the channel number
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTUnassignChannel(byte channelNumber) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTUnassignChannel(channelNumber))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT assign channel.
*
* @param channelNumber the channel number
* @param channelType the channel type
* @param networkNumber the network number
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTAssignChannel(channelNumber, channelType, networkNumber))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set channel id.
*
* @param channelNumber the channel number
* @param deviceNumber the device number
* @param deviceType the device type
* @param txType the tx type
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetChannelId(byte channelNumber, short deviceNumber, byte deviceType, byte txType) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetChannelId(channelNumber, deviceNumber, deviceType, txType))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set channel period.
*
* @param channelNumber the channel number
* @param channelPeriod the channel period
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetChannelPeriod(byte channelNumber, short channelPeriod) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetChannelPeriod(channelNumber, channelPeriod))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set channel rf freq.
*
* @param channelNumber the channel number
* @param radioFrequency the radio frequency
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetChannelRFFreq(channelNumber, radioFrequency))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set channel search timeout.
*
* @param channelNumber the channel number
* @param searchTimeout the search timeout
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetChannelSearchTimeout(channelNumber, searchTimeout))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set low priority channel search timeout.
*
* @param channelNumber the channel number
* @param searchTimeout the search timeout
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetLowPriorityChannelSearchTimeout(channelNumber, searchTimeout))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set proximity search.
*
* @param channelNumber the channel number
* @param searchThreshold the search threshold
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetProximitySearch(byte channelNumber, byte searchThreshold) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetProximitySearch(channelNumber, searchThreshold))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT set channel transmit power
* @param channelNumber the channel number
* @param txPower the transmit power level
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSetChannelTxPower(byte channelNumber, byte txPower) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSetChannelTxPower(channelNumber, txPower))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT add channel id.
*
* @param channelNumber the channel number
* @param deviceNumber the device number
* @param deviceType the device type
* @param txType the tx type
* @param listIndex the list index
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTAddChannelId(byte channelNumber, short deviceNumber, byte deviceType, byte txType, byte listIndex) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTAddChannelId(channelNumber, deviceNumber, deviceType, txType, listIndex))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT config list.
*
* @param channelNumber the channel number
* @param listSize the list size
* @param exclude the exclude
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTConfigList(byte channelNumber, byte listSize, byte exclude) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTConfigList(channelNumber, listSize, exclude))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT config event buffering.
*
* @param screenOnFlushTimerInterval the screen on flush timer interval
* @param screenOnFlushBufferThreshold the screen on flush buffer threshold
* @param screenOffFlushTimerInterval the screen off flush timer interval
* @param screenOffFlushBufferThreshold the screen off flush buffer threshold
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.3
*/
public void ANTConfigEventBuffering(short screenOnFlushTimerInterval, short screenOnFlushBufferThreshold, short screenOffFlushTimerInterval, short screenOffFlushBufferThreshold) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTConfigEventBuffering((int)screenOnFlushTimerInterval, (int)screenOnFlushBufferThreshold, (int)screenOffFlushTimerInterval, (int)screenOffFlushBufferThreshold))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT disable event buffering.
*
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.1
*/
public void ANTDisableEventBuffering() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTDisableEventBuffering())
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT open channel.
*
* @param channelNumber the channel number
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTOpenChannel(byte channelNumber) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTOpenChannel(channelNumber))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT close channel.
*
* @param channelNumber the channel number
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTCloseChannel(byte channelNumber) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTCloseChannel(channelNumber))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT request message.
*
* @param channelNumber the channel number
* @param messageID the message id
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTRequestMessage(byte channelNumber, byte messageID) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTRequestMessage(channelNumber, messageID))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT send broadcast data.
*
* @param channelNumber the channel number
* @param txBuffer the tx buffer
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSendBroadcastData(byte channelNumber, byte[] txBuffer) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSendBroadcastData(channelNumber, txBuffer))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT send acknowledged data.
*
* @param channelNumber the channel number
* @param txBuffer the tx buffer
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSendAcknowledgedData(byte channelNumber, byte[] txBuffer) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSendAcknowledgedData(channelNumber, txBuffer))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT send burst transfer packet.
*
* @param control the control
* @param txBuffer the tx buffer
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public void ANTSendBurstTransferPacket(byte control, byte[] txBuffer) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
if(!sAntReceiver.ANTSendBurstTransferPacket(control, txBuffer))
{
throw new AntInterfaceException();
}
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Transmits the given data on channelNumber as part of a burst message.
*
* @param channelNumber Which channel to transmit on.
* @param txBuffer The data to send.
* @param initialPacket Which packet in the burst sequence does the data begin in, 1 is the first.
* @param containsEndOfBurst Is this the last of the data to be sent in burst.
* @return The number of bytes still to be sent (approximately). 0 if success.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
*/
public int ANTSendBurstTransfer(byte channelNumber, byte[] txBuffer) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.ANTSendBurstTransfer(channelNumber, txBuffer);
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* ANT send partial burst.
*
* @param channelNumber the channel number
* @param txBuffer the tx buffer
* @param initialPacket the initial packet
* @param containsEndOfBurst the contains end of burst
* @return The number of bytes still to be sent (approximately). 0 if success.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.0
*/
public int ANTSendPartialBurst(byte channelNumber, byte[] txBuffer, int initialPacket, boolean containsEndOfBurst) throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.ANTTransmitBurst(channelNumber, txBuffer, initialPacket, containsEndOfBurst);
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Returns the version code (eg. 1) of ANTLib used by the ANT application service
*
* @return the service library version code, or 0 on error.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.2
*/
public int getServiceLibraryVersionCode() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
if(mServiceLibraryVersionCode == 0)
{
try
{
mServiceLibraryVersionCode = sAntReceiver.getServiceLibraryVersionCode();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
return mServiceLibraryVersionCode;
}
/**
* Returns the version name (eg "1.0") of ANTLib used by the ANT application service
*
* @return the service library version name, or null on error.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.2
*/
public String getServiceLibraryVersionName() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.getServiceLibraryVersionName();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Take control of the ANT Radio.
*
* @return True if control has been granted, false if another application has control or the request failed.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.5
*/
public boolean claimInterface() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.claimInterface();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Give up control of the ANT Radio.
*
* @return True if control has been given up, false if this application did not have control.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.5
*/
public boolean releaseInterface() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.releaseInterface();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Claims the interface if it is available. If not the user will be prompted (on the notification bar) if a force claim should be done.
* If the ANT Interface is claimed, an AntInterfaceIntent.ANT_INTERFACE_CLAIMED_ACTION intent will be sent, with the current applications pid.
*
* @param String appName The name if this application, to show to the user.
* @returns false if a claim interface request notification already exists.
* @throws IllegalArgumentException
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.5
*/
public boolean requestForceClaimInterface(String appName) throws AntInterfaceException
{
if((null == appName) || ("".equals(appName)))
{
throw new IllegalArgumentException();
}
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.requestForceClaimInterface(appName);
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Clears the notification asking the user if they would like to seize control of the ANT Radio.
*
* @returns false if this process is not requesting to claim the interface.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.5
*/
public boolean stopRequestForceClaimInterface() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.stopRequestForceClaimInterface();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Check if the calling application has control of the ANT Radio.
*
* @return True if control is currently granted.
* @throws AntInterfaceException
* @throws AntServiceNotConnectedException
* @throws AntRemoteException
* @since 1.5
*/
public boolean hasClaimedInterface() throws AntInterfaceException
{
if(!sServiceConnected)
{
throw new AntServiceNotConnectedException();
}
try
{
return sAntReceiver.hasClaimedInterface();
}
catch(RemoteException e)
{
throw new AntRemoteException(e);
}
}
/**
* Check if this device has support for ANT.
*
* @return True if the device supports ANT (may still require ANT Radio Service be installed).
* @since 1.5
*/
public static boolean hasAntSupport(Context pContext)
{
if(!mCheckedAntSupported)
{
mAntSupported = Arrays.asList(pContext.getPackageManager().getSystemSharedLibraryNames()).contains(ANT_LIBRARY_NAME);
mCheckedAntSupported = true;
}
return mAntSupported;
}
}
| Java |
/*
* Copyright 2010 Dynastream Innovations Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.dsi.ant;
/**
* Public API for controlling the Ant Service.
* AntMesg contains definitions for ANT message IDs
*
* @hide
*/
public class AntMesg {
/////////////////////////////////////////////////////////////////////////////
// HCI VS Message Format
// Messages are in the format:
//
// Outgoing ANT messages (host -> ANT chip)
// 01 D1 FD XX YY YY II JJ ------
// ^ ^ ^ ^
// | HCI framing | | ANT Mesg |
//
// where: 01 is the 1 byte HCI packet Identifier (HCI Command packet)
// D1 FD is the 2 byte HCI op code (0xFDD1 stored in little endian)
// XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte)
// YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian
// II is the 1 byte size of the ANT message (0-249)
// JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid)
// ------ is the data of the ANT message (0-249 bytes of data)
//
// Incoming HCI Command Complete for ANT message command (host <- ANT chip)
// 04 0E 04 01 D1 FD ZZ
//
// where: 04 is the 1 byte HCI packet Identifier (HCI Event packet)
// 0E is the 1 byte HCI event (Command Complete)
// 04 is the 1 byte Length of all parameters in bytes (there are 4 bytes)
// 01 is the 1 byte Number of parameters in the packet (there is 1 parameter)
// D1 FD is the 2 byte HCI Op code of the command (0xFDD1 stored in little endian)
// ZZ is the 1 byte response to the command (0x00 - Command Successful
// 0x1F - Returned if the receive message queue of the ANT chip is full, the command should be retried
// Other - Any other non-zero response code indicates an error)
//
// Incoming ANT messages (host <- ANT chip)
// 04 FF XX 00 05 YY YY II JJ ------
// ^ ^ ^ ^
// | HCI framing | | ANT Mesg |
//
// where: 04 is the 1 byte HCI packet Identifier (HCI Event packet)
// FF is the 1 byte HCI event code (0xFF Vendor Specific event)
// XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte)
// 00 05 is the 2 byte vendor specific event code for ANT messages (0x0500 stored in little endian)
// YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian
// II is the 1 byte size of the ANT message (0-249)
// JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid)
// ------ is the data of the ANT message (0-249 bytes of data)
//
/////////////////////////////////////////////////////////////////////////////
public static final byte MESG_SYNC_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a sync byte
public static final byte MESG_SIZE_SIZE =((byte)1);
public static final byte MESG_ID_SIZE =((byte)1);
public static final byte MESG_CHANNEL_NUM_SIZE =((byte)1);
public static final byte MESG_EXT_MESG_BF_SIZE =((byte)1); // NOTE: this could increase in the future
public static final byte MESG_CHECKSUM_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a checksum
public static final byte MESG_DATA_SIZE =((byte)9);
// The largest serial message is an ANT data message with all of the extended fields
public static final byte MESG_ANT_MAX_PAYLOAD_SIZE =AntDefine.ANT_STANDARD_DATA_PAYLOAD_SIZE;
public static final byte MESG_MAX_EXT_DATA_SIZE =(AntDefine.ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE + AntDefine.ANT_EXT_STRING_SIZE); // ANT device ID (4 bytes) + Padding for ANT EXT string size(19 bytes)
public static final byte MESG_MAX_DATA_SIZE =(MESG_ANT_MAX_PAYLOAD_SIZE + MESG_EXT_MESG_BF_SIZE + MESG_MAX_EXT_DATA_SIZE); // ANT data payload (8 bytes) + extended bitfield (1 byte) + extended data (10 bytes)
public static final byte MESG_MAX_SIZE_VALUE =(MESG_MAX_DATA_SIZE + MESG_CHANNEL_NUM_SIZE); // this is the maximum value that the serial message size value is allowed to be
public static final byte MESG_BUFFER_SIZE =(MESG_SIZE_SIZE + MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE + MESG_CHECKSUM_SIZE);
public static final byte MESG_FRAMED_SIZE =(MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE);
public static final byte MESG_HEADER_SIZE =(MESG_SYNC_SIZE + MESG_SIZE_SIZE + MESG_ID_SIZE);
public static final byte MESG_FRAME_SIZE =(MESG_HEADER_SIZE + MESG_CHECKSUM_SIZE);
public static final byte MESG_MAX_SIZE =(MESG_MAX_DATA_SIZE + MESG_FRAME_SIZE);
public static final byte MESG_SIZE_OFFSET =(MESG_SYNC_SIZE);
public static final byte MESG_ID_OFFSET =(MESG_SYNC_SIZE + MESG_SIZE_SIZE);
public static final byte MESG_DATA_OFFSET =(MESG_HEADER_SIZE);
public static final byte MESG_RECOMMENDED_BUFFER_SIZE =((byte) 64); // This is the recommended size for serial message buffers if there are no RAM restrictions on the system
//////////////////////////////////////////////
// Message ID's
//////////////////////////////////////////////
public static final byte MESG_INVALID_ID =((byte)0x00);
public static final byte MESG_EVENT_ID =((byte)0x01);
public static final byte MESG_VERSION_ID =((byte)0x3E);
public static final byte MESG_RESPONSE_EVENT_ID =((byte)0x40);
public static final byte MESG_UNASSIGN_CHANNEL_ID =((byte)0x41);
public static final byte MESG_ASSIGN_CHANNEL_ID =((byte)0x42);
public static final byte MESG_CHANNEL_MESG_PERIOD_ID =((byte)0x43);
public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_ID =((byte)0x44);
public static final byte MESG_CHANNEL_RADIO_FREQ_ID =((byte)0x45);
public static final byte MESG_NETWORK_KEY_ID =((byte)0x46);
public static final byte MESG_RADIO_TX_POWER_ID =((byte)0x47);
public static final byte MESG_RADIO_CW_MODE_ID =((byte)0x48);
public static final byte MESG_SYSTEM_RESET_ID =((byte)0x4A);
public static final byte MESG_OPEN_CHANNEL_ID =((byte)0x4B);
public static final byte MESG_CLOSE_CHANNEL_ID =((byte)0x4C);
public static final byte MESG_REQUEST_ID =((byte)0x4D);
public static final byte MESG_BROADCAST_DATA_ID =((byte)0x4E);
public static final byte MESG_ACKNOWLEDGED_DATA_ID =((byte)0x4F);
public static final byte MESG_BURST_DATA_ID =((byte)0x50);
public static final byte MESG_CHANNEL_ID_ID =((byte)0x51);
public static final byte MESG_CHANNEL_STATUS_ID =((byte)0x52);
public static final byte MESG_RADIO_CW_INIT_ID =((byte)0x53);
public static final byte MESG_CAPABILITIES_ID =((byte)0x54);
public static final byte MESG_STACKLIMIT_ID =((byte)0x55);
public static final byte MESG_SCRIPT_DATA_ID =((byte)0x56);
public static final byte MESG_SCRIPT_CMD_ID =((byte)0x57);
public static final byte MESG_ID_LIST_ADD_ID =((byte)0x59);
public static final byte MESG_ID_LIST_CONFIG_ID =((byte)0x5A);
public static final byte MESG_OPEN_RX_SCAN_ID =((byte)0x5B);
public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_ID =((byte)0x5C); // OBSOLETE: (for 905 radio)
public static final byte MESG_EXT_BROADCAST_DATA_ID =((byte)0x5D);
public static final byte MESG_EXT_ACKNOWLEDGED_DATA_ID =((byte)0x5E);
public static final byte MESG_EXT_BURST_DATA_ID =((byte)0x5F);
public static final byte MESG_CHANNEL_RADIO_TX_POWER_ID =((byte)0x60);
public static final byte MESG_GET_SERIAL_NUM_ID =((byte)0x61);
public static final byte MESG_GET_TEMP_CAL_ID =((byte)0x62);
public static final byte MESG_SET_LP_SEARCH_TIMEOUT_ID =((byte)0x63);
public static final byte MESG_SET_TX_SEARCH_ON_NEXT_ID =((byte)0x64);
public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_ID =((byte)0x65);
public static final byte MESG_RX_EXT_MESGS_ENABLE_ID =((byte)0x66);
public static final byte MESG_RADIO_CONFIG_ALWAYS_ID =((byte)0x67);
public static final byte MESG_ENABLE_LED_FLASH_ID =((byte)0x68);
public static final byte MESG_XTAL_ENABLE_ID =((byte)0x6D);
public static final byte MESG_STARTUP_MESG_ID =((byte)0x6F);
public static final byte MESG_AUTO_FREQ_CONFIG_ID =((byte)0x70);
public static final byte MESG_PROX_SEARCH_CONFIG_ID =((byte)0x71);
public static final byte MESG_EVENT_BUFFERING_CONFIG_ID =((byte)0x74);
public static final byte MESG_CUBE_CMD_ID =((byte)0x80);
public static final byte MESG_GET_PIN_DIODE_CONTROL_ID =((byte)0x8D);
public static final byte MESG_PIN_DIODE_CONTROL_ID =((byte)0x8E);
public static final byte MESG_FIT1_SET_AGC_ID =((byte)0x8F);
public static final byte MESG_FIT1_SET_EQUIP_STATE_ID =((byte)0x91); // *** CONFLICT: w/ Sensrcore, Fit1 will never have sensrcore enabled
// Sensrcore Messages
public static final byte MESG_SET_CHANNEL_INPUT_MASK_ID =((byte)0x90);
public static final byte MESG_SET_CHANNEL_DATA_TYPE_ID =((byte)0x91);
public static final byte MESG_READ_PINS_FOR_SECT_ID =((byte)0x92);
public static final byte MESG_TIMER_SELECT_ID =((byte)0x93);
public static final byte MESG_ATOD_SETTINGS_ID =((byte)0x94);
public static final byte MESG_SET_SHARED_ADDRESS_ID =((byte)0x95);
public static final byte MESG_ATOD_EXTERNAL_ENABLE_ID =((byte)0x96);
public static final byte MESG_ATOD_PIN_SETUP_ID =((byte)0x97);
public static final byte MESG_SETUP_ALARM_ID =((byte)0x98);
public static final byte MESG_ALARM_VARIABLE_MODIFY_TEST_ID =((byte)0x99);
public static final byte MESG_PARTIAL_RESET_ID =((byte)0x9A);
public static final byte MESG_OVERWRITE_TEMP_CAL_ID =((byte)0x9B);
public static final byte MESG_SERIAL_PASSTHRU_SETTINGS_ID =((byte)0x9C);
public static final byte MESG_BIST_ID =((byte)0xAA);
public static final byte MESG_UNLOCK_INTERFACE_ID =((byte)0xAD);
public static final byte MESG_SERIAL_ERROR_ID =((byte)0xAE);
public static final byte MESG_SET_ID_STRING_ID =((byte)0xAF);
public static final byte MESG_PORT_GET_IO_STATE_ID =((byte)0xB4);
public static final byte MESG_PORT_SET_IO_STATE_ID =((byte)0xB5);
public static final byte MESG_SLEEP_ID =((byte)0xC5);
public static final byte MESG_GET_GRMN_ESN_ID =((byte)0xC6);
public static final byte MESG_SET_USB_INFO_ID =((byte)0xC7);
public static final byte MESG_COMMAND_COMPLETE_RESPONSE_ID =((byte)0xC8);
//////////////////////////////////////////////
// Command complete results
//////////////////////////////////////////////
public static final byte MESG_COMMAND_COMPLETE_SUCCESS =((byte)0x00);
public static final byte MESG_COMMAND_COMPLETE_RETRY =((byte)0x1F);
//////////////////////////////////////////////
// Message Sizes
//////////////////////////////////////////////
public static final byte MESG_INVALID_SIZE =((byte)0);
public static final byte MESG_VERSION_SIZE =((byte)13);
public static final byte MESG_RESPONSE_EVENT_SIZE =((byte)3);
public static final byte MESG_CHANNEL_STATUS_SIZE =((byte)2);
public static final byte MESG_UNASSIGN_CHANNEL_SIZE =((byte)1);
public static final byte MESG_ASSIGN_CHANNEL_SIZE =((byte)3);
public static final byte MESG_CHANNEL_ID_SIZE =((byte)5);
public static final byte MESG_CHANNEL_MESG_PERIOD_SIZE =((byte)3);
public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_SIZE =((byte)2);
public static final byte MESG_CHANNEL_RADIO_FREQ_SIZE =((byte)2);
public static final byte MESG_CHANNEL_RADIO_TX_POWER_SIZE =((byte)2);
public static final byte MESG_NETWORK_KEY_SIZE =((byte)9);
public static final byte MESG_RADIO_TX_POWER_SIZE =((byte)2);
public static final byte MESG_RADIO_CW_MODE_SIZE =((byte)3);
public static final byte MESG_RADIO_CW_INIT_SIZE =((byte)1);
public static final byte MESG_SYSTEM_RESET_SIZE =((byte)1);
public static final byte MESG_OPEN_CHANNEL_SIZE =((byte)1);
public static final byte MESG_CLOSE_CHANNEL_SIZE =((byte)1);
public static final byte MESG_REQUEST_SIZE =((byte)2);
public static final byte MESG_CAPABILITIES_SIZE =((byte)6);
public static final byte MESG_STACKLIMIT_SIZE =((byte)2);
public static final byte MESG_SCRIPT_DATA_SIZE =((byte)10);
public static final byte MESG_SCRIPT_CMD_SIZE =((byte)3);
public static final byte MESG_ID_LIST_ADD_SIZE =((byte)6);
public static final byte MESG_ID_LIST_CONFIG_SIZE =((byte)3);
public static final byte MESG_OPEN_RX_SCAN_SIZE =((byte)1);
public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_SIZE =((byte)3);
public static final byte MESG_RADIO_CONFIG_ALWAYS_SIZE =((byte)2);
public static final byte MESG_RX_EXT_MESGS_ENABLE_SIZE =((byte)2);
public static final byte MESG_SET_TX_SEARCH_ON_NEXT_SIZE =((byte)2);
public static final byte MESG_SET_LP_SEARCH_TIMEOUT_SIZE =((byte)2);
public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_SIZE =((byte)3);
public static final byte MESG_ENABLE_LED_FLASH_SIZE =((byte)2);
public static final byte MESG_GET_SERIAL_NUM_SIZE =((byte)4);
public static final byte MESG_GET_TEMP_CAL_SIZE =((byte)4);
public static final byte MESG_XTAL_ENABLE_SIZE =((byte)1);
public static final byte MESG_STARTUP_MESG_SIZE =((byte)1);
public static final byte MESG_AUTO_FREQ_CONFIG_SIZE =((byte)4);
public static final byte MESG_PROX_SEARCH_CONFIG_SIZE =((byte)2);
public static final byte MESG_GET_PIN_DIODE_CONTROL_SIZE =((byte)1);
public static final byte MESG_PIN_DIODE_CONTROL_ID_SIZE =((byte)2);
public static final byte MESG_FIT1_SET_EQUIP_STATE_SIZE =((byte)2);
public static final byte MESG_FIT1_SET_AGC_SIZE =((byte)3);
public static final byte MESG_BIST_SIZE =((byte)6);
public static final byte MESG_UNLOCK_INTERFACE_SIZE =((byte)1);
public static final byte MESG_SET_SHARED_ADDRESS_SIZE =((byte)3);
public static final byte MESG_GET_GRMN_ESN_SIZE =((byte)5);
public static final byte MESG_PORT_SET_IO_STATE_SIZE =((byte)5);
public static final byte MESG_EVENT_BUFFERING_CONFIG_SIZE =((byte)6);
public static final byte MESG_SLEEP_SIZE =((byte)1);
public static final byte MESG_EXT_DATA_SIZE =((byte)13);
protected AntMesg()
{ }
}
| Java |
/*
* Copyright 2010 Dynastream Innovations Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.dsi.ant;
/**
* Manages the ANT Interface
*
* @hide
*/
public interface AntInterfaceIntent {
public static final String STATUS = "com.dsi.ant.rx.intent.STATUS";
public static final String ANT_MESSAGE = "com.dsi.ant.intent.ANT_MESSAGE";
public static final String ANT_INTERFACE_CLAIMED_PID = "com.dsi.ant.intent.ANT_INTERFACE_CLAIMED_PID";
public static final String ANT_ENABLED_ACTION = "com.dsi.ant.intent.action.ANT_ENABLED";
public static final String ANT_DISABLED_ACTION = "com.dsi.ant.intent.action.ANT_DISABLED";
public static final String ANT_RESET_ACTION = "com.dsi.ant.intent.action.ANT_RESET";
public static final String ANT_INTERFACE_CLAIMED_ACTION = "com.dsi.ant.intent.action.ANT_INTERFACE_CLAIMED_ACTION";
public static final String ANT_RX_MESSAGE_ACTION = "com.dsi.ant.intent.action.ANT_RX_MESSAGE_ACTION";
}
| Java |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.TrackDataHub;
import com.google.android.apps.mytracks.services.RemoveTempFilesService;
import android.app.Application;
import android.content.Intent;
/**
* MyTracksApplication for keeping global state.
*
* @author Jimmy Shih
*/
public class MyTracksApplication extends Application {
private TrackDataHub trackDataHub;
@Override
public void onCreate() {
startService(new Intent(this, RemoveTempFilesService.class));
}
/**
* Gets the application's TrackDataHub.
*
* Note: use synchronized to make sure only one instance is created per application.
*/
public synchronized TrackDataHub getTrackDataHub() {
if (trackDataHub == null) {
trackDataHub = TrackDataHub.newInstance(getApplicationContext());
}
return trackDataHub;
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.ChartView.Mode;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Sensor.SensorDataSet;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.TrackDataHub;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.stats.DoubleBuffer;
import com.google.android.apps.mytracks.stats.TripStatisticsBuilder;
import com.google.android.apps.mytracks.util.LocationUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import com.google.common.annotations.VisibleForTesting;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.location.Location;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ZoomControls;
import java.util.ArrayList;
import java.util.EnumSet;
/**
* An activity that displays a chart from the track point provider.
*
* @author Sandor Dornbush
* @author Rodrigo Damazio
*/
public class ChartActivity extends Activity implements TrackDataListener {
private static final int CHART_SETTINGS_DIALOG = 1;
private final DoubleBuffer elevationBuffer =
new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR);
private final DoubleBuffer speedBuffer =
new DoubleBuffer(Constants.SPEED_SMOOTHING_FACTOR);
private final ArrayList<double[]> pendingPoints = new ArrayList<double[]>();
private TrackDataHub dataHub;
// Stats gathered from received data.
private double profileLength = 0;
private long startTime = -1;
private Location lastLocation;
private double trackMaxSpeed;
// Modes of operation
private boolean metricUnits = true;
private boolean reportSpeed = true;
/*
* UI elements:
*/
private ChartView chartView;
private MenuItem chartSettingsMenuItem;
private LinearLayout busyPane;
private ZoomControls zoomControls;
/**
* A runnable that can be posted to the UI thread. It will remove the spinner
* (if any), enable/disable zoom controls and orange pointer as appropriate
* and redraw.
*/
private final Runnable updateChart = new Runnable() {
@Override
public void run() {
// Get a local reference in case it's set to null concurrently with this.
TrackDataHub localDataHub = dataHub;
if (localDataHub == null || isFinishing()) {
return;
}
busyPane.setVisibility(View.GONE);
zoomControls.setIsZoomInEnabled(chartView.canZoomIn());
zoomControls.setIsZoomOutEnabled(chartView.canZoomOut());
chartView.setShowPointer(localDataHub.isRecordingSelected());
chartView.invalidate();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.w(TAG, "ChartActivity.onCreate");
super.onCreate(savedInstanceState);
// The volume we want to control is the Text-To-Speech volume
setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mytracks_charts);
ViewGroup layout = (ViewGroup) findViewById(R.id.elevation_chart);
chartView = new ChartView(this);
LayoutParams params =
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.addView(chartView, params);
busyPane = (LinearLayout) findViewById(R.id.elevation_busypane);
zoomControls = (ZoomControls) findViewById(R.id.elevation_zoom);
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
zoomIn();
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
zoomOut();
}
});
}
@Override
protected void onResume() {
super.onResume();
dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub();
dataHub.registerTrackDataListener(this, EnumSet.of(
ListenerDataType.SELECTED_TRACK_CHANGED,
ListenerDataType.TRACK_UPDATES,
ListenerDataType.POINT_UPDATES,
ListenerDataType.SAMPLED_OUT_POINT_UPDATES,
ListenerDataType.WAYPOINT_UPDATES,
ListenerDataType.DISPLAY_PREFERENCES));
}
@Override
protected void onPause() {
dataHub.unregisterTrackDataListener(this);
dataHub = null;
super.onPause();
}
private void zoomIn() {
chartView.zoomIn();
zoomControls.setIsZoomInEnabled(chartView.canZoomIn());
zoomControls.setIsZoomOutEnabled(chartView.canZoomOut());
}
private void zoomOut() {
chartView.zoomOut();
zoomControls.setIsZoomInEnabled(chartView.canZoomIn());
zoomControls.setIsZoomOutEnabled(chartView.canZoomOut());
}
private void setMode(Mode newMode) {
if (chartView.getMode() != newMode) {
chartView.setMode(newMode);
dataHub.reloadDataForListener(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
chartSettingsMenuItem = menu.add(Menu.NONE, Constants.MENU_CHART_SETTINGS, Menu.NONE,
R.string.menu_chart_view_chart_settings);
chartSettingsMenuItem.setIcon(R.drawable.chart_settings);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Constants.MENU_CHART_SETTINGS:
showDialog(CHART_SETTINGS_DIALOG);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == CHART_SETTINGS_DIALOG) {
final ChartSettingsDialog settingsDialog = new ChartSettingsDialog(this);
settingsDialog.setOnClickListener(new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int which) {
if (which != DialogInterface.BUTTON_POSITIVE) {
return;
}
for (int i = 0; i < ChartView.NUM_SERIES; i++) {
chartView.setChartValueSeriesEnabled(i, settingsDialog.isSeriesEnabled(i));
}
setMode(settingsDialog.getMode());
chartView.postInvalidate();
}
});
return settingsDialog;
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CHART_SETTINGS_DIALOG) {
prepareSettingsDialog((ChartSettingsDialog) dialog);
}
}
private void prepareSettingsDialog(ChartSettingsDialog settingsDialog) {
settingsDialog.setMode(chartView.getMode());
settingsDialog.setDisplaySpeed(reportSpeed);
for (int i = 0; i < ChartView.NUM_SERIES; i++) {
settingsDialog.setSeriesEnabled(i, chartView.isChartValueSeriesEnabled(i));
}
}
/**
* Given a location, creates a new data point for the chart. A data point is
* an array double[3 or 6], where:
* data[0] = the time or distance
* data[1] = the elevation
* data[2] = the speed
* and possibly:
* data[3] = power
* data[4] = cadence
* data[5] = heart rate
*
* This must be called in order for each point.
*
* @param location the location to get data for (this method takes ownership of that location)
* @param result the resulting point to fill out
*/
@VisibleForTesting
void fillDataPoint(Location location, double result[]) {
double timeOrDistance = Double.NaN,
elevation = Double.NaN,
speed = Double.NaN,
power = Double.NaN,
cadence = Double.NaN,
heartRate = Double.NaN;
if (location instanceof MyTracksLocation &&
((MyTracksLocation) location).getSensorDataSet() != null) {
SensorDataSet sensorData = ((MyTracksLocation) location).getSensorDataSet();
if (sensorData.hasPower()
&& sensorData.getPower().getState() == Sensor.SensorState.SENDING
&& sensorData.getPower().hasValue()) {
power = sensorData.getPower().getValue();
}
if (sensorData.hasCadence()
&& sensorData.getCadence().getState() == Sensor.SensorState.SENDING
&& sensorData.getCadence().hasValue()) {
cadence = sensorData.getCadence().getValue();
}
if (sensorData.hasHeartRate()
&& sensorData.getHeartRate().getState() == Sensor.SensorState.SENDING
&& sensorData.getHeartRate().hasValue()) {
heartRate = sensorData.getHeartRate().getValue();
}
}
// TODO: Account for segment splits?
Mode mode = chartView.getMode();
switch (mode) {
case BY_DISTANCE:
if (lastLocation != null) {
double d = lastLocation.distanceTo(location);
if (metricUnits) {
profileLength += d;
} else {
profileLength += d * UnitConversions.KM_TO_MI;
}
}
timeOrDistance = profileLength * UnitConversions.M_TO_KM;
break;
case BY_TIME:
if (startTime == -1) {
// Base case
startTime = location.getTime();
}
timeOrDistance = (location.getTime() - startTime);
break;
default:
Log.w(TAG, "ChartActivity unknown mode: " + mode);
}
elevationBuffer.setNext(metricUnits
? location.getAltitude()
: location.getAltitude() * UnitConversions.M_TO_FT);
elevation = elevationBuffer.getAverage();
if (lastLocation == null) {
if (Math.abs(location.getSpeed() - 128) > 1) {
speedBuffer.setNext(location.getSpeed());
}
} else if (TripStatisticsBuilder.isValidSpeed(
location.getTime(), location.getSpeed(), lastLocation.getTime(),
lastLocation.getSpeed(), speedBuffer)
&& (location.getSpeed() <= trackMaxSpeed)) {
speedBuffer.setNext(location.getSpeed());
}
speed = speedBuffer.getAverage() * UnitConversions.MS_TO_KMH;
if (!metricUnits) {
speed *= UnitConversions.KM_TO_MI;
}
if (!reportSpeed) {
if (speed != 0) {
// Format as hours per unit
speed = (60.0 / speed);
} else {
speed = Double.NaN;
}
}
// Keep a copy so the location can be reused.
lastLocation = location;
if (result != null) {
result[0] = timeOrDistance;
result[1] = elevation;
result[2] = speed;
result[3] = power;
result[4] = cadence;
result[5] = heartRate;
}
}
@Override
public void onProviderStateChange(ProviderState state) {
// We don't care.
}
@Override
public void onCurrentLocationChanged(Location loc) {
// We don't care.
}
@Override
public void onCurrentHeadingChanged(double heading) {
// We don't care.
}
@Override
public void onSelectedTrackChanged(Track track, boolean isRecording) {
runOnUiThread(new Runnable() {
@Override
public void run() {
busyPane.setVisibility(View.VISIBLE);
}
});
}
@Override
public void onTrackUpdated(Track track) {
if (track == null || track.getStatistics() == null) {
trackMaxSpeed = 0.0;
return;
}
trackMaxSpeed = track.getStatistics().getMaxSpeed();
}
@Override
public void clearTrackPoints() {
profileLength = 0;
lastLocation = null;
startTime = -1;
elevationBuffer.reset();
chartView.reset();
speedBuffer.reset();
pendingPoints.clear();
runOnUiThread(new Runnable() {
@Override
public void run() {
chartView.resetScroll();
}
});
}
@Override
public void onNewTrackPoint(Location loc) {
if (LocationUtils.isValidLocation(loc)) {
double[] point = new double[6];
fillDataPoint(loc, point);
pendingPoints.add(point);
}
}
@Override
public void onSampledOutTrackPoint(Location loc) {
// Still account for the point in the smoothing buffers.
fillDataPoint(loc, null);
}
@Override
public void onSegmentSplit() {
// Do nothing.
}
@Override
public void onNewTrackPointsDone() {
chartView.addDataPoints(pendingPoints);
pendingPoints.clear();
runOnUiThread(updateChart);
}
@Override
public void clearWaypoints() {
chartView.clearWaypoints();
}
@Override
public void onNewWaypoint(Waypoint wpt) {
chartView.addWaypoint(wpt);
}
@Override
public void onNewWaypointsDone() {
runOnUiThread(updateChart);
}
@Override
public boolean onUnitsChanged(boolean metric) {
if (metricUnits == metric) {
return false;
}
metricUnits = metric;
chartView.setMetricUnits(metricUnits);
runOnUiThread(new Runnable() {
@Override
public void run() {
chartView.requestLayout();
}
});
return true;
}
@Override
public boolean onReportSpeedChanged(boolean speed) {
if (reportSpeed == speed) {
return false;
}
reportSpeed = speed;
chartView.setReportSpeed(speed, this);
runOnUiThread(new Runnable() {
@Override
public void run() {
chartView.requestLayout();
}
});
return true;
}
@VisibleForTesting
ChartView getChartView() {
return chartView;
}
@VisibleForTesting
MenuItem getChartSettingsMenuItem() {
return chartSettingsMenuItem;
}
@VisibleForTesting
void setTrackMaxSpeed(double maxSpeed) {
trackMaxSpeed = maxSpeed;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
/**
* Manage the application menus.
*
* @author Sandor Dornbush
*/
class MenuManager {
private final MyTracks activity;
public MenuManager(MyTracks activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
activity.getMenuInflater().inflate(R.menu.main, menu);
// TODO: Replace search button with search widget if API level >= 11
return true;
}
public void onPrepareOptionsMenu(Menu menu, boolean hasRecorded,
boolean isRecording, boolean hasSelectedTrack) {
menu.findItem(R.id.menu_markers)
.setEnabled(hasRecorded && hasSelectedTrack);
menu.findItem(R.id.menu_record_track)
.setEnabled(!isRecording)
.setVisible(!isRecording);
menu.findItem(R.id.menu_stop_recording)
.setEnabled(isRecording)
.setVisible(isRecording);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_record_track: {
activity.startRecording();
return true;
}
case R.id.menu_stop_recording: {
activity.stopRecording();
return true;
}
case R.id.menu_tracks: {
activity.startActivityForResult(new Intent(activity, TrackList.class),
Constants.SHOW_TRACK);
return true;
}
case R.id.menu_markers: {
Intent startIntent = new Intent(activity, WaypointsList.class);
startIntent.putExtra("trackid", activity.getSelectedTrackId());
activity.startActivityForResult(startIntent, Constants.SHOW_WAYPOINT);
return true;
}
case R.id.menu_sensor_state: {
return startActivity(SensorStateActivity.class);
}
case R.id.menu_settings: {
return startActivity(SettingsActivity.class);
}
case R.id.menu_aggregated_statistics: {
return startActivity(AggregatedStatsActivity.class);
}
case R.id.menu_help: {
return startActivity(WelcomeActivity.class);
}
case R.id.menu_search: {
// TODO: Pass the current track ID and current location to do some fancier ranking.
activity.onSearchRequested();
}
}
return false;
}
private boolean startActivity(Class<? extends Activity> activityClass) {
activity.startActivity(new Intent(activity, activityClass));
return true;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import static android.content.Intent.ACTION_BOOT_COMPLETED;
import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.services.RemoveTempFilesService;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* This class handles MyTracks related broadcast messages.
*
* One example of a broadcast message that this class is interested in,
* is notification about the phone boot. We may want to resume a previously
* started tracking session if the phone crashed (hopefully not), or the user
* decided to swap the battery or some external event occurred which forced
* a phone reboot.
*
* This class simply delegates to {@link TrackRecordingService} to make a
* decision whether to continue with the previous track (if any), or just
* abandon it.
*
* @author Bartlomiej Niechwiej
*/
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "BootReceiver.onReceive: " + intent.getAction());
if (ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent startIntent = new Intent(context, TrackRecordingService.class);
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
context.startService(startIntent);
Intent removeTempFilesIntent = new Intent(context, RemoveTempFilesService.class);
context.startService(removeTempFilesIntent);
} else {
Log.w(TAG, "BootReceiver: unsupported action");
}
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.content.WaypointsColumns;
import com.google.android.apps.mytracks.services.ITrackRecordingService;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Activity which shows the list of waypoints in a track.
*
* @author Leif Hendrik Wilden
*/
public class WaypointsList extends ListActivity
implements View.OnClickListener {
private int contextPosition = -1;
private long trackId = -1;
private long selectedWaypointId = -1;
private ListView listView = null;
private Button insertWaypointButton = null;
private Button insertStatisticsButton = null;
private long recordingTrackId = -1;
private MyTracksProviderUtils providerUtils;
private TrackRecordingServiceConnection serviceConnection;
private Cursor waypointsCursor = null;
private final OnCreateContextMenuListener contextMenuListener =
new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderTitle(R.string.marker_list_context_menu_title);
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
contextPosition = info.position;
selectedWaypointId = WaypointsList.this.listView.getAdapter()
.getItemId(contextPosition);
Waypoint waypoint = providerUtils.getWaypoint(info.id);
if (waypoint != null) {
int type = waypoint.getType();
menu.add(Menu.NONE, Constants.MENU_SHOW, Menu.NONE, R.string.marker_list_show_on_map);
menu.add(Menu.NONE, Constants.MENU_EDIT, Menu.NONE, R.string.marker_list_edit_marker);
MenuItem deleteMenu = menu.add(
Menu.NONE, Constants.MENU_DELETE, Menu.NONE, R.string.marker_list_delete_marker);
deleteMenu.setEnabled(recordingTrackId < 0
|| type == Waypoint.TYPE_WAYPOINT
|| type == Waypoint.TYPE_STATISTICS
|| info.id != providerUtils.getLastWaypointId(recordingTrackId));
}
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
editWaypoint(id);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (!super.onMenuItemSelected(featureId, item)) {
switch (item.getItemId()) {
case Constants.MENU_SHOW: {
Intent result = new Intent();
result.putExtra("trackid", trackId);
result.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, selectedWaypointId);
setResult(RESULT_OK, result);
finish();
return true;
}
case Constants.MENU_EDIT: {
editWaypoint(selectedWaypointId);
return true;
}
case Constants.MENU_DELETE: {
deleteWaypoint(selectedWaypointId);
}
}
}
return false;
}
private void editWaypoint(long waypointId) {
Intent intent = new Intent(this, WaypointDetails.class);
intent.putExtra("trackid", trackId);
intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, waypointId);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
providerUtils = MyTracksProviderUtils.Factory.get(this);
serviceConnection = new TrackRecordingServiceConnection(this, null);
// We don't need a window title bar:
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mytracks_waypoints_list);
listView = getListView();
listView.setOnCreateContextMenuListener(contextMenuListener);
insertWaypointButton =
(Button) findViewById(R.id.waypointslist_btn_insert_waypoint);
insertWaypointButton.setOnClickListener(this);
insertStatisticsButton =
(Button) findViewById(R.id.waypointslist_btn_insert_statistics);
insertStatisticsButton.setOnClickListener(this);
SharedPreferences preferences = getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// TODO: Get rid of selected and recording track IDs
long selectedTrackId = -1;
if (preferences != null) {
recordingTrackId =
preferences.getLong(getString(R.string.recording_track_key), -1);
selectedTrackId =
preferences.getLong(getString(R.string.selected_track_key), -1);
}
boolean selectedRecording = selectedTrackId > 0
&& selectedTrackId == recordingTrackId;
insertWaypointButton.setEnabled(selectedRecording);
insertStatisticsButton.setEnabled(selectedRecording);
if (getIntent() != null && getIntent().getExtras() != null) {
trackId = getIntent().getExtras().getLong("trackid", -1);
} else {
trackId = -1;
}
final long firstWaypointId = providerUtils.getFirstWaypointId(trackId);
waypointsCursor = getContentResolver().query(
WaypointsColumns.CONTENT_URI, null,
WaypointsColumns.TRACKID + "=" + trackId + " AND "
+ WaypointsColumns._ID + "!=" + firstWaypointId, null, null);
startManagingCursor(waypointsCursor);
setListAdapter();
}
@Override
protected void onResume() {
super.onResume();
serviceConnection.bindIfRunning();
}
@Override
protected void onDestroy() {
serviceConnection.unbind();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_only, menu);
return true;
}
/* Callback from menu/search_only.xml */
public void onSearch(@SuppressWarnings("unused") MenuItem i) {
onSearchRequested();
}
@Override
public void onClick(View v) {
WaypointCreationRequest request;
switch (v.getId()) {
case R.id.waypointslist_btn_insert_waypoint:
request = WaypointCreationRequest.DEFAULT_MARKER;
break;
case R.id.waypointslist_btn_insert_statistics:
request = WaypointCreationRequest.DEFAULT_STATISTICS;
break;
default:
return;
}
long id = insertWaypoint(request);
if (id < 0) {
Toast.makeText(this, R.string.marker_insert_error, Toast.LENGTH_LONG).show();
Log.e(Constants.TAG, "Failed to insert marker.");
return;
}
Intent intent = new Intent(this, WaypointDetails.class);
intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, id);
startActivity(intent);
}
private long insertWaypoint(WaypointCreationRequest request) {
try {
ITrackRecordingService trackRecordingService = serviceConnection.getServiceIfBound();
if (trackRecordingService != null) {
long waypointId = trackRecordingService.insertWaypoint(request);
if (waypointId >= 0) {
Toast.makeText(this, R.string.marker_insert_success, Toast.LENGTH_LONG).show();
return waypointId;
}
} else {
Log.e(TAG, "Not connected to service, not inserting waypoint");
}
} catch (RemoteException e) {
Log.e(Constants.TAG, "Cannot insert marker.", e);
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "Cannot insert marker.", e);
}
return -1;
}
private void setListAdapter() {
// Get a cursor with all tracks
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.mytracks_marker_item,
waypointsCursor,
new String[] { WaypointsColumns.NAME, WaypointsColumns.TIME,
WaypointsColumns.CATEGORY, WaypointsColumns.TYPE },
new int[] { R.id.waypointslist_item_name,
R.id.waypointslist_item_time,
R.id.waypointslist_item_category,
R.id.waypointslist_item_icon });
final int timeIdx =
waypointsCursor.getColumnIndexOrThrow(WaypointsColumns.TIME);
final int typeIdx =
waypointsCursor.getColumnIndexOrThrow(WaypointsColumns.TYPE);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == timeIdx) {
long time = cursor.getLong(timeIdx);
TextView textView = (TextView) view;
if (time == 0) {
textView.setVisibility(View.GONE);
} else {
textView.setText(StringUtils.formatDateTime(WaypointsList.this, time));
textView.setVisibility(View.VISIBLE);
}
} else if (columnIndex == typeIdx) {
int type = cursor.getInt(typeIdx);
ImageView imageView = (ImageView) view;
imageView.setImageDrawable(getResources().getDrawable(
type == Waypoint.TYPE_STATISTICS
? R.drawable.ylw_pushpin
: R.drawable.blue_pushpin));
} else {
TextView textView = (TextView) view;
textView.setText(cursor.getString(columnIndex));
textView.setVisibility(
textView.getText().length() < 1 ? View.GONE : View.VISIBLE);
}
return true;
}
});
setListAdapter(adapter);
}
/**
* Deletes the way point with the given id.
* Prompts the user if he want to really delete it.
*/
public void deleteWaypoint(final long waypointId) {
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.marker_list_delete_marker_confirm_message));
builder.setTitle(getString(R.string.generic_confirm_title));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton(getString(R.string.generic_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
providerUtils.deleteWaypoint(waypointId,
new DescriptionGeneratorImpl(WaypointsList.this));
}
});
builder.setNegativeButton(getString(R.string.generic_no),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
}
| Java |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.util.ApiAdapterFactory;
import com.google.android.maps.mytracks.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
/**
* A utility class that can be used to delete all tracks and track points
* from the provider, including asking for confirmation from the user via
* a dialog.
*
* @author Leif Hendrik Wilden
*/
public class DeleteAllTracks extends Handler {
private final Context context;
private final Runnable done;
public DeleteAllTracks(Context context, Runnable done) {
this.context = context;
this.done = done;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(
context.getString(R.string.track_list_delete_all_confirm_message));
builder.setTitle(context.getString(R.string.generic_confirm_title));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton(context.getString(R.string.generic_yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Log.w(Constants.TAG, "deleting all!");
MyTracksProviderUtils.Factory.get(context).deleteAllTracks();
SharedPreferences prefs = context.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
// TODO: Go through data manager
editor.putLong(context.getString(R.string.selected_track_key), -1);
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor);
if (done != null) {
Handler h = new Handler();
h.post(done);
}
}
});
builder.setNegativeButton(context.getString(R.string.generic_no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.common.annotations.VisibleForTesting;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import java.io.File;
/**
* A service to remove My Tracks temp files older than one hour on the SD card.
*
* @author Jimmy Shih
*/
public class RemoveTempFilesService extends Service {
private static final String TAG = RemoveTempFilesService.class.getSimpleName();
private static final int ONE_HOUR_IN_MILLISECONDS = 60 * 60 * 1000;
private RemoveTempFilesAsyncTask removeTempFilesAsyncTask = null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Setup an alarm to repeatedly call this service
Intent alarmIntent = new Intent(this, RemoveTempFilesService.class);
PendingIntent pendingIntent = PendingIntent.getService(
this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + ONE_HOUR_IN_MILLISECONDS, AlarmManager.INTERVAL_HOUR,
pendingIntent);
// Invoke the AsyncTask to cleanup the temp files
if (removeTempFilesAsyncTask == null
|| removeTempFilesAsyncTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
removeTempFilesAsyncTask = new RemoveTempFilesAsyncTask();
removeTempFilesAsyncTask.execute((Void[]) null);
}
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class RemoveTempFilesAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// Can't do anything
return null;
}
cleanTempDirectory(TrackFileFormat.GPX.getExtension());
cleanTempDirectory(TrackFileFormat.KML.getExtension());
cleanTempDirectory(TrackFileFormat.CSV.getExtension());
cleanTempDirectory(TrackFileFormat.TCX.getExtension());
return null;
}
@Override
protected void onPostExecute(Void result) {
stopSelf();
}
}
private void cleanTempDirectory(String name) {
FileUtils fileUtils = new FileUtils();
String dirName = fileUtils.buildExternalDirectoryPath(name, "tmp");
File dir = new File(dirName);
cleanTempDirectory(dir);
}
/**
* Removes temp files in a directory older than one hour.
*
* @param dir the directory
* @return the number of files removed.
*/
@VisibleForTesting
int cleanTempDirectory(File dir) {
if (!dir.exists()) {
return 0;
}
int count = 0;
long oneHourAgo = System.currentTimeMillis() - ONE_HOUR_IN_MILLISECONDS;
for (File f : dir.listFiles()) {
if (f.lastModified() < oneHourAgo) {
if (!f.delete()) {
Log.e(TAG, "Unable to delete file: " + f.getAbsolutePath());
} else {
count++;
}
}
}
return count;
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
/**
* This is a simple location listener policy that will always dictate the same
* polling interval.
*
* @author Sandor Dornbush
*/
public class AbsoluteLocationListenerPolicy implements LocationListenerPolicy {
/**
* The interval to request for gps signal.
*/
private final long interval;
/**
* @param interval The interval to request for gps signal
*/
public AbsoluteLocationListenerPolicy(final long interval) {
this.interval = interval;
}
/**
* @return The interval given in the constructor
*/
public long getDesiredPollingInterval() {
return interval;
}
/**
* Discards the idle time.
*/
public void updateIdleTime(long idleTime) {
}
/**
* Returns the minimum distance between updates.
* Get all updates to properly measure moving time.
*/
public int getMinDistance() {
return 0;
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import com.google.android.apps.mytracks.util.UnitConversions;
import android.util.Log;
/**
* Execute a task on a time or distance schedule.
*
* @author Sandor Dornbush
*/
public class PeriodicTaskExecutor {
/**
* The frequency of the task.
* A value greater than zero is a frequency in time.
* A value less than zero is considered a frequency in distance.
*/
private int taskFrequency = 0;
/**
* The next distance when the task should execute.
*/
private double nextTaskDistance = 0;
/**
* Time based executor.
*/
private TimerTaskExecutor timerExecutor = null;
private boolean metricUnits;
private final TrackRecordingService service;
private final PeriodicTaskFactory factory;
private PeriodicTask task;
public PeriodicTaskExecutor(TrackRecordingService service, PeriodicTaskFactory factory) {
this.service = service;
this.factory = factory;
}
/**
* Restores the manager.
*/
public void restore() {
// TODO: Decouple service from this class once and forever.
if (!service.isRecording()) {
return;
}
if (!isTimeFrequency()) {
if (timerExecutor != null) {
timerExecutor.shutdown();
timerExecutor = null;
}
}
if (taskFrequency == 0) {
return;
}
// Try to make the task.
task = factory.create(service);
// Returning null is ok.
if (task == null) {
return;
}
task.start();
if (isTimeFrequency()) {
if (timerExecutor == null) {
timerExecutor = new TimerTaskExecutor(task, service);
}
timerExecutor.scheduleTask(taskFrequency * 60000L);
} else {
// For distance based splits.
calculateNextTaskDistance();
}
}
/**
* Shuts down the manager.
*/
public void shutdown() {
if (task != null) {
task.shutdown();
task = null;
}
if (timerExecutor != null) {
timerExecutor.shutdown();
timerExecutor = null;
}
}
/**
* Calculates the next distance when the task should execute.
*/
void calculateNextTaskDistance() {
// TODO: Decouple service from this class once and forever.
if (!service.isRecording() || task == null) {
return;
}
if (!isDistanceFrequency()) {
nextTaskDistance = Double.MAX_VALUE;
Log.d(TAG, "SplitManager: Distance splits disabled.");
return;
}
double distance = service.getTripStatistics().getTotalDistance() * UnitConversions.M_TO_KM;
if (!metricUnits) {
distance *= UnitConversions.KM_TO_MI;
}
// The index will be negative since the frequency is negative.
int index = (int) (distance / taskFrequency);
index -= 1;
nextTaskDistance = taskFrequency * index;
Log.d(TAG, "SplitManager: Next split distance: " + nextTaskDistance);
}
/**
* Updates executer with new trip statistics.
*/
public void update() {
if (!isDistanceFrequency() || task == null) {
return;
}
// Convert the distance in meters to km or mi.
double distance = service.getTripStatistics().getTotalDistance() * UnitConversions.M_TO_KM;
if (!metricUnits) {
distance *= UnitConversions.KM_TO_MI;
}
if (distance > nextTaskDistance) {
task.run(service);
calculateNextTaskDistance();
}
}
private boolean isTimeFrequency() {
return taskFrequency > 0;
}
private boolean isDistanceFrequency() {
return taskFrequency < 0;
}
/**
* Sets the task frequency.
* < 0 Use the absolute value as a distance in the current measurement km
* or mi
* 0 Turn off the task
* > 0 Use the value as a time in minutes
* @param taskFrequency The frequency in time or distance
*/
public void setTaskFrequency(int taskFrequency) {
Log.d(TAG, "setTaskFrequency: taskFrequency = " + taskFrequency);
this.taskFrequency = taskFrequency;
restore();
}
public void setMetricUnits(boolean metricUnits) {
this.metricUnits = metricUnits;
calculateNextTaskDistance();
}
double getNextTaskDistance() {
return nextTaskDistance;
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import static com.google.android.apps.mytracks.Constants.TAG;
import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import java.util.HashMap;
/**
* This class will periodically announce the user's trip statistics for Froyo and future handsets.
* This class will request and release audio focus.
*
* @author Sandor Dornbush
*/
public class FroyoStatusAnnouncerTask extends StatusAnnouncerTask {
private final static HashMap<String, String> SPEECH_PARAMS = new HashMap<String, String>();
static {
SPEECH_PARAMS.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "not_used");
}
private final AudioManager audioManager;
private final OnUtteranceCompletedListener utteranceListener =
new OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
int result = audioManager.abandonAudioFocus(null);
if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
Log.w(TAG, "FroyoStatusAnnouncerTask: Failed to relinquish audio focus");
}
}
};
public FroyoStatusAnnouncerTask(Context context) {
super(context);
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
@Override
protected void onTtsReady() {
super.onTtsReady();
tts.setOnUtteranceCompletedListener(utteranceListener);
}
@Override
protected synchronized void speakAnnouncement(String announcement) {
int result = audioManager.requestAudioFocus(null,
TextToSpeech.Engine.DEFAULT_STREAM,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
Log.w(TAG, "FroyoStatusAnnouncerTask: Request for audio focus failed.");
}
// We don't care about the utterance id.
// It is supplied here to force onUtteranceCompleted to be called.
tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, SPEECH_PARAMS);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.