code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
#
# GENPlus DROID
# Copyright 2011 Stephen Damm (Halsafar)
# All rights reserved.
# shinhalsafar@gmail.com
#
# OPTIONS
ENABLE_BLUETOOTH := 0
ENABLE_DEBUG := 0
ENABLE_DEBUG_LOGGING := 1
# STORE VARS FOR AFTER CLEANING
LOCAL_PATH := $(call my-dir)
ORG_PATH := $(LOCAL_PATH)
# BUILD ALL EXTERNAL LIBS
include $(CLEAR_VARS)
include $(call all-makefiles-under,$(LOCAL_PATH))
# BUILD EMU LIB
include $(CLEAR_VARS)
LOCAL_PATH := $(ORG_PATH)/
LOCAL_MODULE_TAGS := user
LOCAL_ARM_MODE := arm
LOCAL_MODULE := libemu
LIB_EMU_DIR := libemu
MY_FILES := \
$(wildcard $(LOCAL_PATH)/../genplusgx/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/cart_hw/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/cart_hw/svp/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/input_hw/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/m68k/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/ntsc/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/sound/*.c) \
$(wildcard $(LOCAL_PATH)/../genplusgx/z80/*.c)
# Correct the file names
MY_FILES := $(MY_FILES:$(LOCAL_PATH)/%=%)
# Emulator Engine source files that we will compile.
LOCAL_SRC_FILES := \
$(MY_FILES) \
$(LIB_EMU_DIR)/rewind.c \
$(LIB_EMU_DIR)/GraphicsDriver.cpp \
$(LIB_EMU_DIR)/InputHandler.cpp \
$(LIB_EMU_DIR)/Quad.cpp \
EmulatorBridge.cpp \
Application.cpp
ifeq ($(ENABLE_BLUETOOTH), 1)
LOCAL_SRC_FILES += $(LIB_EMU_DIR)/bluetooth/BluetoothFacade.cpp
endif
# INCLUDE DIRS
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../ \
$(LOCAL_PATH)/libemu/ \
$(LOCAL_PATH)/../genplusgx/ \
$(LOCAL_PATH)/../genplusgx/m68k \
$(LOCAL_PATH)/../genplusgx/z80 \
$(LOCAL_PATH)/../genplusgx/input_hw \
$(LOCAL_PATH)/../genplusgx/sound \
$(LOCAL_PATH)/../genplusgx/cart_hw \
$(LOCAL_PATH)/../genplusgx/cart_hw/svp \
$(LOCAL_PATH)/../genplusgx/ntsc \
$(LOCAL_PATH)/../genplusgx/android
# Debug
LOCAL_CFLAGS := -DLOG_TAG=\"GENPlusDroid\"
ifeq ($(ENABLE_DEBUG), 1)
# DEBUG FLAGS
LOCAL_CFLAGS += -g
else
# RELEASE/Optimization flags
LOCAL_CFLAGS += -O3 \
-ffast-math \
-fomit-frame-pointer \
-fvisibility=hidden \
-funit-at-a-time \
-fms-extensions \
-finline-functions
#-funroll-loops \
#-finline-functions \
#-mfloat-abi=softfp \
#-mfpu=neon
#--param inline-unit-growth=1000 \
#--param large-function-growth=5000 \
#--param max-inline-insns-single=2450
# -fvisibility=hidden
endif
ifeq ($(ENABLE_DEBUG_LOGGING), 1)
LOCAL_CFLAGS += -DDEBUG_LOGGING
endif
# Compiler Warning flags
#LOCAL_CFLAGS += -Winline
LOCAL_CFLAGS += -Wno-write-strings
# Custom Emulator Flags
LOCAL_CFLAGS += -DHALDROID
# FCEU Flags
LOCAL_CFLAGS += -DLSB_FIRST -DFRAMESKIP -DMAXPATHLEN=1024 -DUSE_32BPP_RENDERING $(MACHDEP)
# C99
LOCAL_CFLAGS += -std=c99
# Copy C Flags to CXX flags
LOCAL_CPPFLAGS := $(LOCAL_CFLAGS)
LOCAL_CXXFLAGS := $(LOCAL_CFLAGS)
# Native libs to link to
LOCAL_LDLIBS := -lz -llog -lGLESv2
# All of the shared libraries we link against.
LOCAL_SHARED_LIBRARIES := libzip libgnupng
# Static libraries.
LOCAL_STATIC_LIBRARIES :=
# Don't prelink this library. For more efficient code, you may want
# to add this library to the prelink map and set this to true. However,
# it's difficult to do this for applications that are not supplied as
# part of a system image.
LOCAL_PRELINK_MODULE := false
include $(BUILD_SHARED_LIBRARY)
| zyking1987-genplus-droid | jni/Android.mk | Makefile | gpl2 | 3,524 |
/**
* GENPlusDroid
* Copyright 2011 Stephen Damm (Halsafar)
* All rights reserved.
* shinhalsafar@gmail.com
*/
#include <jni.h>
#include "libpng/png.h"
#include "common.h"
#include "GraphicsDriver.h"
#include "InputHandler.h"
extern "C"
{
#include "rewind.h"
}
#include "genplusgx/types.h"
#define TURBO_FRAMES_TO_EMULATE 10
#define GENPLUS_RENDER_TEXTURE_WIDTH 320.0
#define GENPLUS_RENDER_TEXTURE_HEIGHT 224.0
#define SCREEN_RENDER_TEXTURE_WIDTH 512.0
#define SCREEN_RENDER_TEXTURE_HEIGHT 512.0
#define SCREEN_RENDER_BYTE_BY_PIXEL 4
enum Buttons
{
BUTTON_INDEX_A,
BUTTON_INDEX_B,
BUTTON_INDEX_C,
BUTTON_INDEX_X,
BUTTON_INDEX_Y,
BUTTON_INDEX_Z,
BUTTON_INDEX_START,
BUTTON_INDEX_REWIND,
BUTTON_INDEX_FORWARD,
BUTTON_INDEX_LEFT,
BUTTON_INDEX_UP,
BUTTON_INDEX_RIGHT,
BUTTON_INDEX_DOWN,
BUTTON_INDEX_COUNT
};
class Application
{
public:
Application();
~Application();
int init(JNIEnv *env, const char* apkPath);
int initGraphics();
int initAudioBuffers(const int sizeInSamples);
void setAudioSampleRate(int rate);
void destroy();
int setPaths(const char* externalStorageDir, const char* romDir,
const char* stateDir, const char* sramDir,
const char* cheatsDir);
void processInput();
int loadROM(const char* filename);
void closeROM();
void resetROM();
void saveSRam(const char* romName);
void loadSRam(const char* romName);
void saveState(const int i);
void loadState(const int i);
void selectState(const int i);
void step(const JNIEnv *env);
void draw(const JNIEnv *env);
void setAudioEnabled(const bool b);
size_t readAudio(jshort* in, const size_t samples);
size_t getAudioBufferSize() { return _audioBufferSize; }
size_t getCurrentEmuSamples() { return _ssize; }
unsigned char* getAudioBuffer();
void setFrameSkip(int i)
{
if (i < 0) i = 0;
if (i > 9) i = 9;
_frameSkip = i;
}
void setRewind(bool b);
bool isRomLoaded() { return _romLoaded; }
bool isInitialized() { return _initialized; }
bool isAudioInit() { return _audioInitialized; }
void setGenPlusVideoChanged();
GraphicsDriver Graphics;
InputHandler Input;
private:
bool _initialized;
bool _romLoaded;
bool _fceuInitialized;
bool _audioInitialized;
double _timeStart;
double _timeEnd;
double _timeDelta;
int _frameSkip;
int _frameSkipCount;
char* _apkPath;
char* _stateDir;
char* _sramDir;
char* _currentRom;
// video
int _viewPortW;
int _viewPortH;
// audio
int32 _ssize;
int _sampleRate;
size_t _audioBufferSize;
// rewinding
bool _rewindTouched;
bool _rewindEnabled;
uint8 *_rewindBuf;
state_manager_t* _rewindState;
int makePath(const char* dirName, char* outBuffer);
};
| zyking1987-genplus-droid | jni/Application.h | C++ | gpl2 | 3,003 |
#
# GENPlusDroid
# Copyright 2011 Stephen Damm (Halsafar)
# All rights reserved.
# shinhalsafar@gmail.com
#
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := user
LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_PACKAGE_NAME := GenesisDroid
LOCAL_JNI_SHARED_LIBRARIES := libzip libgnupng libemu
include $(BUILD_PACKAGE)
# ============================================================
MY_DIR := $(LOCAL_PATH)
# Also build all of the sub-targets under this one: the shared library.
include $(call all-makefiles-under,$(MY_DIR))
| zyking1987-genplus-droid | Android.mk | Makefile | gpl2 | 561 |
/*
* Copyright 2013 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.gcm.demo.app;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* This {@code WakefulBroadcastReceiver} takes care of creating and managing a
* partial wake lock for your app. It passes off the work of processing the GCM
* message to an {@code IntentService}, while ensuring that the device does not
* go back to sleep in the transition. The {@code IntentService} calls
* {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to
* release the wake lock.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| zyf404283839-gcm-demo-client | gcm-client/GcmClient/src/main/java/com/google/android/gcm/demo/app/GcmBroadcastReceiver.java | Java | asf20 | 1,788 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.gcm.demo.app;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {@code IntentService} does the actual handling of the GCM message.
* {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {@code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| zyf404283839-gcm-demo-client | gcm-client/GcmClient/src/main/java/com/google/android/gcm/demo/app/GcmIntentService.java | Java | asf20 | 4,598 |
/*
* Copyright 2013 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.gcm.demo.app;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
String SENDER_ID = "Your-Sender-ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Demo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
Context context;
String regid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
@Override
protected void onResume() {
super.onResume();
// Check device for Play Services APK.
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Stores the registration ID and the app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGcmPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Gets the current registration ID for application on GCM service, if there is one.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
// Send an upstream message.
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGcmPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
| zyf404283839-gcm-demo-client | gcm-client/GcmClient/src/main/java/com/google/android/gcm/demo/app/DemoActivity.java | Java | asf20 | 9,852 |
/*
* 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.gcm.demo.server;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is thread-safe but not persistent (it will lost the data when the
* app is restarted) - it is meant just as an example.
*/
public final class Datastore {
private static final List<String> regIds = new ArrayList<String>();
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
synchronized (regIds) {
regIds.add(regId);
}
}
/**
* Unregisters a device.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
synchronized (regIds) {
regIds.remove(regId);
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
synchronized (regIds) {
regIds.remove(oldId);
regIds.add(newId);
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
synchronized (regIds) {
return new ArrayList<String>(regIds);
}
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/Datastore.java | Java | asf20 | 2,049 |
/*
* 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.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/UnregisterServlet.java | Java | asf20 | 1,429 |
/*
* 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.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty()) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/HomeServlet.java | Java | asf20 | 2,340 |
/*
* 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.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/BaseServlet.java | Java | asf20 | 2,802 |
/*
* 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.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/RegisterServlet.java | Java | asf20 | 1,450 |
/*
* 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.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
private static final int MULTICAST_SIZE = 1000;
private Sender sender;
private static final Executor threadPool = Executors.newFixedThreadPool(5);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String registrationId = devices.get(0);
Message message = new Message.Builder().build();
Result result = sender.send(message, registrationId, 5);
status = "Sent message to one device: " + result;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == MULTICAST_SIZE || counter == total) {
asyncSend(partialDevices);
partialDevices.clear();
tasks++;
}
}
status = "Asynchronously sending " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
private void asyncSend(List<String> partialDevices) {
// make a copy
final List<String> devices = new ArrayList<String>(partialDevices);
threadPool.execute(new Runnable() {
public void run() {
Message message = new Message.Builder().build();
MulticastResult multicastResult;
try {
multicastResult = sender.send(message, devices, 5);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error posting messages", e);
return;
}
List<Result> results = multicastResult.getResults();
// analyze the results
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logger.fine("Succesfully sent message to device: " + regId +
"; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.info("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
logger.info("Unregistered device: " + regId);
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to " + regId + ": " + error);
}
}
}
}});
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/SendAllMessagesServlet.java | Java | asf20 | 5,498 |
/*
* 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.gcm.demo.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from a
* {@value #PATH} file located in the classpath (typically under
* {@code WEB-INF/classes}).
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String PATH = "/api.key";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
logger.info("Reading " + PATH + " from resources (probably from " +
"WEB-INF/classes");
String key = getKey();
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key);
}
/**
* Gets the access key.
*/
protected String getKey() {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(PATH);
if (stream == null) {
throw new IllegalStateException("Could not find file " + PATH +
" on web resources)");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
String key = reader.readLine();
return key;
} catch (IOException e) {
throw new RuntimeException("Could not read file " + PATH, e);
} finally {
try {
reader.close();
} catch (IOException e) {
logger.log(Level.WARNING, "Exception closing " + PATH, e);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/src/com/google/android/gcm/demo/server/ApiKeyInitializer.java | Java | asf20 | 2,369 |
<jsp:forward page="/home"/>
| zyf404283839-gcm-demo-client | samples/gcm-demo-server/WebContent/index.jsp | Java Server Pages | asf20 | 28 |
/*
* 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.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is neither persistent (it will lost the data when the app is
* restarted) nor thread safe.
*/
public final class Datastore {
static final int MULTICAST_SIZE = 1000;
private static final String DEVICE_TYPE = "Device";
private static final String DEVICE_REG_ID_PROPERTY = "regId";
private static final String MULTICAST_TYPE = "Multicast";
private static final String MULTICAST_REG_IDS_PROPERTY = "regIds";
private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder
.withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE);
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private static final DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*
* @param regId device's registration id.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity != null) {
logger.fine(regId + " is already registered; ignoring.");
return;
}
entity = new Entity(DEVICE_TYPE);
entity.setProperty(DEVICE_REG_ID_PROPERTY, regId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Unregisters a device.
*
* @param regId device's registration id.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity == null) {
logger.warning("Device " + regId + " already unregistered");
} else {
Key key = entity.getKey();
datastore.delete(key);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(oldId);
if (entity == null) {
logger.warning("No device for registration id " + oldId);
return;
}
entity.setProperty(DEVICE_REG_ID_PROPERTY, newId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
List<String> devices;
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE);
Iterable<Entity> entities =
datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS);
devices = new ArrayList<String>();
for (Entity entity : entities) {
String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY);
devices.add(device);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return devices;
}
/**
* Gets the number of total devices.
*/
public static int getTotalDevices() {
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE).setKeysOnly();
List<Entity> allKeys =
datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS);
int total = allKeys.size();
logger.fine("Total number of devices: " + total);
txn.commit();
return total;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
private static Entity findDeviceByRegId(String regId) {
Query query = new Query(DEVICE_TYPE)
.addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId);
PreparedQuery preparedQuery = datastore.prepare(query);
List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS);
Entity entity = null;
if (!entities.isEmpty()) {
entity = entities.get(0);
}
int size = entities.size();
if (size > 0) {
logger.severe(
"Found " + size + " entities for regId " + regId + ": " + entities);
}
return entity;
}
/**
* Creates a persistent record with the devices to be notified using a
* multicast message.
*
* @param devices registration ids of the devices.
* @return encoded key for the persistent record.
*/
public static String createMulticast(List<String> devices) {
logger.info("Storing multicast for " + devices.size() + " devices");
String encodedKey;
Transaction txn = datastore.beginTransaction();
try {
Entity entity = new Entity(MULTICAST_TYPE);
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
Key key = entity.getKey();
encodedKey = KeyFactory.keyToString(key);
logger.fine("multicast key: " + encodedKey);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return encodedKey;
}
/**
* Gets a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static List<String> getMulticast(String encodedKey) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
entity = datastore.get(key);
@SuppressWarnings("unchecked")
List<String> devices =
(List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY);
txn.commit();
return devices;
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return Collections.emptyList();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
* @param devices new list of registration ids of the devices.
*/
public static void updateMulticast(String encodedKey, List<String> devices) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return;
}
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Deletes a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static void deleteMulticast(String encodedKey) {
Transaction txn = datastore.beginTransaction();
try {
Key key = KeyFactory.stringToKey(encodedKey);
datastore.delete(key);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/Datastore.java | Java | asf20 | 8,837 |
/*
* 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.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/UnregisterServlet.java | Java | asf20 | 1,429 |
/*
* 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.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
int total = Datastore.getTotalDevices();
if (total == 0) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + total + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/HomeServlet.java | Java | asf20 | 2,295 |
/*
* 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.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/BaseServlet.java | Java | asf20 | 2,802 |
/*
* 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.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that sends a message to a device.
* <p>
* This servlet is invoked by AppEngine's Push Queue mechanism.
*/
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount";
private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName";
private static final int MAX_RETRY = 3;
static final String PARAMETER_DEVICE = "device";
static final String PARAMETER_MULTICAST = "multicastKey";
private Sender sender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp) {
resp.setStatus(200);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getHeader(HEADER_QUEUE_NAME) == null) {
throw new IOException("Missing header " + HEADER_QUEUE_NAME);
}
String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT);
logger.fine("retry count: " + retryCountHeader);
if (retryCountHeader != null) {
int retryCount = Integer.parseInt(retryCountHeader);
if (retryCount > MAX_RETRY) {
logger.severe("Too many retries, dropping task");
taskDone(resp);
return;
}
}
String regId = req.getParameter(PARAMETER_DEVICE);
if (regId != null) {
sendSingleMessage(regId, resp);
return;
}
String multicastKey = req.getParameter(PARAMETER_MULTICAST);
if (multicastKey != null) {
sendMulticastMessage(multicastKey, resp);
return;
}
logger.severe("Invalid request!");
taskDone(resp);
return;
}
private Message createMessage() {
Message message = new Message.Builder().build();
return message;
}
private void sendSingleMessage(String regId, HttpServletResponse resp) {
logger.info("Sending message to device " + regId);
Message message = createMessage();
Result result;
try {
result = sender.sendNoRetry(message, regId);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
taskDone(resp);
return;
}
if (result == null) {
retryTask(resp);
return;
}
if (result.getMessageId() != null) {
logger.info("Succesfully sent message to device " + regId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.finest("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to device " + regId
+ ": " + error);
}
}
}
private void sendMulticastMessage(String multicastKey,
HttpServletResponse resp) {
// Recover registration ids from datastore
List<String> regIds = Datastore.getMulticast(multicastKey);
Message message = createMessage();
MulticastResult multicastResult;
try {
multicastResult = sender.sendNoRetry(message, regIds);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
multicastDone(resp, multicastKey);
return;
}
boolean allDone = true;
// check if any registration id must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = regIds.get(i);
Datastore.updateRegistration(regId, canonicalRegId);
}
}
}
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retriableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = regIds.get(i);
logger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
}
if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retriableRegIds.add(regId);
}
}
}
if (!retriableRegIds.isEmpty()) {
// update task
Datastore.updateMulticast(multicastKey, retriableRegIds);
allDone = false;
retryTask(resp);
}
}
if (allDone) {
multicastDone(resp, multicastKey);
} else {
retryTask(resp);
}
}
private void multicastDone(HttpServletResponse resp, String encodedKey) {
Datastore.deleteMulticast(encodedKey);
taskDone(resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/SendMessageServlet.java | Java | asf20 | 7,021 |
/*
* 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.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/RegisterServlet.java | Java | asf20 | 1,450 |
/*
* 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.gcm.demo.server;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
Queue queue = QueueFactory.getQueue("gcm");
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String device = devices.get(0);
queue.add(withUrl("/send").param(
SendMessageServlet.PARAMETER_DEVICE, device));
status = "Single message queued for registration id " + device;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
String multicastKey = Datastore.createMulticast(partialDevices);
logger.fine("Queuing " + partialSize + " devices on multicast " +
multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/send")
.param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey)
.method(Method.POST);
queue.add(taskOptions);
partialDevices.clear();
tasks++;
}
}
status = "Queued tasks to send " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/SendAllMessagesServlet.java | Java | asf20 | 3,528 |
/*
* 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.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from the App Engine datastore.
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String ENTITY_KIND = "Settings";
private static final String ENTITY_KEY = "MyKey";
private static final String ACCESS_KEY_FIELD = "ApiKey";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
Entity entity;
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
entity = new Entity(key);
// NOTE: it's not possible to change entities in the local server, so
// it will be necessary to hardcode the API key below if you are running
// it locally.
entity.setProperty(ACCESS_KEY_FIELD,
"replace_this_text_by_your_Simple_API_Access_key");
datastore.put(entity);
logger.severe("Created fake key. Please go to App Engine admin "
+ "console, change its value to your API Key (the entity "
+ "type is '" + ENTITY_KIND + "' and its field to be changed is '"
+ ACCESS_KEY_FIELD + "'), then restart the server!");
}
String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/src/com/google/android/gcm/demo/server/ApiKeyInitializer.java | Java | asf20 | 2,712 |
<jsp:forward page="/home"/>
| zyf404283839-gcm-demo-client | samples/gcm-demo-appengine/WebContent/index.jsp | Java Server Pages | asf20 | 28 |
/*
* 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.gcm.demo.app;
import android.content.Context;
import android.content.Intent;
/**
* Helper class providing methods and constants common to other classes in the
* app.
*/
public final class CommonUtilities {
/**
* Base URL of the Demo Server (such as http://my_host:8080/gcm-demo)
*/
static final String SERVER_URL = null;
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = null;
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
/**
* Intent used to display a message in the screen.
*/
static final String DISPLAY_MESSAGE_ACTION =
"com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-client/src/com/google/android/gcm/demo/app/CommonUtilities.java | Java | asf20 | 1,993 |
/*
* 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.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered,
registrationId));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message. Extras: " + intent.getExtras());
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-client/src/com/google/android/gcm/demo/app/GCMIntentService.java | Java | asf20 | 4,223 |
/*
* 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.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| zyf404283839-gcm-demo-client | samples/gcm-demo-client/src/com/google/android/gcm/demo/app/ServerUtilities.java | Java | asf20 | 7,034 |
/*
* 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.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import com.google.android.gcm.GCMRegistrar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
/*
* Typically, an application registers automatically, so options
* below are disabled. Uncomment them if you want to manually
* register or unregister the device (you will also need to
* uncomment the equivalent options on options_menu.xml).
*/
/*
case R.id.options_register:
GCMRegistrar.register(this, SENDER_ID);
return true;
case R.id.options_unregister:
GCMRegistrar.unregister(this);
return true;
*/
case R.id.options_clear:
mDisplay.setText(null);
return true;
case R.id.options_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
} | zyf404283839-gcm-demo-client | samples/gcm-demo-client/src/com/google/android/gcm/demo/app/DemoActivity.java | Java | asf20 | 5,509 |
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gcm;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | zyf404283839-gcm-demo-client | gcm-client-deprecated/gen/com/google/android/gcm/BuildConfig.java | Java | asf20 | 164 |
/*
* 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.gcm;
/**
* Constants used by the GCM library.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMConstants {
/**
* Intent sent to GCM to register the application.
*/
public static final String INTENT_TO_GCM_REGISTRATION =
"com.google.android.c2dm.intent.REGISTER";
/**
* Intent sent to GCM to unregister the application.
*/
public static final String INTENT_TO_GCM_UNREGISTRATION =
"com.google.android.c2dm.intent.UNREGISTER";
/**
* Intent sent by GCM indicating with the result of a registration request.
*/
public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK =
"com.google.android.c2dm.intent.REGISTRATION";
/**
* Intent used by the GCM library to indicate that the registration call
* should be retried.
*/
public static final String INTENT_FROM_GCM_LIBRARY_RETRY =
"com.google.android.gcm.intent.RETRY";
/**
* Intent sent by GCM containing a message.
*/
public static final String INTENT_FROM_GCM_MESSAGE =
"com.google.android.c2dm.intent.RECEIVE";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to indicate which senders (Google API project ids) can send messages to
* the application.
*/
public static final String EXTRA_SENDER = "sender";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to get the application info.
*/
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate that the application has been unregistered.
*/
public static final String EXTRA_UNREGISTERED = "unregistered";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate an error when the registration fails.
* See constants starting with ERROR_ for possible values.
*/
public static final String EXTRA_ERROR = "error";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate the registration id when the registration succeeds.
*/
public static final String EXTRA_REGISTRATION_ID = "registration_id";
/**
* Type of message present in the
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* intent.
* This extra is only set for special messages sent from GCM, not for
* messages originated from the application.
*/
public static final String EXTRA_SPECIAL_MESSAGE = "message_type";
/**
* Special message indicating the server deleted the pending messages.
*/
public static final String VALUE_DELETED_MESSAGES = "deleted_messages";
/**
* Number of messages deleted by the server because the device was idle.
* Present only on messages of special type
* {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES}
*/
public static final String EXTRA_TOTAL_DELETED = "total_deleted";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* to indicate which sender (Google API project id) sent the message.
*/
public static final String EXTRA_FROM = "from";
/**
* Permission necessary to receive GCM intents.
*/
public static final String PERMISSION_GCM_INTENTS =
"com.google.android.c2dm.permission.SEND";
/**
* @see GCMBroadcastReceiver
*/
public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME =
".GCMIntentService";
/**
* The device can't read the response, or there was a 500/503 from the
* server that can be retried later. The application should use exponential
* back off and retry.
*/
public static final String ERROR_SERVICE_NOT_AVAILABLE =
"SERVICE_NOT_AVAILABLE";
/**
* There is no Google account on the phone. The application should ask the
* user to open the account manager and add a Google account.
*/
public static final String ERROR_ACCOUNT_MISSING =
"ACCOUNT_MISSING";
/**
* Bad password. The application should ask the user to enter his/her
* password, and let user retry manually later. Fix on the device side.
*/
public static final String ERROR_AUTHENTICATION_FAILED =
"AUTHENTICATION_FAILED";
/**
* The request sent by the phone does not contain the expected parameters.
* This phone doesn't currently support GCM.
*/
public static final String ERROR_INVALID_PARAMETERS =
"INVALID_PARAMETERS";
/**
* The sender account is not recognized. Fix on the device side.
*/
public static final String ERROR_INVALID_SENDER =
"INVALID_SENDER";
/**
* Incorrect phone registration with Google. This phone doesn't currently
* support GCM.
*/
public static final String ERROR_PHONE_REGISTRATION_ERROR =
"PHONE_REGISTRATION_ERROR";
private GCMConstants() {
throw new UnsupportedOperationException();
}
}
| zyf404283839-gcm-demo-client | gcm-client-deprecated/src/com/google/android/gcm/GCMConstants.java | Java | asf20 | 6,105 |
/*
* 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.gcm;
import android.util.Log;
/**
* Custom logger.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
class GCMLogger {
private final String mTag;
// can't use class name on TAG since size is limited to 23 chars
private final String mLogPrefix;
GCMLogger(String tag, String logPrefix) {
mTag = tag;
mLogPrefix = logPrefix;
}
/**
* Logs a message on logcat.
*
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
protected void log(int priority, String template, Object... args) {
if (Log.isLoggable(mTag, priority)) {
String message = String.format(template, args);
Log.println(priority, mTag, mLogPrefix + message);
}
}
}
| zyf404283839-gcm-demo-client | gcm-client-deprecated/src/com/google/android/gcm/GCMLogger.java | Java | asf20 | 1,530 |
/*
* 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.gcm;
import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE;
import static com.google.android.gcm.GCMConstants.EXTRA_ERROR;
import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID;
import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE;
import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED;
import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK;
import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Skeleton for application-specific {@link IntentService}s responsible for
* handling communication from Google Cloud Messaging service.
* <p>
* The abstract methods in this class are called from its worker thread, and
* hence should run in a limited amount of time. If they execute long
* operations, they should spawn new threads, otherwise the worker thread will
* be blocked.
* <p>
* Subclasses must provide a public no-arg constructor.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public abstract class GCMBaseIntentService extends IntentService {
/**
* Old TAG used for logging. Marked as deprecated since it should have
* been private at first place.
*/
@Deprecated
public static final String TAG = "GCMBaseIntentService";
private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService",
"[" + getClass().getName() + "]: ");
// wakelock
private static final String WAKELOCK_KEY = "GCM_LIB";
private static PowerManager.WakeLock sWakeLock;
// Java lock used to synchronize access to sWakelock
private static final Object LOCK = GCMBaseIntentService.class;
private final String[] mSenderIds;
// instance counter
private static int sCounter = 0;
private static final Random sRandom = new Random();
private static final int MAX_BACKOFF_MS =
(int) TimeUnit.SECONDS.toMillis(3600); // 1 hour
/**
* Constructor that does not set a sender id, useful when the sender id
* is context-specific.
* <p>
* When using this constructor, the subclass <strong>must</strong>
* override {@link #getSenderIds(Context)}, otherwise methods such as
* {@link #onHandleIntent(Intent)} will throw an
* {@link IllegalStateException} on runtime.
*/
protected GCMBaseIntentService() {
this(getName("DynamicSenderIds"), null);
}
/**
* Constructor used when the sender id(s) is fixed.
*/
protected GCMBaseIntentService(String... senderIds) {
this(getName(senderIds), senderIds);
}
private GCMBaseIntentService(String name, String[] senderIds) {
super(name); // name is used as base name for threads, etc.
mSenderIds = senderIds;
mLogger.log(Log.VERBOSE, "Intent service name: %s", name);
}
private static String getName(String senderId) {
String name = "GCMIntentService-" + senderId + "-" + (++sCounter);
return name;
}
private static String getName(String[] senderIds) {
String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds);
return getName(flatSenderIds);
}
/**
* Gets the sender ids.
*
* <p>By default, it returns the sender ids passed in the constructor, but
* it could be overridden to provide a dynamic sender id.
*
* @throws IllegalStateException if sender id was not set on constructor.
*/
protected String[] getSenderIds(Context context) {
if (mSenderIds == null) {
throw new IllegalStateException("sender id not set on constructor");
}
return mSenderIds;
}
/**
* Called when a cloud message has been received.
*
* @param context application's context.
* @param intent intent containing the message payload as extras.
*/
protected abstract void onMessage(Context context, Intent intent);
/**
* Called when the GCM server tells pending messages have been deleted
* because the device was idle.
*
* @param context application's context.
* @param total total number of collapsed messages
*/
protected void onDeletedMessages(Context context, int total) {
}
/**
* Called on a registration error that could be retried.
*
* <p>By default, it does nothing and returns {@literal true}, but could be
* overridden to change that behavior and/or display the error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*
* @return if {@literal true}, failed operation will be retried (using
* exponential backoff).
*/
protected boolean onRecoverableError(Context context, String errorId) {
return true;
}
/**
* Called on registration or unregistration error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*/
protected abstract void onError(Context context, String errorId);
/**
* Called after a device has been registered.
*
* @param context application's context.
* @param registrationId the registration id returned by the GCM service.
*/
protected abstract void onRegistered(Context context,
String registrationId);
/**
* Called after a device has been unregistered.
*
* @param registrationId the registration id that was previously registered.
* @param context application's context.
*/
protected abstract void onUnregistered(Context context,
String registrationId);
@Override
public final void onHandleIntent(Intent intent) {
try {
Context context = getApplicationContext();
String action = intent.getAction();
if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) {
GCMRegistrar.setRetryBroadcastReceiver(context);
handleRegistration(context, intent);
} else if (action.equals(INTENT_FROM_GCM_MESSAGE)) {
// checks for special messages
String messageType =
intent.getStringExtra(EXTRA_SPECIAL_MESSAGE);
if (messageType != null) {
if (messageType.equals(VALUE_DELETED_MESSAGES)) {
String sTotal =
intent.getStringExtra(EXTRA_TOTAL_DELETED);
if (sTotal != null) {
try {
int total = Integer.parseInt(sTotal);
mLogger.log(Log.VERBOSE,
"Received notification for %d deleted"
+ "messages", total);
onDeletedMessages(context, total);
} catch (NumberFormatException e) {
mLogger.log(Log.ERROR, "GCM returned invalid "
+ "number of deleted messages (%d)",
sTotal);
}
}
} else {
// application is not using the latest GCM library
mLogger.log(Log.ERROR,
"Received unknown special message: %s",
messageType);
}
} else {
onMessage(context, intent);
}
} else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) {
String packageOnIntent = intent.getPackage();
if (packageOnIntent == null || !packageOnIntent.equals(
getApplicationContext().getPackageName())) {
mLogger.log(Log.ERROR,
"Ignoring retry intent from another package (%s)",
packageOnIntent);
return;
}
// retry last call
if (GCMRegistrar.isRegistered(context)) {
GCMRegistrar.internalUnregister(context);
} else {
String[] senderIds = getSenderIds(context);
GCMRegistrar.internalRegister(context, senderIds);
}
}
} finally {
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If onMessage() needs to spawn a thread or do something else,
// it should use its own lock.
synchronized (LOCK) {
// sanity check for null as this is a public method
if (sWakeLock != null) {
sWakeLock.release();
} else {
// should never happen during normal workflow
mLogger.log(Log.ERROR, "Wakelock reference is null");
}
}
}
}
/**
* Called from the broadcast receiver.
* <p>
* Will process the received intent, call handleMessage(), registered(),
* etc. in background threads, with a wake lock, while keeping the service
* alive.
*/
static void runIntentInService(Context context, Intent intent,
String className) {
synchronized (LOCK) {
if (sWakeLock == null) {
// This is called from BroadcastReceiver, there is no init.
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WAKELOCK_KEY);
}
}
sWakeLock.acquire();
intent.setClassName(context, className);
context.startService(intent);
}
private void handleRegistration(final Context context, Intent intent) {
GCMRegistrar.cancelAppPendingIntent();
String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
String error = intent.getStringExtra(EXTRA_ERROR);
String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, "
+ "error = %s, unregistered = %s",
registrationId, error, unregistered);
// registration succeeded
if (registrationId != null) {
GCMRegistrar.resetBackoff(context);
GCMRegistrar.setRegistrationId(context, registrationId);
onRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null) {
// Remember we are unregistered
GCMRegistrar.resetBackoff(context);
String oldRegistrationId =
GCMRegistrar.clearRegistrationId(context);
onUnregistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
// Registration failed
if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
boolean retry = onRecoverableError(context, error);
if (retry) {
int backoffTimeMs = GCMRegistrar.getBackoff(context);
int nextAttempt = backoffTimeMs / 2 +
sRandom.nextInt(backoffTimeMs);
mLogger.log(Log.DEBUG,
"Scheduling registration retry, backoff = %d (%d)",
nextAttempt, backoffTimeMs);
Intent retryIntent =
new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
retryIntent.setPackage(context.getPackageName());
PendingIntent retryPendingIntent = PendingIntent
.getBroadcast(context, 0, retryIntent, 0);
AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + nextAttempt,
retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MAX_BACKOFF_MS) {
GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
}
} else {
mLogger.log(Log.VERBOSE, "Not retrying failed operation");
}
} else {
// Unrecoverable error, notify app
onError(context, error);
}
}
}
| zyf404283839-gcm-demo-client | gcm-client-deprecated/src/com/google/android/gcm/GCMBaseIntentService.java | Java | asf20 | 14,032 |
/*
* 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.gcm;
import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* {@link BroadcastReceiver} that receives GCM messages and delivers them to
* an application-specific {@link GCMBaseIntentService} subclass.
* <p>
* By default, the {@link GCMBaseIntentService} class belongs to the application
* main package and is named
* {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class,
* the {@link #getGCMIntentServiceClassName(Context)} must be overridden.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static boolean mReceiverSet = false;
private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver",
"[" + getClass().getName() + "]: ");
@Override
public final void onReceive(Context context, Intent intent) {
mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction());
// do a one-time check if app is using a custom GCMBroadcastReceiver
if (!mReceiverSet) {
mReceiverSet = true;
GCMRegistrar.setRetryReceiverClassName(context,
getClass().getName());
}
String className = getGCMIntentServiceClassName(context);
mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className);
// Delegates to the application-specific intent service.
GCMBaseIntentService.runIntentInService(context, intent, className);
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
/**
* Gets the class name of the intent service that will handle GCM messages.
*/
protected String getGCMIntentServiceClassName(Context context) {
return getDefaultIntentServiceClassName(context);
}
/**
* Gets the default class name of the intent service that will handle GCM
* messages.
*/
static final String getDefaultIntentServiceClassName(Context context) {
String className = context.getPackageName() +
DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
}
| zyf404283839-gcm-demo-client | gcm-client-deprecated/src/com/google/android/gcm/GCMBroadcastReceiver.java | Java | asf20 | 3,012 |
/*
* 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.gcm;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities for device registration.
* <p>
* <strong>Note:</strong> this class uses a private {@link SharedPreferences}
* object to keep track of the registration token.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMRegistrar {
/**
* Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)}
* flag until it is considered expired.
*/
// NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8
public static final long DEFAULT_ON_SERVER_LIFESPAN_MS =
1000 * 3600 * 24 * 7;
private static final String TAG = "GCMRegistrar";
private static final String BACKOFF_MS = "backoff_ms";
private static final String GSF_PACKAGE = "com.google.android.gsf";
private static final String PREFERENCES = "com.google.android.gcm";
private static final int DEFAULT_BACKOFF_MS = 3000;
private static final String PROPERTY_REG_ID = "regId";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String PROPERTY_ON_SERVER = "onServer";
private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
"onServerExpirationTime";
private static final String PROPERTY_ON_SERVER_LIFESPAN =
"onServerLifeSpan";
/**
* {@link GCMBroadcastReceiver} instance used to handle the retry intent.
*
* <p>
* This instance cannot be the same as the one defined in the manifest
* because it needs a different permission.
*/
// guarded by GCMRegistrar.class
private static GCMBroadcastReceiver sRetryReceiver;
// guarded by GCMRegistrar.class
private static Context sRetryReceiverContext;
// guarded by GCMRegistrar.class
private static String sRetryReceiverClassName;
// guarded by GCMRegistrar.class
private static PendingIntent sAppPendingIntent;
/**
* Checks if the device has the proper dependencies installed.
* <p>
* This method should be called when the application starts to verify that
* the device supports GCM.
*
* @param context application context.
* @throws UnsupportedOperationException if the device does not support GCM.
*/
public static void checkDevice(Context context) {
int version = Build.VERSION.SDK_INT;
if (version < 8) {
throw new UnsupportedOperationException("Device must be at least " +
"API Level 8 (instead of " + version + ")");
}
PackageManager packageManager = context.getPackageManager();
try {
packageManager.getPackageInfo(GSF_PACKAGE, 0);
} catch (NameNotFoundException e) {
throw new UnsupportedOperationException(
"Device does not have package " + GSF_PACKAGE);
}
}
/**
* Checks that the application manifest is properly configured.
* <p>
* A proper configuration means:
* <ol>
* <li>It creates a custom permission called
* {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
* <li>It defines at least one {@link BroadcastReceiver} with category
* {@code PACKAGE_NAME}.
* <li>The {@link BroadcastReceiver}(s) uses the
* {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS}
* permission.
* <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents
* ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* and
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
* </ol>
* ...where {@code PACKAGE_NAME} is the application package.
* <p>
* This method should be used during development time to verify that the
* manifest is properly set up, but it doesn't need to be called once the
* application is deployed to the users' devices.
*
* @param context application context.
* @throws IllegalStateException if any of the conditions above is not met.
*/
public static void checkManifest(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
String permissionName = packageName + ".permission.C2D_MESSAGE";
// check permission
try {
packageManager.getPermissionInfo(permissionName,
PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Application does not define permission " + permissionName);
}
// check receivers
PackageInfo receiversInfo;
try {
receiversInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Could not get receivers for package " + packageName);
}
ActivityInfo[] receivers = receiversInfo.receivers;
if (receivers == null || receivers.length == 0) {
throw new IllegalStateException("No receiver for package " +
packageName);
}
log(context, Log.VERBOSE, "number of receivers for %s: %d",
packageName, receivers.length);
Set<String> allowedReceivers = new HashSet<String>();
for (ActivityInfo receiver : receivers) {
if (GCMConstants.PERMISSION_GCM_INTENTS.equals(
receiver.permission)) {
allowedReceivers.add(receiver.name);
}
}
if (allowedReceivers.isEmpty()) {
throw new IllegalStateException("No receiver allowed to receive " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void checkReceiver(Context context,
Set<String> allowedReceivers, String action) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
Intent intent = new Intent(action);
intent.setPackage(packageName);
List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent,
PackageManager.GET_INTENT_FILTERS);
if (receivers.isEmpty()) {
throw new IllegalStateException("No receivers for action " +
action);
}
log(context, Log.VERBOSE, "Found %d receivers for action %s",
receivers.size(), action);
// make sure receivers match
for (ResolveInfo receiver : receivers) {
String name = receiver.activityInfo.name;
if (!allowedReceivers.contains(name)) {
throw new IllegalStateException("Receiver " + name +
" is not set with permission " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
}
}
/**
* Initiate messaging registration for the current application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with
* either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or
* {@link GCMConstants#EXTRA_ERROR}.
*
* @param context application context.
* @param senderIds Google Project ID of the accounts authorized to send
* messages to this application.
* @throws IllegalStateException if device does not have all GCM
* dependencies installed.
*/
public static void register(Context context, String... senderIds) {
GCMRegistrar.resetBackoff(context);
internalRegister(context, senderIds);
}
static void internalRegister(Context context, String... senderIds) {
String flatSenderIds = getFlatSenderIds(senderIds);
log(context, Log.VERBOSE, "Registering app for senders %s",
flatSenderIds);
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
context.startService(intent);
}
/**
* Unregister the application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an
* {@link GCMConstants#EXTRA_UNREGISTERED} extra.
*/
public static void unregister(Context context) {
GCMRegistrar.resetBackoff(context);
internalUnregister(context);
}
static void internalUnregister(Context context) {
log(context, Log.VERBOSE, "Unregistering app");
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
context.startService(intent);
}
static String getFlatSenderIds(String... senderIds) {
if (senderIds == null || senderIds.length == 0) {
throw new IllegalArgumentException("No senderIds");
}
StringBuilder builder = new StringBuilder(senderIds[0]);
for (int i = 1; i < senderIds.length; i++) {
builder.append(',').append(senderIds[i]);
}
return builder.toString();
}
/**
* Clear internal resources.
*
* <p>
* This method should be called by the main activity's {@code onDestroy()}
* method.
*/
public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
log(context, Log.VERBOSE, "Unregistering retry receiver");
sRetryReceiverContext.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
sRetryReceiverContext = null;
}
}
static synchronized void cancelAppPendingIntent() {
if (sAppPendingIntent != null) {
sAppPendingIntent.cancel();
sAppPendingIntent = null;
}
}
private synchronized static void setPackageNameExtra(Context context,
Intent intent) {
if (sAppPendingIntent == null) {
log(context, Log.VERBOSE,
"Creating pending intent to get package name");
sAppPendingIntent = PendingIntent.getBroadcast(context, 0,
new Intent(), 0);
}
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
sAppPendingIntent);
}
/**
* Lazy initializes the {@link GCMBroadcastReceiver} instance.
*/
static synchronized void setRetryBroadcastReceiver(Context context) {
if (sRetryReceiver == null) {
if (sRetryReceiverClassName == null) {
// should never happen
log(context, Log.ERROR,
"internal error: retry receiver class not set yet");
sRetryReceiver = new GCMBroadcastReceiver();
} else {
Class<?> clazz;
try {
clazz = Class.forName(sRetryReceiverClassName);
sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
} catch (Exception e) {
log(context, Log.ERROR, "Could not create instance of %s. "
+ "Using %s directly.", sRetryReceiverClassName,
GCMBroadcastReceiver.class.getName());
sRetryReceiver = new GCMBroadcastReceiver();
}
}
String category = context.getPackageName();
IntentFilter filter = new IntentFilter(
GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.addCategory(category);
log(context, Log.VERBOSE, "Registering retry receiver");
sRetryReceiverContext = context;
sRetryReceiverContext.registerReceiver(sRetryReceiver, filter);
}
}
/**
* Sets the name of the retry receiver class.
*/
static synchronized void setRetryReceiverClassName(Context context,
String className) {
log(context, Log.VERBOSE,
"Setting the name of retry receiver class to %s", className);
sRetryReceiverClassName = className;
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
log(context, Log.VERBOSE, "App version changed from %d to %d;"
+ "resetting registration id", oldVersion, newVersion);
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
/**
* Checks whether the application was successfully registered on GCM
* service.
*/
public static boolean isRegistered(Context context) {
return getRegistrationId(context).length() > 0;
}
/**
* Clears the registration id in the persistence store.
*
* <p>As a side-effect, it also expires the registeredOnServer property.
*
* @param context application's context.
* @return old registration id.
*/
static String clearRegistrationId(Context context) {
setRegisteredOnServer(context, null, 0);
return setRegistrationId(context, "");
}
/**
* Sets the registration id in the persistence store.
*
* @param context application's context.
* @param regId registration id
*/
static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
}
/**
* Sets whether the device was successfully registered in the server side.
*/
public static void setRegisteredOnServer(Context context, boolean flag) {
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
setRegisteredOnServer(context, flag, expirationTime);
}
private static void setRegisteredOnServer(Context context, Boolean flag,
long expirationTime) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
if (flag != null) {
editor.putBoolean(PROPERTY_ON_SERVER, flag);
log(context, Log.VERBOSE,
"Setting registeredOnServer flag as %b until %s",
flag, new Timestamp(expirationTime));
} else {
log(context, Log.VERBOSE,
"Setting registeredOnServer expiration to %s",
new Timestamp(expirationTime));
}
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side,
* as set by {@link #setRegisteredOnServer(Context, boolean)}.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, this flag has an expiration date, which
* is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed
* by {@link #setRegisterOnServerLifespan(Context, long)}).
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false);
log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered);
if (isRegistered) {
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
if (System.currentTimeMillis() > expirationTime) {
log(context, Log.VERBOSE, "flag expired on: %s",
new Timestamp(expirationTime));
return false;
}
}
return isRegistered;
}
/**
* Gets how long (in milliseconds) the {@link #isRegistered(Context)}
* property is valid.
*
* @return value set by {@link #setRegisteredOnServer(Context, boolean)} or
* {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set.
*/
public static long getRegisterOnServerLifespan(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN,
DEFAULT_ON_SERVER_LIFESPAN_MS);
return lifespan;
}
/**
* Sets how long (in milliseconds) the {@link #isRegistered(Context)}
* flag is valid.
*/
public static void setRegisterOnServerLifespan(Context context,
long lifespan) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan);
editor.commit();
}
/**
* Gets the application version.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
}
/**
* Resets the backoff counter.
* <p>
* This method should be called after a GCM call succeeds.
*
* @param context application's context.
*/
static void resetBackoff(Context context) {
log(context, Log.VERBOSE, "Resetting backoff");
setBackoff(context, DEFAULT_BACKOFF_MS);
}
/**
* Gets the current backoff counter.
*
* @param context application's context.
* @return current backoff counter, in milliseconds.
*/
static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
/**
* Sets the backoff counter.
* <p>
* This method should be called after a GCM call fails, passing an
* exponential value.
*
* @param context application's context.
* @param backoff new backoff counter, in milliseconds.
*/
static void setBackoff(Context context, int backoff) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putInt(BACKOFF_MS, backoff);
editor.commit();
}
private static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
/**
* Logs a message on logcat.
*
* @param context application's context.
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
private static void log(Context context, int priority, String template,
Object... args) {
if (Log.isLoggable(TAG, priority)) {
String message = String.format(template, args);
Log.println(priority, TAG, "[" + context.getPackageName() + "]: "
+ message);
}
}
private GCMRegistrar() {
throw new UnsupportedOperationException();
}
}
| zyf404283839-gcm-demo-client | gcm-client-deprecated/src/com/google/android/gcm/GCMRegistrar.java | Java | asf20 | 22,174 |
/*
* 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.gcm.server;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* GCM message.
*
* <p>
* Instances of this class are immutable and should be created using a
* {@link Builder}. Examples:
*
* <strong>Simplest message:</strong>
* <pre><code>
* Message message = new Message.Builder().build();
* </pre></code>
*
* <strong>Message with optional attributes:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .build();
* </pre></code>
*
* <strong>Message with optional attributes and payload data:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .addData("key1", "value1")
* .addData("key2", "value2")
* .build();
* </pre></code>
*/
public final class Message implements Serializable {
private final String collapseKey;
private final Boolean delayWhileIdle;
private final Integer timeToLive;
private final Map<String, String> data;
private final Boolean dryRun;
private final String restrictedPackageName;
public static final class Builder {
private final Map<String, String> data;
// optional parameters
private String collapseKey;
private Boolean delayWhileIdle;
private Integer timeToLive;
private Boolean dryRun;
private String restrictedPackageName;
public Builder() {
this.data = new LinkedHashMap<String, String>();
}
/**
* Sets the collapseKey property.
*/
public Builder collapseKey(String value) {
collapseKey = value;
return this;
}
/**
* Sets the delayWhileIdle property (default value is {@literal false}).
*/
public Builder delayWhileIdle(boolean value) {
delayWhileIdle = value;
return this;
}
/**
* Sets the time to live, in seconds.
*/
public Builder timeToLive(int value) {
timeToLive = value;
return this;
}
/**
* Adds a key/value pair to the payload data.
*/
public Builder addData(String key, String value) {
data.put(key, value);
return this;
}
/**
* Sets the dryRun property (default value is {@literal false}).
*/
public Builder dryRun(boolean value) {
dryRun = value;
return this;
}
/**
* Sets the restrictedPackageName property.
*/
public Builder restrictedPackageName(String value) {
restrictedPackageName = value;
return this;
}
public Message build() {
return new Message(this);
}
}
private Message(Builder builder) {
collapseKey = builder.collapseKey;
delayWhileIdle = builder.delayWhileIdle;
data = Collections.unmodifiableMap(builder.data);
timeToLive = builder.timeToLive;
dryRun = builder.dryRun;
restrictedPackageName = builder.restrictedPackageName;
}
/**
* Gets the collapse key.
*/
public String getCollapseKey() {
return collapseKey;
}
/**
* Gets the delayWhileIdle flag.
*/
public Boolean isDelayWhileIdle() {
return delayWhileIdle;
}
/**
* Gets the time to live (in seconds).
*/
public Integer getTimeToLive() {
return timeToLive;
}
/**
* Gets the dryRun flag.
*/
public Boolean isDryRun() {
return dryRun;
}
/**
* Gets the restricted package name.
*/
public String getRestrictedPackageName() {
return restrictedPackageName;
}
/**
* Gets the payload data, which is immutable.
*/
public Map<String, String> getData() {
return data;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Message(");
if (collapseKey != null) {
builder.append("collapseKey=").append(collapseKey).append(", ");
}
if (timeToLive != null) {
builder.append("timeToLive=").append(timeToLive).append(", ");
}
if (delayWhileIdle != null) {
builder.append("delayWhileIdle=").append(delayWhileIdle).append(", ");
}
if (dryRun != null) {
builder.append("dryRun=").append(dryRun).append(", ");
}
if (restrictedPackageName != null) {
builder.append("restrictedPackageName=").append(restrictedPackageName).append(", ");
}
if (!data.isEmpty()) {
builder.append("data: {");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(",");
}
builder.delete(builder.length() - 1, builder.length());
builder.append("}");
}
if (builder.charAt(builder.length() - 1) == ' ') {
builder.delete(builder.length() - 2, builder.length());
}
builder.append(")");
return builder.toString();
}
}
| zyf404283839-gcm-demo-client | gcm-server/src/com/google/android/gcm/server/Message.java | Java | asf20 | 5,628 |
/*
* 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.gcm.server;
import java.io.IOException;
/**
* Exception thrown when GCM returned an error due to an invalid request.
* <p>
* This is equivalent to GCM posts that return an HTTP error different of 200.
*/
public final class InvalidRequestException extends IOException {
private final int status;
private final String description;
public InvalidRequestException(int status) {
this(status, null);
}
public InvalidRequestException(int status, String description) {
super(getMessage(status, description));
this.status = status;
this.description = description;
}
private static String getMessage(int status, String description) {
StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status);
if (description != null) {
base.append("(").append(description).append(")");
}
return base.toString();
}
/**
* Gets the HTTP Status Code.
*/
public int getHttpStatusCode() {
return status;
}
/**
* Gets the error description.
*/
public String getDescription() {
return description;
}
}
| zyf404283839-gcm-demo-client | gcm-server/src/com/google/android/gcm/server/InvalidRequestException.java | Java | asf20 | 1,700 |
/*
* 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.gcm.server;
import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS;
import static com.google.android.gcm.server.Constants.JSON_ERROR;
import static com.google.android.gcm.server.Constants.JSON_FAILURE;
import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID;
import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID;
import static com.google.android.gcm.server.Constants.JSON_PAYLOAD;
import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS;
import static com.google.android.gcm.server.Constants.JSON_RESULTS;
import static com.google.android.gcm.server.Constants.JSON_SUCCESS;
import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY;
import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE;
import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN;
import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX;
import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID;
import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME;
import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE;
import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID;
import static com.google.android.gcm.server.Constants.TOKEN_ERROR;
import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID;
import com.google.android.gcm.server.Result.Builder;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper class to send messages to the GCM service using an API Key.
*/
public class Sender {
protected static final String UTF8 = "UTF-8";
/**
* Initial delay before first retry, without jitter.
*/
protected static final int BACKOFF_INITIAL_DELAY = 1000;
/**
* Maximum delay before a retry.
*/
protected static final int MAX_BACKOFF_DELAY = 1024000;
protected final Random random = new Random();
protected static final Logger logger =
Logger.getLogger(Sender.class.getName());
private final String key;
/**
* Default constructor.
*
* @param key API key obtained through the Google API Console.
*/
public Sender(String key) {
this.key = nonNull(key);
}
/**
* Sends a message to one device, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent, including the device's registration id.
* @param registrationId device where the message will be sent.
* @param retries number of retries in case of service unavailability errors.
*
* @return result of the request (see its javadoc for more details).
*
* @throws IllegalArgumentException if registrationId is {@literal null}.
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IOException if message could not be sent.
*/
public Result send(Message message, String registrationId, int retries)
throws IOException {
int attempt = 0;
Result result = null;
int backoff = BACKOFF_INITIAL_DELAY;
boolean tryAgain;
do {
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + registrationId);
}
result = sendNoRetry(message, registrationId);
tryAgain = result == null && attempt <= retries;
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (result == null) {
throw new IOException("Could not send message after " + attempt +
" attempts");
}
return result;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, String, int)} for more info.
*
* @return result of the post, or {@literal null} if the GCM service was
* unavailable or any network exception caused the request to fail.
*
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IllegalArgumentException if registrationId is {@literal null}.
*/
public Result sendNoRetry(Message message, String registrationId)
throws IOException {
StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
Boolean delayWhileIdle = message.isDelayWhileIdle();
if (delayWhileIdle != null) {
addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
}
Boolean dryRun = message.isDryRun();
if (dryRun != null) {
addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
}
String collapseKey = message.getCollapseKey();
if (collapseKey != null) {
addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
}
String restrictedPackageName = message.getRestrictedPackageName();
if (restrictedPackageName != null) {
addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
}
Integer timeToLive = message.getTimeToLive();
if (timeToLive != null) {
addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
}
for (Entry<String, String> entry : message.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
logger.warning("Ignoring payload entry thas has null: " + entry);
} else {
key = PARAM_PAYLOAD_PREFIX + key;
addParameter(body, key, URLEncoder.encode(value, UTF8));
}
}
String requestBody = body.toString();
logger.finest("Request body: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
if (status / 100 == 5) {
logger.fine("GCM service is unavailable (status " + status + ")");
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("Plain post error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
} else {
try {
responseBody = getAndClose(conn.getInputStream());
} catch (IOException e) {
logger.log(Level.WARNING, "Exception reading response: ", e);
// return null so it can retry
return null;
}
}
String[] lines = responseBody.split("\n");
if (lines.length == 0 || lines[0].equals("")) {
throw new IOException("Received empty response from GCM service.");
}
String firstLine = lines[0];
String[] responseParts = split(firstLine);
String token = responseParts[0];
String value = responseParts[1];
if (token.equals(TOKEN_MESSAGE_ID)) {
Builder builder = new Result.Builder().messageId(value);
// check for canonical registration id
if (lines.length > 1) {
String secondLine = lines[1];
responseParts = split(secondLine);
token = responseParts[0];
value = responseParts[1];
if (token.equals(TOKEN_CANONICAL_REG_ID)) {
builder.canonicalRegistrationId(value);
} else {
logger.warning("Invalid response from GCM: " + responseBody);
}
}
Result result = builder.build();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Message created succesfully (" + result + ")");
}
return result;
} else if (token.equals(TOKEN_ERROR)) {
return new Result.Builder().errorCode(value).build();
} else {
throw new IOException("Invalid response from GCM: " + responseBody);
}
}
/**
* Sends a message to many devices, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent.
* @param regIds registration id of the devices that will receive
* the message.
* @param retries number of retries in case of service unavailability errors.
*
* @return combined result of all requests made.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
* @throws IOException if message could not be sent.
*/
public MulticastResult send(Message message, List<String> regIds, int retries)
throws IOException {
int attempt = 0;
MulticastResult multicastResult;
int backoff = BACKOFF_INITIAL_DELAY;
// Map of results by registration id, it will be updated after each attempt
// to send the messages
Map<String, Result> results = new HashMap<String, Result>();
List<String> unsentRegIds = new ArrayList<String>(regIds);
boolean tryAgain;
List<Long> multicastIds = new ArrayList<Long>();
do {
multicastResult = null;
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + unsentRegIds);
}
try {
multicastResult = sendNoRetry(message, unsentRegIds);
} catch(IOException e) {
// no need for WARNING since exception might be already logged
logger.log(Level.FINEST, "IOException on attempt " + attempt, e);
}
if (multicastResult != null) {
long multicastId = multicastResult.getMulticastId();
logger.fine("multicast_id on attempt # " + attempt + ": " +
multicastId);
multicastIds.add(multicastId);
unsentRegIds = updateStatus(unsentRegIds, results, multicastResult);
tryAgain = !unsentRegIds.isEmpty() && attempt <= retries;
} else {
tryAgain = attempt <= retries;
}
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (multicastIds.isEmpty()) {
// all JSON posts failed due to GCM unavailability
throw new IOException("Could not post JSON requests to GCM after "
+ attempt + " attempts");
}
// calculate summary
int success = 0, failure = 0 , canonicalIds = 0;
for (Result result : results.values()) {
if (result.getMessageId() != null) {
success++;
if (result.getCanonicalRegistrationId() != null) {
canonicalIds++;
}
} else {
failure++;
}
}
// build a new object with the overall result
long multicastId = multicastIds.remove(0);
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId).retryMulticastIds(multicastIds);
// add results, in the same order as the input
for (String regId : regIds) {
Result result = results.get(regId);
builder.addResult(result);
}
return builder.build();
}
/**
* Updates the status of the messages sent to devices and the list of devices
* that should be retried.
*
* @param unsentRegIds list of devices that are still pending an update.
* @param allResults map of status that will be updated.
* @param multicastResult result of the last multicast sent.
*
* @return updated version of devices that should be retried.
*/
private List<String> updateStatus(List<String> unsentRegIds,
Map<String, Result> allResults, MulticastResult multicastResult) {
List<Result> results = multicastResult.getResults();
if (results.size() != unsentRegIds.size()) {
// should never happen, unless there is a flaw in the algorithm
throw new RuntimeException("Internal error: sizes do not match. " +
"currentResults: " + results + "; unsentRegIds: " + unsentRegIds);
}
List<String> newUnsentRegIds = new ArrayList<String>();
for (int i = 0; i < unsentRegIds.size(); i++) {
String regId = unsentRegIds.get(i);
Result result = results.get(i);
allResults.put(regId, result);
String error = result.getErrorCodeName();
if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE)
|| error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) {
newUnsentRegIds.add(regId);
}
}
return newUnsentRegIds;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, List, int)} for more info.
*
* @return multicast results if the message was sent successfully,
* {@literal null} if it failed but could be retried.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 status.
* @throws IOException if there was a JSON parsing error
*/
public MulticastResult sendNoRetry(Message message,
List<String> registrationIds) throws IOException {
if (nonNull(registrationIds).isEmpty()) {
throw new IllegalArgumentException("registrationIds cannot be empty");
}
Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE,
message.isDelayWhileIdle());
setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
Map<String, String> payload = message.getData();
if (!payload.isEmpty()) {
jsonRequest.put(JSON_PAYLOAD, payload);
}
String requestBody = JSONValue.toJSONString(jsonRequest);
logger.finest("JSON request: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("JSON error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
}
try {
responseBody = getAndClose(conn.getInputStream());
} catch(IOException e) {
logger.log(Level.WARNING, "IOException reading response", e);
return null;
}
logger.finest("JSON response: " + responseBody);
JSONParser parser = new JSONParser();
JSONObject jsonResponse;
try {
jsonResponse = (JSONObject) parser.parse(responseBody);
int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId);
@SuppressWarnings("unchecked")
List<Map<String, Object>> results =
(List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
if (results != null) {
for (Map<String, Object> jsonResult : results) {
String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
String canonicalRegId =
(String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
String error = (String) jsonResult.get(JSON_ERROR);
Result result = new Result.Builder()
.messageId(messageId)
.canonicalRegistrationId(canonicalRegId)
.errorCode(error)
.build();
builder.addResult(result);
}
}
MulticastResult multicastResult = builder.build();
return multicastResult;
} catch (ParseException e) {
throw newIoException(responseBody, e);
} catch (CustomParserException e) {
throw newIoException(responseBody, e);
}
}
private IOException newIoException(String responseBody, Exception e) {
// log exception, as IOException constructor that takes a message and cause
// is only available on Java 6
String msg = "Error parsing JSON response (" + responseBody + ")";
logger.log(Level.WARNING, msg, e);
return new IOException(msg + ":" + e);
}
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore error
logger.log(Level.FINEST, "IOException closing stream", e);
}
}
}
/**
* Sets a JSON field, but only if the value is not {@literal null}.
*/
private void setJsonField(Map<Object, Object> json, String field,
Object value) {
if (value != null) {
json.put(field, value);
}
}
private Number getNumber(Map<?, ?> json, String field) {
Object value = json.get(field);
if (value == null) {
throw new CustomParserException("Missing field: " + field);
}
if (!(value instanceof Number)) {
throw new CustomParserException("Field " + field +
" does not contain a number: " + value);
}
return (Number) value;
}
class CustomParserException extends RuntimeException {
CustomParserException(String message) {
super(message);
}
}
private String[] split(String line) throws IOException {
String[] split = line.split("=", 2);
if (split.length != 2) {
throw new IOException("Received invalid response line from GCM: " + line);
}
return split;
}
/**
* Make an HTTP post to a given URL.
*
* @return HTTP response.
*/
protected HttpURLConnection post(String url, String body)
throws IOException {
return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body);
}
/**
* Makes an HTTP POST request to a given endpoint.
*
* <p>
* <strong>Note: </strong> the returned connected should not be disconnected,
* otherwise it would kill persistent connections made using Keep-Alive.
*
* @param url endpoint to post the request.
* @param contentType type of request.
* @param body body of the request.
*
* @return the underlying connection.
*
* @throws IOException propagated from underlying methods.
*/
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
if (url == null || body == null) {
throw new IllegalArgumentException("arguments cannot be null");
}
if (!url.startsWith("https://")) {
logger.warning("URL does not use https: " + url);
}
logger.fine("Sending POST to " + url);
logger.finest("POST body: " + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
try {
out.write(bytes);
} finally {
close(out);
}
return conn;
}
/**
* Creates a map with just one key-value pair.
*/
protected static final Map<String, String> newKeyValues(String key,
String value) {
Map<String, String> keyValues = new HashMap<String, String>(1);
keyValues.put(nonNull(key), nonNull(value));
return keyValues;
}
/**
* Creates a {@link StringBuilder} to be used as the body of an HTTP POST.
*
* @param name initial parameter for the POST.
* @param value initial value for that parameter.
* @return StringBuilder to be used an HTTP POST body.
*/
protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Adds a new parameter to the HTTP POST body.
*
* @param body HTTP POST body.
* @param name parameter's name.
* @param value parameter's value.
*/
protected static void addParameter(StringBuilder body, String name,
String value) {
nonNull(body).append('&')
.append(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Gets an {@link HttpURLConnection} given an URL.
*/
protected HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
return conn;
}
/**
* Convenience method to convert an InputStream to a String.
* <p>
* If the stream ends in a newline character, it will be stripped.
* <p>
* If the stream is {@literal null}, returns an empty string.
*/
protected static String getString(InputStream stream) throws IOException {
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
// strip last newline
content.setLength(content.length() - 1);
}
return content.toString();
}
private static String getAndClose(InputStream stream) throws IOException {
try {
return getString(stream);
} finally {
if (stream != null) {
close(stream);
}
}
}
static <T> T nonNull(T argument) {
if (argument == null) {
throw new IllegalArgumentException("argument cannot be null");
}
return argument;
}
void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| zyf404283839-gcm-demo-client | gcm-server/src/com/google/android/gcm/server/Sender.java | Java | asf20 | 24,302 |
/*
* 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.gcm.server;
import java.io.Serializable;
/**
* Result of a GCM message request that returned HTTP status code 200.
*
* <p>
* If the message is successfully created, the {@link #getMessageId()} returns
* the message id and {@link #getErrorCodeName()} returns {@literal null};
* otherwise, {@link #getMessageId()} returns {@literal null} and
* {@link #getErrorCodeName()} returns the code of the error.
*
* <p>
* There are cases when a request is accept and the message successfully
* created, but GCM has a canonical registration id for that device. In this
* case, the server should update the registration id to avoid rejected requests
* in the future.
*
* <p>
* In a nutshell, the workflow to handle a result is:
* <pre>
* - Call {@link #getMessageId()}:
* - {@literal null} means error, call {@link #getErrorCodeName()}
* - non-{@literal null} means the message was created:
* - Call {@link #getCanonicalRegistrationId()}
* - if it returns {@literal null}, do nothing.
* - otherwise, update the server datastore with the new id.
* </pre>
*/
public final class Result implements Serializable {
private final String messageId;
private final String canonicalRegistrationId;
private final String errorCode;
public static final class Builder {
// optional parameters
private String messageId;
private String canonicalRegistrationId;
private String errorCode;
public Builder canonicalRegistrationId(String value) {
canonicalRegistrationId = value;
return this;
}
public Builder messageId(String value) {
messageId = value;
return this;
}
public Builder errorCode(String value) {
errorCode = value;
return this;
}
public Result build() {
return new Result(this);
}
}
private Result(Builder builder) {
canonicalRegistrationId = builder.canonicalRegistrationId;
messageId = builder.messageId;
errorCode = builder.errorCode;
}
/**
* Gets the message id, if any.
*/
public String getMessageId() {
return messageId;
}
/**
* Gets the canonical registration id, if any.
*/
public String getCanonicalRegistrationId() {
return canonicalRegistrationId;
}
/**
* Gets the error code, if any.
*/
public String getErrorCodeName() {
return errorCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (messageId != null) {
builder.append(" messageId=").append(messageId);
}
if (canonicalRegistrationId != null) {
builder.append(" canonicalRegistrationId=")
.append(canonicalRegistrationId);
}
if (errorCode != null) {
builder.append(" errorCode=").append(errorCode);
}
return builder.append(" ]").toString();
}
}
| zyf404283839-gcm-demo-client | gcm-server/src/com/google/android/gcm/server/Result.java | Java | asf20 | 3,458 |
/*
* 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.gcm.server;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result of a GCM multicast message request .
*/
public final class MulticastResult implements Serializable {
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
private final List<Result> results;
private final List<Long> retryMulticastIds;
public static final class Builder {
private final List<Result> results = new ArrayList<Result>();
// required parameters
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
// optional parameters
private List<Long> retryMulticastIds;
public Builder(int success, int failure, int canonicalIds,
long multicastId) {
this.success = success;
this.failure = failure;
this.canonicalIds = canonicalIds;
this.multicastId = multicastId;
}
public Builder addResult(Result result) {
results.add(result);
return this;
}
public Builder retryMulticastIds(List<Long> retryMulticastIds) {
this.retryMulticastIds = retryMulticastIds;
return this;
}
public MulticastResult build() {
return new MulticastResult(this);
}
}
private MulticastResult(Builder builder) {
success = builder.success;
failure = builder.failure;
canonicalIds = builder.canonicalIds;
multicastId = builder.multicastId;
results = Collections.unmodifiableList(builder.results);
List<Long> tmpList = builder.retryMulticastIds;
if (tmpList == null) {
tmpList = Collections.emptyList();
}
retryMulticastIds = Collections.unmodifiableList(tmpList);
}
/**
* Gets the multicast id.
*/
public long getMulticastId() {
return multicastId;
}
/**
* Gets the number of successful messages.
*/
public int getSuccess() {
return success;
}
/**
* Gets the total number of messages sent, regardless of the status.
*/
public int getTotal() {
return success + failure;
}
/**
* Gets the number of failed messages.
*/
public int getFailure() {
return failure;
}
/**
* Gets the number of successful messages that also returned a canonical
* registration id.
*/
public int getCanonicalIds() {
return canonicalIds;
}
/**
* Gets the results of each individual message, which is immutable.
*/
public List<Result> getResults() {
return results;
}
/**
* Gets additional ids if more than one multicast message was sent.
*/
public List<Long> getRetryMulticastIds() {
return retryMulticastIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MulticastResult(")
.append("multicast_id=").append(multicastId).append(",")
.append("total=").append(getTotal()).append(",")
.append("success=").append(success).append(",")
.append("failure=").append(failure).append(",")
.append("canonical_ids=").append(canonicalIds).append(",");
if (!results.isEmpty()) {
builder.append("results: " + results);
}
return builder.toString();
}
}
| zyf404283839-gcm-demo-client | gcm-server/src/com/google/android/gcm/server/MulticastResult.java | Java | asf20 | 3,886 |
/*
* 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.gcm.server;
/**
* Constants used on GCM service communication.
*/
public final class Constants {
/**
* Endpoint for sending messages.
*/
public static final String GCM_SEND_ENDPOINT =
"https://android.googleapis.com/gcm/send";
/**
* HTTP parameter for registration id.
*/
public static final String PARAM_REGISTRATION_ID = "registration_id";
/**
* HTTP parameter for collapse key.
*/
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
/**
* HTTP parameter for delaying the message delivery if the device is idle.
*/
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
/**
* HTTP parameter for telling gcm to validate the message without actually sending it.
*/
public static final String PARAM_DRY_RUN = "dry_run";
/**
* HTTP parameter for package name that can be used to restrict message delivery by matching
* against the package name used to generate the registration id.
*/
public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name";
/**
* Prefix to HTTP parameter used to pass key-values in the message payload.
*/
public static final String PARAM_PAYLOAD_PREFIX = "data.";
/**
* Prefix to HTTP parameter used to set the message time-to-live.
*/
public static final String PARAM_TIME_TO_LIVE = "time_to_live";
/**
* Too many messages sent by the sender. Retry after a while.
*/
public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded";
/**
* Too many messages sent by the sender to a specific device.
* Retry after a while.
*/
public static final String ERROR_DEVICE_QUOTA_EXCEEDED =
"DeviceQuotaExceeded";
/**
* Missing registration_id.
* Sender should always add the registration_id to the request.
*/
public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration";
/**
* Bad registration_id. Sender should remove this registration_id.
*/
public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration";
/**
* The sender_id contained in the registration_id does not match the
* sender_id used to register with the GCM servers.
*/
public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId";
/**
* The user has uninstalled the application or turned off notifications.
* Sender should stop sending messages to this device and delete the
* registration_id. The client needs to re-register with the GCM servers to
* receive notifications again.
*/
public static final String ERROR_NOT_REGISTERED = "NotRegistered";
/**
* The payload of the message is too big, see the limitations.
* Reduce the size of the message.
*/
public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig";
/**
* Collapse key is required. Include collapse key in the request.
*/
public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey";
/**
* A particular message could not be sent because the GCM servers were not
* available. Used only on JSON requests, as in plain text requests
* unavailability is indicated by a 503 response.
*/
public static final String ERROR_UNAVAILABLE = "Unavailable";
/**
* A particular message could not be sent because the GCM servers encountered
* an error. Used only on JSON requests, as in plain text requests internal
* errors are indicated by a 500 response.
*/
public static final String ERROR_INTERNAL_SERVER_ERROR =
"InternalServerError";
/**
* Time to Live value passed is less than zero or more than maximum.
*/
public static final String ERROR_INVALID_TTL= "InvalidTtl";
/**
* Token returned by GCM when a message was successfully sent.
*/
public static final String TOKEN_MESSAGE_ID = "id";
/**
* Token returned by GCM when the requested registration id has a canonical
* value.
*/
public static final String TOKEN_CANONICAL_REG_ID = "registration_id";
/**
* Token returned by GCM when there was an error sending a message.
*/
public static final String TOKEN_ERROR = "Error";
/**
* JSON-only field representing the registration ids.
*/
public static final String JSON_REGISTRATION_IDS = "registration_ids";
/**
* JSON-only field representing the payload data.
*/
public static final String JSON_PAYLOAD = "data";
/**
* JSON-only field representing the number of successful messages.
*/
public static final String JSON_SUCCESS = "success";
/**
* JSON-only field representing the number of failed messages.
*/
public static final String JSON_FAILURE = "failure";
/**
* JSON-only field representing the number of messages with a canonical
* registration id.
*/
public static final String JSON_CANONICAL_IDS = "canonical_ids";
/**
* JSON-only field representing the id of the multicast request.
*/
public static final String JSON_MULTICAST_ID = "multicast_id";
/**
* JSON-only field representing the result of each individual request.
*/
public static final String JSON_RESULTS = "results";
/**
* JSON-only field representing the error field of an individual request.
*/
public static final String JSON_ERROR = "error";
/**
* JSON-only field sent by GCM when a message was successfully sent.
*/
public static final String JSON_MESSAGE_ID = "message_id";
private Constants() {
throw new UnsupportedOperationException();
}
}
| zyf404283839-gcm-demo-client | gcm-server/src/com/google/android/gcm/server/Constants.java | Java | asf20 | 6,107 |
/*
* 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 com.google.android.apps.authenticator;
import junit.framework.TestCase;
/**
* Unit tests for {@link Utilities}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class UtilitiesTest extends TestCase {
public void testMillisToSeconds() {
// Test rounding
assertEquals(1234, Utilities.millisToSeconds(1234567));
assertEquals(1234, Utilities.millisToSeconds(1234000));
assertEquals(1234, Utilities.millisToSeconds(1234999));
// Test that it works fine for longs
assertEquals(12345678901L, Utilities.millisToSeconds(12345678901234L));
}
public void testSecondsToMillis() {
assertEquals(1234000, Utilities.secondsToMillis(1234));
// Test that it works fine for longs
assertEquals(12345678901000L, Utilities.secondsToMillis(12345678901L));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/UtilitiesTest.java | Java | asf20 | 1,423 |
/*
* 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 com.google.android.apps.authenticator;
import static org.mockito.MockitoAnnotations.initMocks;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.dataimport.ImportController;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
import android.test.MoreAsserts;
import android.view.View;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
/**
* Unit test for authenticator activity (part/shard 2).
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class AuthenticatorActivityPart2Test
extends ActivityInstrumentationTestCase2<AuthenticatorActivity> {
private AccountDb mAccountDb;
@Mock private ImportController mMockDataImportController;
public AuthenticatorActivityPart2Test() {
super(TestUtilities.APP_PACKAGE_NAME, AuthenticatorActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
mAccountDb = DependencyInjector.getAccountDb();
initMocks(this);
DependencyInjector.setDataImportController(mMockDataImportController);
}
@Override
protected void tearDown() throws Exception {
// Stop the activity to avoid it using the DependencyInjector after it's been closed.
TestUtilities.invokeFinishActivityOnUiThread(getActivity());
DependencyInjector.close();
super.tearDown();
}
public void testAccountSetup_validTotpUriAccepted() throws Throwable {
getActivity();
String secret = "CQAHUXJ2VWDI7WFF";
String accountName = "9.99.99.999";
callOnActivityResultOnUiThreadWithScannedUri(
"otpauth://totp/" + accountName + "?secret=" + secret);
List<String> accountNames = new ArrayList<String>();
assertEquals(1, mAccountDb.getNames(accountNames));
assertEquals(accountName, accountNames.get(0));
assertEquals(secret, mAccountDb.getSecret(accountName));
assertEquals(OtpType.TOTP, mAccountDb.getType(accountName));
assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue
}
public void testAccountSetup_validHotpUriWithoutCounterAccepted() throws Throwable {
getActivity();
String secret = "CQAHUXJ2VWDI7WFF";
String accountName = "9.99.99.999";
callOnActivityResultOnUiThreadWithScannedUri(
"otpauth://hotp/" + accountName + "?secret=" + secret);
List<String> accountNames = new ArrayList<String>();
assertEquals(1, mAccountDb.getNames(accountNames));
assertEquals(accountName, accountNames.get(0));
assertEquals(secret, mAccountDb.getSecret(accountName));
assertEquals(OtpType.HOTP, mAccountDb.getType(accountName));
assertEquals(new Integer(0), mAccountDb.getCounter(accountName));
assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue
}
public void testAccountSetup_validHotpUriWithCounterAccepted() throws Throwable {
getActivity();
String secret = "CQAHUXJ2VWDI7WFF";
String accountName = "9.99.99.999";
callOnActivityResultOnUiThreadWithScannedUri(
"otpauth://hotp/" + accountName + "?secret=" + secret + "&counter=264");
List<String> accountNames = new ArrayList<String>();
assertEquals(1, mAccountDb.getNames(accountNames));
assertEquals(accountName, accountNames.get(0));
assertEquals(secret, mAccountDb.getSecret(accountName));
assertEquals(OtpType.HOTP, mAccountDb.getType(accountName));
assertEquals(new Integer(264), mAccountDb.getCounter(accountName));
assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue
}
///////////////////// Tests with Scanned URIs returned in ActivityResult ////////////////
private void checkBadAccountSetup(String uri, int dialogId) throws Throwable {
getActivity();
callOnActivityResultOnUiThreadWithScannedUri(uri);
List<String> accountNames = new ArrayList<String>();
mAccountDb.getNames(accountNames);
MoreAsserts.assertEmpty(accountNames);
TestUtilities.assertDialogWasDisplayed(getActivity(), dialogId);
assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue
}
public void testAccountSetup_uriWithMissingSecretRejected() throws Throwable {
checkBadAccountSetup("otpauth://totp/9.99.99.999?secret2=unused",
Utilities.INVALID_SECRET_IN_QR_CODE);
}
public void testAccountSetup_uriWithEmptySecretRejected() throws Throwable {
checkBadAccountSetup("otpauth://totp/9.99.99.999?secret=", Utilities.INVALID_SECRET_IN_QR_CODE);
}
public void testAccountSetup_uriWithInvalidSecretRejected() throws Throwable {
// The URI contains an invalid base32 characters: 1 and 8
checkBadAccountSetup("otpauth://totp/9.99.99.999?secret=CQ1HUXJ2VWDI8WFF",
Utilities.INVALID_SECRET_IN_QR_CODE);
}
public void testAccountSetup_withNullUri() throws Throwable {
checkBadAccountSetup(null, Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withNullScheme() throws Throwable {
checkBadAccountSetup("totp/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withBadScheme() throws Throwable {
checkBadAccountSetup("otpauth?//totp/9.99.99.999?secret=CQAHUXJ2VWDI7WFF",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withEmptyAuthority() throws Throwable {
checkBadAccountSetup("otpauth:///9.99.99.999?secret=CQAHUXJ2VWDI7WFF",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withBadAuthority() throws Throwable {
checkBadAccountSetup("otpauth://bad/9.99.99.999?secret=CQAHUXJ2VWDI7WFF",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withEmptyUserAccount() throws Throwable {
checkBadAccountSetup("otpauth://totp/?secret=CQAHUXJ2VWDI7WFF",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withWhiteSpaceForUserAccount() throws Throwable {
checkBadAccountSetup("otpauth://totp/ ?secret=CQAHUXJ2VWDI7WFF",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withCounterTooBig() throws Throwable {
checkBadAccountSetup("otpauth://hotp/?secret=CQAHUXJ2VWDI7WFF&counter=34359738368",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withNonNumericCounter() throws Throwable {
checkBadAccountSetup("otpauth://hotp/?secret=CQAHUXJ2VWDI7WFF&counter=abc",
Utilities.INVALID_QR_CODE);
}
public void testAccountSetup_withNullIntent() throws Throwable {
getActivity();
callOnActivityResultOnUiThread(AuthenticatorActivity.SCAN_REQUEST, Activity.RESULT_OK, null);
List<String> accountNames = new ArrayList<String>();
mAccountDb.getNames(accountNames);
MoreAsserts.assertEmpty(accountNames);
TestUtilities.assertDialogWasDisplayed(getActivity(), Utilities.INVALID_QR_CODE);
assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue
}
/**
* Invokes the activity's {@code onActivityResult} as though it received the specified scanned
* URI.
*/
private void callOnActivityResultOnUiThreadWithScannedUri(String uri) throws Throwable {
Intent intent = new Intent(Intent.ACTION_VIEW, null);
intent.putExtra("SCAN_RESULT", uri);
callOnActivityResultOnUiThread(AuthenticatorActivity.SCAN_REQUEST, Activity.RESULT_OK, intent);
}
private void callOnActivityResultOnUiThread(
final int requestCode, final int resultCode, final Intent intent) throws Throwable {
runTestOnUiThread(new Runnable() {
@Override
public void run () {
getActivity().onActivityResult(requestCode, resultCode, intent);
}
});
}
public void testDirectAccountSetupWithConfirmationAccepted() throws Throwable {
// start AuthenticatorActivity with a valid Uri for account setup.
String secret = "CQAHUXJ2VWDI7WFF";
String accountName = "9.99.99.999";
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("otpauth://totp/" + accountName + "?secret=" + secret));
setActivityIntent(intent);
getActivity();
// check main screen does not have focus because of save confirmation dialog.
View contentView = getActivity().findViewById(R.id.content_no_accounts);
assertFalse(contentView.hasWindowFocus());
// click Ok on the dialog box which has focus.
TestUtilities.tapDialogPositiveButton(this);
// check main screen gets focus back after dialog window disappears.
TestUtilities.waitForWindowFocus(contentView);
// check update to database.
List<String> accountNames = new ArrayList<String>();
assertEquals(1, mAccountDb.getNames(accountNames));
assertEquals(accountName, accountNames.get(0));
assertEquals(secret, mAccountDb.getSecret(accountName));
assertEquals(OtpType.TOTP, mAccountDb.getType(accountName));
}
public void testDirectAccountSetupWithConfirmationRejected() throws Throwable {
// start AuthenticatorActivity with a valid Uri for account setup.
String secret = "CQAHUXJ2VWDI7WFF";
String accountName = "9.99.99.999";
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("otpauth://totp/" + accountName + "?secret=" + secret));
setActivityIntent(intent);
getActivity();
// check main screen does not have focus because of save confirmation dialog.
View contentView = getActivity().findViewById(R.id.content_no_accounts);
assertFalse(contentView.hasWindowFocus());
// click Cancel on the save confirmation dialog box.
TestUtilities.tapDialogNegativeButton(this);
// check main screen gets focus back after dialog window disappears.
TestUtilities.waitForWindowFocus(contentView);
// check database has not been updated.
List<String> accountNames = new ArrayList<String>();
assertEquals(0, mAccountDb.getNames(accountNames));
assertEquals(null, mAccountDb.getSecret(accountName));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/AuthenticatorActivityPart2Test.java | Java | asf20 | 10,954 |
/*
* 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 com.google.android.apps.authenticator.howitworks;
import com.google.android.apps.authenticator.wizard.WizardPageActivityTestBase;
import android.content.Intent;
import java.io.Serializable;
/**
* Unit tests for {@link IntroEnterPasswordActivity}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class IntroEnterPasswordActivityTest
extends WizardPageActivityTestBase<IntroEnterPasswordActivity, Serializable> {
public IntroEnterPasswordActivityTest() {
super(IntroEnterPasswordActivity.class);
}
public void testBackKeyFinishesActivity() throws Exception {
assertBackKeyFinishesActivity();
}
public void testLeftButtonFinishesActivity() throws Exception {
assertLeftButtonPressFinishesActivity();
}
public void testRightButtonStartsNextPage() throws Exception {
Intent intent = pressRightButtonAndCaptureActivityStartIntent();
assertIntentForClassInTargetPackage(IntroEnterCodeActivity.class, intent);
assertFalse(getActivity().isFinishing());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/howitworks/IntroEnterPasswordActivityTest.java | Java | asf20 | 1,637 |
/*
* 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 com.google.android.apps.authenticator.howitworks;
import com.google.android.apps.authenticator.wizard.WizardPageActivityTestBase;
import android.content.Intent;
import java.io.Serializable;
/**
* Unit tests for {@link IntroEnterCodeActivity}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class IntroEnterCodeActivityTest
extends WizardPageActivityTestBase<IntroEnterCodeActivity, Serializable> {
public IntroEnterCodeActivityTest() {
super(IntroEnterCodeActivity.class);
}
public void testBackKeyFinishesActivity() throws Exception {
assertBackKeyFinishesActivity();
}
public void testLeftButtonFinishesActivity() throws Exception {
assertLeftButtonPressFinishesActivity();
}
public void testRightButtonStartsNextPage() throws Exception {
Intent intent = pressRightButtonAndCaptureActivityStartIntent();
assertIntentForClassInTargetPackage(IntroVerifyDeviceActivity.class, intent);
assertFalse(getActivity().isFinishing());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/howitworks/IntroEnterCodeActivityTest.java | Java | asf20 | 1,620 |
/*
* 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 com.google.android.apps.authenticator.howitworks;
import com.google.android.apps.authenticator.AuthenticatorActivity;
import com.google.android.apps.authenticator.wizard.WizardPageActivityTestBase;
import android.content.Intent;
import java.io.Serializable;
/**
* Unit tests for {@link IntroVerifyDeviceActivity}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class IntroVerifyDeviceActivityTest
extends WizardPageActivityTestBase<IntroVerifyDeviceActivity, Serializable> {
public IntroVerifyDeviceActivityTest() {
super(IntroVerifyDeviceActivity.class);
}
public void testBackKeyFinishesActivity() throws Exception {
assertBackKeyFinishesActivity();
}
public void testLeftButtonFinishesActivity() throws Exception {
assertLeftButtonPressFinishesActivity();
}
public void testRightButtonExitsWizard() throws Exception {
Intent intent = pressRightButtonAndCaptureActivityStartIntent();
assertIntentForClassInTargetPackage(AuthenticatorActivity.class, intent);
assertTrue(getActivity().isFinishing());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/howitworks/IntroVerifyDeviceActivityTest.java | Java | asf20 | 1,695 |
/*
* 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 com.google.android.apps.authenticator;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.dataimport.ImportController;
import com.google.android.apps.authenticator.howitworks.IntroEnterPasswordActivity;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator.testability.StartActivityListener;
import com.google.android.apps.authenticator2.R;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.ViewAsserts;
import android.text.ClipboardManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.List;
/**
* Unit test for authenticator activity (part/shard 1).
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class AuthenticatorActivityTest extends
ActivityInstrumentationTestCase2<AuthenticatorActivity> {
private AccountDb mAccountDb;
@Mock private ImportController mMockDataImportController;
public AuthenticatorActivityTest() {
super(TestUtilities.APP_PACKAGE_NAME, AuthenticatorActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
mAccountDb = DependencyInjector.getAccountDb();
initMocks(this);
DependencyInjector.setDataImportController(mMockDataImportController);
TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver();
}
@Override
protected void tearDown() throws Exception {
// Stop the activity to avoid it using the DependencyInjector after it's been closed.
TestUtilities.invokeFinishActivityOnUiThread(getActivity());
DependencyInjector.close();
super.tearDown();
}
public void testGetTitle() {
assertEquals(getActivity().getString(R.string.app_name), getActivity().getTitle());
}
//////////////////////// Main screen UI Tests ///////////////////////////////
public void testNoAccountUi() throws Throwable {
getActivity();
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
TextView enterPinPrompt = (TextView) getActivity().findViewById(R.id.enter_pin_prompt);
Button howItWorksButton = (Button) getActivity().findViewById(R.id.how_it_works_button);
Button addAccountButton = (Button) getActivity().findViewById(R.id.add_account_button);
View contentWhenNoAccounts = getActivity().findViewById(R.id.content_no_accounts);
// check existence of fields
assertNotNull(userList);
assertNotNull(enterPinPrompt);
assertNotNull(howItWorksButton);
assertNotNull(addAccountButton);
assertNotNull(contentWhenNoAccounts);
// check visibility
View origin = getActivity().getWindow().getDecorView();
ViewAsserts.assertOnScreen(origin, enterPinPrompt);
ViewAsserts.assertOnScreen(origin, howItWorksButton);
ViewAsserts.assertOnScreen(origin, addAccountButton);
ViewAsserts.assertOnScreen(origin, contentWhenNoAccounts);
assertFalse(userList.isShown());
}
public void testGetOtpWithOneTotpAccount() throws Throwable {
mAccountDb.update(
"johndoeTotp@gmail.com", "7777777777777777", "johndoeTotp@gmail.com", OtpType.TOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
assertEquals(1, userList.getChildCount());
View listEntry = userList.getChildAt(0);
String user = ((TextView) listEntry.findViewById(R.id.current_user)).getText().toString();
String pin = ((TextView) listEntry.findViewById(R.id.pin_value)).getText().toString();
assertEquals("johndoeTotp@gmail.com", user);
assertTrue(Integer.parseInt(pin) >= 0 && Integer.parseInt(pin) <= 999999);
assertEquals(6, pin.length());
assertFalse(listEntry.findViewById(R.id.next_otp).isShown());
assertTrue(listEntry.findViewById(R.id.countdown_icon).isShown());
}
public void testGetOtpWithOneHotpAccount() throws Throwable {
mAccountDb.update(
"johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
assertEquals(1, userList.getChildCount());
View listEntry = userList.getChildAt(0);
String user = ((TextView) listEntry.findViewById(R.id.current_user)).getText().toString();
String pin = ((TextView) listEntry.findViewById(R.id.pin_value)).getText().toString();
assertEquals("johndoeHotp@gmail.com", user);
assertEquals(getActivity().getString(R.string.empty_pin), pin); // starts empty
assertFalse(listEntry.findViewById(R.id.countdown_icon).isShown());
View buttonView = listEntry.findViewById(R.id.next_otp);
assertTrue(buttonView.isShown());
// get next Otp value by clicking icon
TestUtilities.clickView(getInstrumentation(), buttonView);
pin = ((TextView) listEntry.findViewById(R.id.pin_value)).getText().toString();
assertEquals("683298", pin);
}
public void testGetOtpWithMultipleAccounts() throws Throwable {
mAccountDb.update(
"johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null);
mAccountDb.update(
"johndoeTotp1@gmail.com", "2222222222222222", "johndoeTotp1@gmail.com", OtpType.TOTP, null);
mAccountDb.update(
"johndoeTotp2@gmail.com", "3333333333333333", "johndoeTotp2@gmail.com", OtpType.TOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
assertEquals(3, userList.getChildCount());
// check hotp account
View listEntry0 = userList.getChildAt(0);
String user = ((TextView) listEntry0.findViewById(R.id.current_user)).getText().toString();
String pin = ((TextView) listEntry0.findViewById(R.id.pin_value)).getText().toString();
assertEquals("johndoeHotp@gmail.com", user);
assertEquals(getActivity().getString(R.string.empty_pin), pin); // starts empty
assertFalse(listEntry0.findViewById(R.id.countdown_icon).isShown());
View buttonView = listEntry0.findViewById(R.id.next_otp);
assertTrue(buttonView.isShown());
// get next Otp value by clicking icon
TestUtilities.clickView(getInstrumentation(), buttonView);
listEntry0 = userList.getChildAt(0); // get refreshed value after clicking nextOtp button.
pin = ((TextView) listEntry0.findViewById(R.id.pin_value)).getText().toString();
assertEquals("683298", pin);
// check first totp account
View listEntry1 = userList.getChildAt(1);
user = ((TextView) listEntry1.findViewById(R.id.current_user)).getText().toString();
pin = ((TextView) listEntry1.findViewById(R.id.pin_value)).getText().toString();
assertEquals("johndoeTotp1@gmail.com", user);
assertTrue(Integer.parseInt(pin) > 0 && Integer.parseInt(pin) <= 999999);
assertFalse(listEntry1.findViewById(R.id.next_otp).isShown());
assertTrue(listEntry1.findViewById(R.id.countdown_icon).isShown());
View listEntry2 = userList.getChildAt(2);
// check second totp account
user = ((TextView) listEntry2.findViewById(R.id.current_user)).getText().toString();
pin = ((TextView) listEntry2.findViewById(R.id.pin_value)).getText().toString();
assertEquals("johndoeTotp2@gmail.com", user);
assertTrue(Integer.parseInt(pin) > 0 && Integer.parseInt(pin) <= 999999);
assertFalse(listEntry1.findViewById(R.id.next_otp).isShown());
assertTrue(listEntry1.findViewById(R.id.countdown_icon).isShown());
}
////////////////////////// Context Menu Tests ////////////////////////////
public void testContextMenuCheckCode() throws Exception {
mAccountDb.update(
"johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
View listEntry0 = userList.getChildAt(0);
TestUtilities.openContextMenuAndInvokeItem(
getInstrumentation(),
getActivity(),
listEntry0,
AuthenticatorActivity.CHECK_KEY_VALUE_ID);
Intent launchIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
assertEquals(
new ComponentName(getInstrumentation().getTargetContext(), CheckCodeActivity.class),
launchIntent.getComponent());
assertEquals("johndoeHotp@gmail.com", launchIntent.getStringExtra("user"));
}
public void testContextMenuRemove() throws Exception {
mAccountDb.update(
"johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
View listEntry0 = userList.getChildAt(0);
TestUtilities.openContextMenuAndInvokeItem(
getInstrumentation(),
getActivity(),
listEntry0,
AuthenticatorActivity.REMOVE_ID);
// Select Remove on confirmation dialog to remove account.
sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
// check main screen gets focus back;
TestUtilities.waitForWindowFocus(listEntry0);
// check that account is deleted in database.
assertEquals(0, mAccountDb.getNames(new ArrayList<String>()));
}
public void testContextMenuRename() throws Exception {
mAccountDb.update(
"johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
View listEntry0 = userList.getChildAt(0);
TestUtilities.openContextMenuAndInvokeItem(
getInstrumentation(),
getActivity(),
listEntry0,
AuthenticatorActivity.RENAME_ID);
// Type new name and select save on dialog.
sendKeys("21*DPAD_RIGHT"); // move right to end;
sendKeys("21*DEL"); // delete the entire name
sendKeys("N E W N A M E AT G M A I L PERIOD C O M");
sendKeys("DPAD_DOWN");
TestUtilities.tapDialogPositiveButton(this); // select save on the dialog
// check main screen gets focus back;
listEntry0 = userList.getChildAt(0);
TestUtilities.waitForWindowFocus(listEntry0);
// check update to database.
List<String> accountNames = new ArrayList<String>();
assertEquals(1, mAccountDb.getNames(accountNames));
assertEquals("newname@gmail.com", accountNames.get(0));
}
public void testContextMenuCopyToClipboard() throws Exception {
// use HOTP to avoid any timing issues when "current" pin is compared with clip board text.
mAccountDb.update(
"johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null);
ListView userList = (ListView) getActivity().findViewById(R.id.user_list);
// find and click next otp button.
View buttonView = getActivity().findViewById(R.id.next_otp);
TestUtilities.clickView(getInstrumentation(), buttonView);
// get the pin being displayed
View listEntry0 = userList.getChildAt(0);
String pin = ((TextView) listEntry0.findViewById(R.id.pin_value)).getText().toString();
TestUtilities.openContextMenuAndInvokeItem(
getInstrumentation(),
getActivity(),
listEntry0,
AuthenticatorActivity.COPY_TO_CLIPBOARD_ID);
// check clip board value.
Context context = getInstrumentation().getTargetContext();
ClipboardManager clipboard =
(ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
assertEquals(pin, clipboard.getText());
}
/////////////////////////// Options Menu Tests /////////////////////////////
private void checkOptionsMenuItemWithComponent(int itemId, Class<?> cls) throws Exception {
TestUtilities.openOptionsMenuAndInvokeItem(getInstrumentation(), getActivity(), itemId);
Intent launchIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
assertEquals(new ComponentName(getInstrumentation().getTargetContext(), cls),
launchIntent.getComponent());
}
public void testOptionsMenuHowItWorks() throws Exception {
checkOptionsMenuItemWithComponent(R.id.how_it_works, IntroEnterPasswordActivity.class);
}
public void testOptionsMenuAddAccount() throws Exception {
checkOptionsMenuItemWithComponent(R.id.add_account, AddOtherAccountActivity.class);
}
public void testOptionsMenuSettings() throws Exception {
checkOptionsMenuItemWithComponent(R.id.settings, SettingsActivity.class);
}
public void testIntentActionScanBarcode_withScannerInstalled() throws Exception {
setActivityIntent(new Intent(AuthenticatorActivity.ACTION_SCAN_BARCODE));
getActivity();
Intent launchIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
assertEquals("com.google.zxing.client.android.SCAN", launchIntent.getAction());
assertEquals("QR_CODE_MODE", launchIntent.getStringExtra("SCAN_MODE"));
assertEquals(false, launchIntent.getExtras().get("SAVE_HISTORY"));
}
public void testIntentActionScanBarcode_withScannerNotInstalled() throws Exception {
// When no barcode scanner is installed no matching activities are found as emulated below.
StartActivityListener mockStartActivityListener = mock(StartActivityListener.class);
doThrow(new ActivityNotFoundException())
.when(mockStartActivityListener).onStartActivityInvoked(
Mockito.<Context>anyObject(), Mockito.<Intent>anyObject());
DependencyInjector.setStartActivityListener(mockStartActivityListener);
setActivityIntent(new Intent(AuthenticatorActivity.ACTION_SCAN_BARCODE));
getActivity();
TestUtilities.assertDialogWasDisplayed(
getActivity(), Utilities.DOWNLOAD_DIALOG);
}
/////////////////////////// Data Import tests /////////////////////////////
public void testLaunchingActivityStartsImportController() {
AuthenticatorActivity activity = getActivity();
ArgumentCaptor<Context> contextArgCaptor = ArgumentCaptor.forClass(Context.class);
verify(mMockDataImportController)
.start(contextArgCaptor.capture(), Mockito.<ImportController.Listener>anyObject());
assertEquals(activity, contextArgCaptor.getValue());
}
public void testImportControllerOldAppUninstallCallbackDisplaysDialog() {
final ImportController.Listener listener = startActivityAndGetDataImportListener();
assertNotNull(listener);
invokeDataImportListenerOnOldAppUninstallSuggestedOnMainThread(listener, new Intent());
invokeDataImportListenerFinishedOnMainThread(listener);
TestUtilities.assertDialogWasDisplayed(
getActivity(), AuthenticatorActivity.DIALOG_ID_UNINSTALL_OLD_APP);
}
public void testImportControllerDataImportedDoesNotBlowUp() {
final ImportController.Listener listener = startActivityAndGetDataImportListener();
assertNotNull(listener);
invokeDataImportListenerOnDataImportedOnMainThread(listener);
invokeDataImportListenerFinishedOnMainThread(listener);
getInstrumentation().waitForIdleSync();
}
public void testImportControllerUnknownFailureDoesNotBlowUp() {
final ImportController.Listener listener = startActivityAndGetDataImportListener();
assertNotNull(listener);
invokeDataImportListenerFinishedOnMainThread(listener);
getInstrumentation().waitForIdleSync();
}
private ImportController.Listener startActivityAndGetDataImportListener() {
ArgumentCaptor<ImportController.Listener> listenerArgCaptor =
ArgumentCaptor.forClass(ImportController.Listener.class);
doNothing().when(mMockDataImportController).start(
Mockito.<Context>anyObject(), listenerArgCaptor.capture());
getActivity();
return listenerArgCaptor.getValue();
}
private void invokeDataImportListenerOnOldAppUninstallSuggestedOnMainThread(
final ImportController.Listener listener, final Intent uninstallIntent) {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
listener.onOldAppUninstallSuggested(uninstallIntent);
}
});
}
private void invokeDataImportListenerOnDataImportedOnMainThread(
final ImportController.Listener listener) {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
listener.onDataImported();
}
});
}
private void invokeDataImportListenerFinishedOnMainThread(
final ImportController.Listener listener) {
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
listener.onFinished();
}
});
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/AuthenticatorActivityTest.java | Java | asf20 | 17,750 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.test.AndroidTestCase;
/**
* Unit tests for {@link TotpClock}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class TotpClockTest extends AndroidTestCase {
private TotpClock mClock;
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getContext());
mClock = new TotpClock(DependencyInjector.getContext());
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testCurrentTimeMillisUsesCurrentTimeAndTimeCorrection() {
assertEquals(0, mClock.getTimeCorrectionMinutes());
long millisBefore = System.currentTimeMillis();
long actualMillis = mClock.currentTimeMillis();
long millisAfter = System.currentTimeMillis();
assertInRangeInclusive(actualMillis, millisBefore, millisAfter);
mClock.setTimeCorrectionMinutes(137);
millisBefore = System.currentTimeMillis();
actualMillis = mClock.currentTimeMillis();
millisAfter = System.currentTimeMillis();
assertInRangeInclusive(
actualMillis,
millisBefore + 137 * Utilities.MINUTE_IN_MILLIS,
millisAfter + 137 * Utilities.MINUTE_IN_MILLIS);
}
public void testTimeCorrectionBackedByPreferences() {
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(DependencyInjector.getContext());
assertTrue(preferences.edit().putInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 7).commit());
assertEquals(7, mClock.getTimeCorrectionMinutes());
mClock.setTimeCorrectionMinutes(42);
assertEquals(42, preferences.getInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 0));
assertEquals(42, mClock.getTimeCorrectionMinutes());
}
public void testTimeCorrectionCaching() {
// Check that the preference is only read first time the the time correction value is requested
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(DependencyInjector.getContext());
assertTrue(preferences.edit().putInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 7).commit());
assertEquals(7, mClock.getTimeCorrectionMinutes());
assertTrue(preferences.edit().putInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 42).commit());
assertEquals(7, mClock.getTimeCorrectionMinutes());
}
private static void assertInRangeInclusive(
long actual, long expectedMinValue, long expectedMaxValue) {
if ((actual < expectedMinValue) || (actual > expectedMaxValue)) {
fail(actual + " not in [" + expectedMinValue + ", " + expectedMaxValue + "]");
}
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/TotpClockTest.java | Java | asf20 | 3,452 |
/*
* 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 com.google.android.apps.authenticator;
import android.test.AndroidTestCase;
import java.io.File;
import java.io.IOException;
/**
* Unit tests for {@link Utilities}.
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class FileUtilitiesTest extends AndroidTestCase {
public void testRestrictAccess_withActualDirectory() throws Exception {
File dir = createTempDirInCacheDir();
try {
String path = dir.getPath();
setFilePermissions(path, 0755);
FileUtilities.restrictAccessToOwnerOnly(path);
assertEquals(0700, getFilePermissions(path) & 0777);
} finally {
dir.delete();
}
}
public void testRestrictAccess_withActualNonExistentDirectory()
throws Exception {
File dir = createTempDirInCacheDir();
assertTrue(dir.delete());
try {
FileUtilities.restrictAccessToOwnerOnly(dir.getPath());
fail();
} catch (IOException expected) {}
}
public void testGetStat_withActualDirectory() throws Exception {
File dir = createTempDirInCacheDir();
try {
String path = dir.getPath();
setFilePermissions(path, 0755);
FileUtilities.StatStruct s1 = FileUtilities.getStat(path);
assertEquals(0755, s1.mode & 0777);
long ctime1 = s1.ctime;
assertTrue(s1.toString().contains(Long.toString(ctime1)));
setFilePermissions(path, 0700);
FileUtilities.StatStruct s2 = FileUtilities.getStat(path);
assertEquals(0700, s2.mode & 0777);
long ctime2 = s2.ctime;
assertTrue(ctime2 >= ctime1);
} finally {
dir.delete();
}
}
public void testGetStat_withActualNonExistentDirectory() throws Exception {
File dir = createTempDirInCacheDir();
assertTrue(dir.delete());
try {
FileUtilities.getStat(dir.getPath());
fail();
} catch (IOException expected) {}
}
private static void setFilePermissions(String path, int mode) throws Exception {
// IMPLEMENTATION NOTE: The code below simply invokes
// android.os.FileUtils.setPermissions(path, mode, -1, -1) via Reflection.
int errorCode = (Integer) Class.forName("android.os.FileUtils")
.getMethod("setPermissions", String.class, int.class, int.class, int.class)
.invoke(null, path, mode, -1, -1);
assertEquals(0, errorCode);
assertEquals(mode, getFilePermissions(path) & 0777);
}
private static int getFilePermissions(String path)
throws Exception {
// IMPLEMENTATION NOTE: The code below simply invokes
// android.os.FileUtils.getPermissions(path, int[]) via Reflection.
int[] modeUidAndGid = new int[3];
int errorCode = (Integer) Class.forName("android.os.FileUtils")
.getMethod("getPermissions", String.class, int[].class)
.invoke(null, path, modeUidAndGid);
assertEquals(0, errorCode);
return modeUidAndGid[0];
}
private File createTempDirInCacheDir() throws IOException {
// IMPLEMENTATION NOTE: There's no API to create temp dir on one go. Thus, we create
// a temp file, delete it, and recreate it as a directory.
File file = File.createTempFile(getClass().getSimpleName(), "", getContext().getCacheDir());
assertTrue(file.delete());
assertTrue(file.mkdir());
return file;
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/FileUtilitiesTest.java | Java | asf20 | 3,863 |
/*
* 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 com.google.android.apps.authenticator.wizard;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import com.google.android.apps.authenticator.AuthenticatorActivity;
import com.google.android.apps.authenticator.TestUtilities;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.test.ActivityUnitTestCase;
import android.view.View;
import android.widget.TextView;
import java.io.Serializable;
/**
* Unit tests for {@link WizardPageActivity}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class WizardPageActivityTest
extends ActivityUnitTestCase<WizardPageActivityTest.TestableWizardPageActivity> {
public WizardPageActivityTest() {
super(TestableWizardPageActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testCleanStartSucceeds_withNullWizardState() {
WizardPageActivity<WizardState> activity = startActivityWithWizardState(null);
assertNull(activity.getWizardState());
}
public void testCleanStartSucceeds_withWizardState() {
WizardState wizardState = new WizardState();
wizardState.mText = "123";
WizardPageActivity<WizardState> activity = startActivityWithWizardState(wizardState);
// Check that the wizard state has been loaded by the Activity from the Intent
assertEquals(wizardState, activity.getWizardState());
}
public void testStartWithInstanceStateLoadsWizardStateFromBundle() {
WizardState wizardStateInIntent = new WizardState();
WizardState wizardStateInBundle = new WizardState();
wizardStateInBundle.mText = "1234";
Bundle savedInstanceState = new Bundle();
savedInstanceState.putSerializable(WizardPageActivity.KEY_WIZARD_STATE, wizardStateInBundle);
WizardPageActivity<WizardState> activity =
startActivity(getStartIntent(wizardStateInIntent), savedInstanceState, null);
// Check that the wizard state has been loaded by the Activity from the Bundle
assertEquals(wizardStateInBundle, activity.getWizardState());
}
public void testOnSaveSaveInstanceStateSavesWizardStateInBundle() {
WizardState wizardState = new WizardState();
wizardState.mText = "test";
WizardPageActivity<WizardState> activity = startActivityWithWizardState(wizardState);
Bundle savedInstanceState = new Bundle();
activity.onSaveInstanceState(savedInstanceState);
assertEquals(
wizardState,
savedInstanceState.getSerializable(WizardPageActivity.KEY_WIZARD_STATE));
}
public void testSetWizardState() {
WizardPageActivity<WizardState> activity = startActivity();
WizardState wizardState = new WizardState();
wizardState.mText = "test";
assertFalse(wizardState.equals(activity.getWizardState()));
activity.setWizardState(wizardState);
assertEquals(wizardState, activity.getWizardState());
}
public void testUiStateAfterCreate() {
WizardPageActivity<WizardState> activity = startActivity();
TestUtilities.assertViewVisibleOnScreen(activity.mLeftButton);
TestUtilities.assertViewVisibleOnScreen(activity.mRightButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mMiddleButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mCancelButton);
assertEquals(
activity.getString(R.string.button_back), ((TextView) activity.mLeftButton).getText());
assertEquals(activity.getString(
R.string.button_next), ((TextView) activity.mRightButton).getText());
}
public void testUiStateInButtonBarMiddleButtonOnlyMode() {
WizardPageActivity<WizardState> activity = startActivity();
activity.setButtonBarModeMiddleButtonOnly();
TestUtilities.assertViewVisibleOnScreen(activity.mMiddleButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mLeftButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mRightButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mCancelButton);
}
public void testUiStateInInlineProgressMode() {
WizardPageActivity<WizardState> activity = startActivity();
activity.showInlineProgress(null);
TestUtilities.assertViewVisibleOnScreen(activity.mCancelButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mLeftButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mRightButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mMiddleButton);
assertEquals(
activity.getString(R.string.cancel), ((TextView) activity.mCancelButton).getText());
}
public void testInlineProgressCallbackInvokedWhenCancelButtonPressed() {
WizardPageActivity<WizardState> activity = startActivity();
View.OnClickListener listener = mock(View.OnClickListener.class);
activity.showInlineProgress(listener);
activity.mCancelButton.performClick();
verify(listener).onClick(activity.mCancelButton);
}
public void testButtonBarModeRestoredAfterDismissingInlineProgress() {
WizardPageActivity<WizardState> activity = startActivity();
activity.setButtonBarModeMiddleButtonOnly();
activity.showInlineProgress(null);
activity.dismissInlineProgress();
TestUtilities.assertViewVisibleOnScreen(activity.mMiddleButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mLeftButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mRightButton);
TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mCancelButton);
}
public void testStartPageActivity() {
WizardPageActivity<WizardState> activity = startActivity();
activity.getWizardState().mText = "token";
activity.startPageActivity(TestableWizardPageActivity.class);
Intent intent = getStartedActivityIntent();
assertNotNull(intent);
assertEquals(
new ComponentName(activity, TestableWizardPageActivity.class), intent.getComponent());
assertEquals(
activity.getWizardState(),
intent.getSerializableExtra(WizardPageActivity.KEY_WIZARD_STATE));
}
public void testStartPageActivityForResult() {
WizardPageActivity<WizardState> activity = startActivity();
activity.getWizardState().mText = "token";
activity.startPageActivityForResult(TestableWizardPageActivity.class, 13);
assertEquals(13, getStartedActivityRequest());
Intent intent = getStartedActivityIntent();
assertNotNull(intent);
assertEquals(
new ComponentName(activity, TestableWizardPageActivity.class), intent.getComponent());
assertEquals(
activity.getWizardState(),
intent.getSerializableExtra(WizardPageActivity.KEY_WIZARD_STATE));
}
public void testExitWizardLaunchesAuthenticatorActivity() {
WizardPageActivity<WizardState> activity = startActivity();
activity.exitWizard();
Intent intent = getStartedActivityIntent();
assertNotNull(intent);
assertEquals(new ComponentName(activity, AuthenticatorActivity.class), intent.getComponent());
assertTrue(
(intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_TOP) == Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
public void testLeftButtonInvokesOnLeftButtonPressed() {
TestableWizardPageActivity activity = startActivity();
activity.mLeftButton.performClick();
assertTrue(activity.mOnLeftButtonPressedInvoked);
}
public void testRightButtonInvokesOnRightButtonPressed() {
TestableWizardPageActivity activity = startActivity();
activity.mRightButton.performClick();
assertTrue(activity.mOnRightButtonPressedInvoked);
}
public void testMiddleButtonInvokesOnMiddleButtonPressed() {
TestableWizardPageActivity activity = startActivity();
activity.setButtonBarModeMiddleButtonOnly();
activity.mMiddleButton.performClick();
assertTrue(activity.mOnMiddleButtonPressedInvoked);
}
public void testOnLeftButtonPressedInvokesOnBackPressed() {
TestableWizardPageActivity activity = startActivity();
activity.onLeftButtonPressed();
assertTrue(activity.mOnBackPressedInvoked);
}
private static Intent getStartIntent(WizardState wizardState) {
Intent intent = new Intent();
if (wizardState != null) {
intent.putExtra(WizardPageActivity.KEY_WIZARD_STATE, wizardState);
}
return intent;
}
private TestableWizardPageActivity startActivity() {
return startActivityWithWizardState(new WizardState());
}
private TestableWizardPageActivity startActivityWithWizardState(WizardState wizardState) {
return startActivity(getStartIntent(wizardState), null, null);
}
/**
* Subclass of {@link WizardPageActivity} to test whether certain methods of the class are
* invoked.
*/
public static class TestableWizardPageActivity extends WizardPageActivity<WizardState> {
private boolean mOnLeftButtonPressedInvoked;
private boolean mOnRightButtonPressedInvoked;
private boolean mOnMiddleButtonPressedInvoked;
private boolean mOnBackPressedInvoked;
@Override
protected void onLeftButtonPressed() {
mOnLeftButtonPressedInvoked = true;
super.onLeftButtonPressed();
}
@Override
protected void onRightButtonPressed() {
mOnRightButtonPressedInvoked = true;
super.onRightButtonPressed();
}
@Override
protected void onMiddleButtonPressed() {
mOnMiddleButtonPressedInvoked = true;
super.onMiddleButtonPressed();
}
@Override
public void onBackPressed() {
mOnBackPressedInvoked = true;
super.onBackPressed();
}
}
private static class WizardState implements Serializable {
private String mText;
@Override
public int hashCode() {
return (mText != null) ? mText.hashCode() : 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WizardState other = (WizardState) obj;
if (mText == null) {
if (other.mText != null) {
return false;
}
} else if (!mText.equals(other.mText)) {
return false;
}
return true;
}
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/wizard/WizardPageActivityTest.java | Java | asf20 | 11,172 |
/*
* 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 com.google.android.apps.authenticator.wizard;
import com.google.android.apps.authenticator.TestUtilities;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.content.ComponentName;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import java.io.Serializable;
import java.util.concurrent.TimeoutException;
/**
* Base class for unit tests of Activity classes representing pages of a wizard.
*
* @author klyubin@google.com (Alex Klyubin)
*/
@SuppressWarnings("rawtypes")
public class WizardPageActivityTestBase<
A extends WizardPageActivity, WizardState extends Serializable>
extends ActivityInstrumentationTestCase2<A> {
public WizardPageActivityTestBase(Class<A> activityClass) {
super(TestUtilities.APP_PACKAGE_NAME, activityClass);
}
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver();
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
protected void setWizardStateInActivityIntent(WizardState state) {
setActivityIntent(new Intent().putExtra(WizardPageActivity.KEY_WIZARD_STATE, state));
}
@SuppressWarnings("unchecked")
protected WizardState getWizardStateFromIntent(Intent intent) {
return (WizardState) intent.getSerializableExtra(WizardPageActivity.KEY_WIZARD_STATE);
}
/**
* Asserts that pressing the {@code Back} key finishes the Activity under test.
*/
protected void assertBackKeyFinishesActivity() throws InterruptedException, TimeoutException {
TestUtilities.invokeActivityOnBackPressedOnUiThread(getActivity());
assertTrue(getActivity().isFinishing());
}
/**
* Asserts that pressing the {@code Back} key does not finish the Activity under test.
*/
protected void assertBackKeyDoesNotFinishActivity()
throws InterruptedException, TimeoutException {
TestUtilities.invokeActivityOnBackPressedOnUiThread(getActivity());
assertFalse(getActivity().isFinishing());
}
protected void assertLeftButtonPressFinishesActivity() {
pressButton(R.id.button_left);
assertTrue(getActivity().isFinishing());
}
private void pressButton(int buttonViewId) {
View button = getActivity().findViewById(buttonViewId);
// The button can only be pressed if it's on screen and visible
assertNotNull(button);
TestUtilities.assertViewVisibleOnScreen(button);
assertTrue(button.isEnabled());
TestUtilities.assertViewVisibleOnScreen(button);
TestUtilities.clickView(getInstrumentation(), button);
}
protected void pressLeftButton() {
pressButton(R.id.button_left);
}
protected void pressRightButton() {
pressButton(R.id.button_right);
}
protected void pressMiddleButton() {
pressButton(R.id.button_middle);
}
private Intent pressButtonAndCaptureActivityStartIntent(int buttonViewId) {
pressButton(buttonViewId);
return TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
}
protected Intent pressMiddleButtonAndCaptureActivityStartIntent() {
return pressButtonAndCaptureActivityStartIntent(R.id.button_middle);
}
protected Intent pressRightButtonAndCaptureActivityStartIntent() {
return pressButtonAndCaptureActivityStartIntent(R.id.button_right);
}
protected void assertIntentForClassInTargetPackage(Class<?> expectedClass, Intent intent) {
assertEquals(
new ComponentName(
getInstrumentation().getTargetContext(),
expectedClass),
intent.getComponent());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/wizard/WizardPageActivityTestBase.java | Java | asf20 | 4,456 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.PasscodeGenerator.Signer;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import junit.framework.TestCase;
/**
* Unit test for {@link PasscodeGenerator}
* @author sarvar@google.com (Sarvar )
*/
public class PasscodeGeneratorTest extends TestCase {
private byte[] KEYBYTES1;
private byte[] KEYBYTES2;
private Mac mac1;
private Mac mac2;
private PasscodeGenerator passcodeGenerator1;
private PasscodeGenerator passcodeGenerator2;
private Signer signer;
@Override
public void setUp() throws Exception {
KEYBYTES1 = Base32String.decode("7777777777777777");
KEYBYTES2 = Base32String.decode("22222222222222222");
mac1 = Mac.getInstance("HMACSHA1");
mac1.init(new SecretKeySpec(KEYBYTES1, ""));
mac2 = Mac.getInstance("HMACSHA1");
mac2.init(new SecretKeySpec(KEYBYTES2, ""));
passcodeGenerator1 = new PasscodeGenerator(mac1);
passcodeGenerator2 = new PasscodeGenerator(mac2);
signer = AccountDb.getSigningOracle("7777777777777777");
}
public void testGenerateResponseCodeLong() throws Exception {
// test with long
String response1Long = passcodeGenerator1.generateResponseCode(123456789123456789L);
assertTrue(passcodeGenerator1.verifyResponseCode(123456789123456789L, response1Long));
assertFalse(passcodeGenerator1.verifyResponseCode(123456789123456789L, "boguscode"));
// test with (long, null), response code should be same as with just long
String response1LongNull = passcodeGenerator1.generateResponseCode(123456789123456789L, null);
assertEquals(response1Long, response1LongNull);
// test with byte[] using base32 encoded representation of byte array created from 0L
String response1ByteArray =
passcodeGenerator1.generateResponseCode(Base32String.decode("AG3JWS5M2BPRK"));
assertEquals(response1Long, response1ByteArray);
// test Long with another key bytes.
String response2Long = passcodeGenerator2.generateResponseCode(123456789123456789L);
assertTrue(passcodeGenerator2.verifyResponseCode(123456789123456789L, response2Long));
}
public void testRegressionGenerateResponseCode() throws Exception {
// test with long
assertEquals("724477", passcodeGenerator1.generateResponseCode(0L));
assertEquals("815107", passcodeGenerator1.generateResponseCode(123456789123456789L));
// test with byte[] for 0L and then for 123456789123456789L
assertEquals("724477",
passcodeGenerator1.generateResponseCode(Base32String.decode("AAAAAAAAAAAAA")));
assertEquals("815107",
passcodeGenerator1.generateResponseCode(Base32String.decode("AG3JWS5M2BPRK")));
// test with long and byte[]
assertEquals("498157", passcodeGenerator1.generateResponseCode(
123456789123456789L, "challenge".getBytes("UTF-8")));
}
public void testVerifyTimeoutCode() throws Exception {
/* currentInterval is 1234 in this test.
* timeInterval, timeoutCode values around 1234.
* 1231, 422609
* 1232, 628381
* 1233, 083501
* 1234, 607007
* 1235, 972746
* 1236, 706552
* 1237, 342936
*/
// verify code and plus one interval and minus one interval timeout codes.
assertTrue(passcodeGenerator1.verifyTimeoutCode(1234, "607007"));
assertTrue(passcodeGenerator1.verifyTimeoutCode(1234, "972746")); // plus one
assertTrue(passcodeGenerator1.verifyTimeoutCode(1234, "083501")); // minus one
assertFalse(passcodeGenerator1.verifyTimeoutCode(1234, "628381")); // fail for minus two
// verify timeout with custom window of +/- 2 intervals
assertTrue(passcodeGenerator1.verifyTimeoutCode("607007", 1234, 2, 2));
assertTrue(passcodeGenerator1.verifyTimeoutCode("972746", 1234, 2, 2)); // plus one
assertTrue(passcodeGenerator1.verifyTimeoutCode("706552", 1234, 2, 2)); // plus two
assertTrue(passcodeGenerator1.verifyTimeoutCode("083501", 1234, 2, 2)); // minus one
assertTrue(passcodeGenerator1.verifyTimeoutCode("628381", 1234, 2, 2)); // minus two
assertFalse(passcodeGenerator1.verifyTimeoutCode("000000", 1234, 2, 2)); // fail for wrong code
assertFalse(passcodeGenerator1.verifyTimeoutCode("342936", 1234, 2, 2)); // fail for plus three
// verify timeout with custom window of +1 and -2 intervals
assertTrue(passcodeGenerator1.verifyTimeoutCode("607007", 1234, 1, 2));
assertTrue(passcodeGenerator1.verifyTimeoutCode("972746", 1234, 1, 2)); // plus one
assertTrue(passcodeGenerator1.verifyTimeoutCode("083501", 1234, 1, 2)); // minus one
assertTrue(passcodeGenerator1.verifyTimeoutCode("628381", 1234, 1, 2)); // minus two
assertFalse(passcodeGenerator1.verifyTimeoutCode("706552", 1234, 1, 2)); // fail for plus two
assertFalse(passcodeGenerator1.verifyTimeoutCode("342936", 1234, 1, 2)); // fail for plus three
assertFalse(passcodeGenerator1.verifyTimeoutCode("000000", 1234, 1, 2)); // fail for wrong code
// verify timeout with custom window of 0 and -0 intervals
assertTrue(passcodeGenerator1.verifyTimeoutCode("607007", 1234, 0, 0)); // pass for current
assertFalse(passcodeGenerator1.verifyTimeoutCode("972746", 1234, 0, 0)); // fail for plus one
assertFalse(passcodeGenerator1.verifyTimeoutCode("083501", 1234, 0, 0)); // fail for minus one
}
public void testMacAndSignEquivalence() throws Exception {
String codeFromMac = passcodeGenerator1.generateResponseCode(0L);
String codeFromSigning = new PasscodeGenerator(signer, 6).generateResponseCode(0L);
assertEquals(codeFromMac, codeFromSigning);
String codeFromSigning2 = new PasscodeGenerator(signer, 6).generateResponseCode(1L);
assertFalse(codeFromSigning.equals(codeFromSigning2));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/PasscodeGeneratorTest.java | Java | asf20 | 6,501 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
import java.util.concurrent.Executor;
/**
* {@link Executor} that invokes the provided {@link Runnable} instances immediately on the thread
* invoking its {@code execute} method.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class RunImmediatelyOnCallingThreadExecutor implements Executor {
@Override
public void execute(Runnable command) {
command.run();
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/RunImmediatelyOnCallingThreadExecutor.java | Java | asf20 | 1,052 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.timesync;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import android.test.MoreAsserts;
import junit.framework.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicHeader;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.io.IOException;
import java.util.Arrays;
/**
* Unit tests for {@link NetworkTimeProvider}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class NetworkTimeProviderTest extends TestCase {
@Mock private HttpClient mMockHttpClient;
private NetworkTimeProvider mProvider;
@Override
protected void setUp() throws Exception {
super.setUp();
initMocks(this);
mProvider = new NetworkTimeProvider(mMockHttpClient);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testRequest() throws Exception {
withHttpRequestThrowing(new IOException("arbitrary"));
try {
mProvider.getNetworkTime();
} catch (Exception expected) {}
ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);
verify(mMockHttpClient).execute(requestCaptor.capture());
HttpUriRequest request = requestCaptor.getValue();
assertEquals("HEAD", request.getMethod());
assertEquals("https://www.google.com", request.getURI().toString());
MoreAsserts.assertEmpty(Arrays.asList(request.getAllHeaders()));
}
public void testResponseWithValidDate() throws Exception {
withHttpRequestReturningDate("Tue, 05 Jun 2012 22:54:01 GMT");
assertEquals(1338936841000L, mProvider.getNetworkTime());
}
public void testResponseWithMissingDate() throws Exception {
withHttpRequestReturningDate(null);
try {
mProvider.getNetworkTime();
fail();
} catch (IOException expected) {}
}
public void testResponseWithMalformedDate() throws Exception {
withHttpRequestReturningDate("Tue, 05 Jun 2012 22:54:01 Unknown");
try {
mProvider.getNetworkTime();
fail();
} catch (IOException expected) {}
}
public void testRequestThrowsExceptions() throws Exception {
withHttpRequestThrowing(new IOException(""));
try {
mProvider.getNetworkTime();
fail();
} catch (IOException expected) {}
withHttpRequestThrowing(new ClientProtocolException());
try {
mProvider.getNetworkTime();
fail();
} catch (IOException expected) {}
}
private void withHttpRequestThrowing(Exception exception) throws IOException {
doThrow(exception).when(mMockHttpClient).execute(Mockito.<HttpUriRequest>anyObject());
}
private void withHttpRequestReturningDate(String dateHeaderValue) throws IOException {
HttpResponse mockResponse = mock(HttpResponse.class);
if (dateHeaderValue != null) {
doReturn(new BasicHeader("Date", dateHeaderValue)).when(mockResponse).getLastHeader("Date");
}
doReturn(mockResponse).when(mMockHttpClient).execute(Mockito.<HttpUriRequest>anyObject());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/timesync/NetworkTimeProviderTest.java | Java | asf20 | 4,004 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.timesync;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.MockitoAnnotations.initMocks;
import com.google.android.apps.authenticator.RunImmediatelyOnCallingThreadExecutor;
import com.google.android.apps.authenticator.TotpClock;
import com.google.android.apps.authenticator.Utilities;
import junit.framework.TestCase;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import java.io.IOException;
import java.util.concurrent.Executor;
/**
* Unit tests for {@link SyncNowController}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SyncNowControllerTest extends TestCase {
@Mock private NetworkTimeProvider mMockNetworkTimeProvider;
@Mock private TotpClock mMockTotpClock;
@Mock private SyncNowController.Presenter mMockPresenter;
private Executor mBackgroundExecutor;
private Executor mCallbackExecutor;
private SyncNowController mController;
@Override
protected void setUp() throws Exception {
super.setUp();
initMocks(this);
// By default, configure the controller to invoke its background operations on the calling
// thread so that tests do not depend on other threads (especially Looper threads) and are
// easier to read due to lack of concurrency complications.
withImmediateExecutors();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testAdjustmentMade() throws Exception {
withTotpClockTimeCorrectionMinutes(7);
withNetworkTimeProviderReturningMillis(
System.currentTimeMillis() + 3 * Utilities.MINUTE_IN_MILLIS);
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.TIME_CORRECTED, verifyPresenterOnDoneInvoked());
assertEquals(3, verifyTotpClockSetTimeCorrectionInvoked());
reset(mMockPresenter);
mController.detach(mMockPresenter);
verifyZeroInteractions(mMockPresenter);
}
public void testAdjustmentNotNeeded() throws Exception {
withTotpClockTimeCorrectionMinutes(-3);
withNetworkTimeProviderReturningMillis(
System.currentTimeMillis() - 3 * Utilities.MINUTE_IN_MILLIS);
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.TIME_ALREADY_CORRECT, verifyPresenterOnDoneInvoked());
verifyTotpClockSetTimeCorrectionNotInvoked();
}
public void testConnectivityError() throws Exception {
withNetworkTimeProviderThrowing(new IOException());
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.ERROR_CONNECTIVITY_ISSUE, verifyPresenterOnDoneInvoked());
verifyTotpClockSetTimeCorrectionNotInvoked();
}
public void testCancelledByUserBeforeBackgroundOperation() throws Exception {
withTotpClockTimeCorrectionMinutes(-7);
withNetworkTimeProviderReturningMillis(
System.currentTimeMillis() - 7 * Utilities.MINUTE_IN_MILLIS);
withBackgroundExecutorThatAbortsControllerBeforeExecuting();
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.CANCELLED_BY_USER, verifyPresenterOnDoneInvoked());
verifyTotpClockSetTimeCorrectionNotInvoked();
}
public void testCancelledByUserBeforeCallback() throws Exception {
withTotpClockTimeCorrectionMinutes(-7);
withNetworkTimeProviderReturningMillis(
System.currentTimeMillis() - 7 * Utilities.MINUTE_IN_MILLIS);
withCallbackExecutorThatAbortsControllerBeforeExecuting();
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.CANCELLED_BY_USER, verifyPresenterOnDoneInvoked());
verifyTotpClockSetTimeCorrectionNotInvoked();
}
public void testAttachToNewPresenter() throws Exception {
withTotpClockTimeCorrectionMinutes(7);
withNetworkTimeProviderReturningMillis(
System.currentTimeMillis() + 3 * Utilities.MINUTE_IN_MILLIS);
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.TIME_CORRECTED, verifyPresenterOnDoneInvoked());
assertEquals(3, verifyTotpClockSetTimeCorrectionInvoked());
reset(mMockTotpClock, mMockNetworkTimeProvider);
mMockPresenter = mock(SyncNowController.Presenter.class);
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.TIME_CORRECTED, verifyPresenterOnDoneInvoked());
verifyZeroInteractions(mMockTotpClock, mMockNetworkTimeProvider);
}
public void testDetachPresenterBeforeFinished() throws Exception {
withTotpClockTimeCorrectionMinutes(7);
withNetworkTimeProviderReturningMillis(
System.currentTimeMillis() + 3 * Utilities.MINUTE_IN_MILLIS);
withBackgroundExecutorThatDetachesPresenterBeforeExecuting();
createController();
mController.attach(mMockPresenter);
assertEquals(SyncNowController.Result.CANCELLED_BY_USER, verifyPresenterOnDoneInvoked());
verifyZeroInteractions(mMockTotpClock);
}
private void createController() {
mController = new SyncNowController(
mMockTotpClock,
mMockNetworkTimeProvider,
mBackgroundExecutor,
false,
mCallbackExecutor);
}
private void withNetworkTimeProviderReturningMillis(long timeMillis) throws IOException {
doReturn(timeMillis).when(mMockNetworkTimeProvider).getNetworkTime();
}
private void withNetworkTimeProviderThrowing(IOException exception) throws IOException {
doThrow(exception).when(mMockNetworkTimeProvider).getNetworkTime();
}
private void withTotpClockTimeCorrectionMinutes(int timeCorrectionMinutes) {
doReturn(timeCorrectionMinutes).when(mMockTotpClock).getTimeCorrectionMinutes();
}
private SyncNowController.Result verifyPresenterOnDoneInvoked() {
ArgumentCaptor<SyncNowController.Result> resultCaptor =
ArgumentCaptor.forClass(SyncNowController.Result.class);
verify(mMockPresenter).onDone(resultCaptor.capture());
return resultCaptor.getValue();
}
private void verifyTotpClockSetTimeCorrectionNotInvoked() {
verify(mMockTotpClock, never()).setTimeCorrectionMinutes(anyInt());
}
private int verifyTotpClockSetTimeCorrectionInvoked() {
ArgumentCaptor<Integer> resultCaptor = ArgumentCaptor.forClass(Integer.class);
verify(mMockTotpClock).setTimeCorrectionMinutes(resultCaptor.capture());
return resultCaptor.getValue();
}
private void withImmediateExecutors() {
mBackgroundExecutor = new RunImmediatelyOnCallingThreadExecutor();
mCallbackExecutor = new RunImmediatelyOnCallingThreadExecutor();
}
private void withBackgroundExecutorThatAbortsControllerBeforeExecuting() {
mBackgroundExecutor = new Executor() {
@Override
public void execute(Runnable command) {
mController.abort(mMockPresenter);
command.run();
}
};
}
private void withCallbackExecutorThatAbortsControllerBeforeExecuting() {
mCallbackExecutor = new Executor() {
@Override
public void execute(Runnable command) {
mController.abort(mMockPresenter);
command.run();
}
};
}
private void withBackgroundExecutorThatDetachesPresenterBeforeExecuting() {
mBackgroundExecutor = new Executor() {
@Override
public void execute(Runnable command) {
mController.detach(mMockPresenter);
command.run();
}
};
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/timesync/SyncNowControllerTest.java | Java | asf20 | 8,351 |
/*
* 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 com.google.android.apps.authenticator;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator.testability.StartActivityListener;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Looper;
import android.os.SystemClock;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.test.InstrumentationTestCase;
import android.test.TouchUtils;
import android.test.ViewAsserts;
import android.view.Gravity;
import android.view.View;
import android.view.ViewParent;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import junit.framework.Assert;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A class that offers various utility methods for writing tests.
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class TestUtilities {
public static final String APP_PACKAGE_NAME = "com.google.android.apps.authenticator2";
/**
* Timeout (milliseconds) when waiting for the results of a UI action performed by the code
* under test.
*/
public static final int UI_ACTION_EFFECT_TIMEOUT_MILLIS = 5000;
private TestUtilities() { }
public static void clickView(Instrumentation instr, final View view) {
instr.runOnMainSync(new Runnable() {
@Override
public void run() {
view.performClick();
}
});
// this shouldn't be needed but without it or sleep, there isn't time for view refresh, etc.
instr.waitForIdleSync();
}
public static void longClickView(Instrumentation instr, final View view) {
instr.runOnMainSync(new Runnable() {
@Override
public void run() {
view.performLongClick();
}
});
instr.waitForIdleSync();
}
/**
* Selects the item at the requested position in the Spinner.
*
* @return the selected item as string.
*/
public static String selectSpinnerItem(
Instrumentation instr, final Spinner spinner, final int position) {
instr.runOnMainSync(new Runnable() {
@Override
public void run() {
spinner.setSelection(position);
}
});
instr.waitForIdleSync();
return spinner.getSelectedItem().toString();
}
/**
* Sets the text of the provided {@link EditText} widget on the UI thread.
*
* @return the resulting text of the widget.
*/
public static String setText(Instrumentation instr, final EditText editText, final String text) {
instr.runOnMainSync(new Runnable() {
@Override
public void run() {
editText.setText(text);
}
});
instr.waitForIdleSync();
return editText.getText().toString();
}
/*
* Sends a string to a EditText box.
*
* @return the resulting string read from the editText - this should equal text.
*/
public static String enterText(
Instrumentation instr, final EditText editText, final String text) {
instr.runOnMainSync(new Runnable() {
@Override
public void run() {
editText.requestFocus();
}
});
// TODO(sarvar): decide on using touch mode and how to do it consistently. e.g.,
// the above could be replaced by "TouchUtils.tapView(this, editText);"
instr.sendStringSync(text);
return editText.getText().toString();
}
/**
* Taps the specified preference displayed by the provided Activity.
*/
public static void tapPreference(InstrumentationTestCase instrumentationTestCase,
PreferenceActivity activity, Preference preference) {
// IMPLEMENTATION NOTE: There's no obvious way to find out which View corresponds to the
// preference because the Preference list in the adapter is flattened, whereas the View
// hierarchy in the ListView is not.
// Thus, we go for the Reflection-based invocation of Preference.performClick() which is as
// close to the invocation stack of a normal tap as it gets.
// Only perform the click if the preference is in the adapter to catch cases where the
// preference is not part of the PreferenceActivity for some reason.
ListView listView = activity.getListView();
ListAdapter listAdapter = listView.getAdapter();
for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
if (listAdapter.getItem(i) == preference) {
invokePreferencePerformClickOnMainThread(
instrumentationTestCase.getInstrumentation(),
preference,
activity.getPreferenceScreen());
return;
}
}
throw new IllegalArgumentException("Preference " + preference + " not in list");
}
private static void invokePreferencePerformClickOnMainThread(
Instrumentation instrumentation,
final Preference preference,
final PreferenceScreen preferenceScreen) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
invokePreferencePerformClick(preference, preferenceScreen);
} else {
FutureTask<Void> task = new FutureTask<Void>(new Runnable() {
@Override
public void run() {
invokePreferencePerformClick(preference, preferenceScreen);
}
}, null);
instrumentation.runOnMainSync(task);
try {
task.get();
} catch (Exception e) {
throw new RuntimeException("Failed to click on preference on main thread", e);
}
}
}
private static void invokePreferencePerformClick(
Preference preference, PreferenceScreen preferenceScreen) {
try {
Method performClickMethod =
Preference.class.getDeclaredMethod("performClick", PreferenceScreen.class);
performClickMethod.setAccessible(true);
performClickMethod.invoke(preference, preferenceScreen);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Preference.performClickMethod method not found", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Preference.performClickMethod failed", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to access Preference.performClickMethod", e);
}
}
/**
* Waits until the window which contains the provided view has focus.
*/
public static void waitForWindowFocus(View view)
throws InterruptedException, TimeoutException {
long deadline = SystemClock.uptimeMillis() + UI_ACTION_EFFECT_TIMEOUT_MILLIS;
while (!view.hasWindowFocus()) {
long millisTillDeadline = deadline - SystemClock.uptimeMillis();
if (millisTillDeadline < 0) {
throw new TimeoutException("Timed out while waiting for window focus");
}
Thread.sleep(50);
}
}
/**
* Waits until the {@link Activity} is finishing.
*/
public static void waitForActivityFinishing(Activity activity)
throws InterruptedException, TimeoutException {
long deadline = SystemClock.uptimeMillis() + UI_ACTION_EFFECT_TIMEOUT_MILLIS;
while (!activity.isFinishing()) {
long millisTillDeadline = deadline - SystemClock.uptimeMillis();
if (millisTillDeadline < 0) {
throw new TimeoutException("Timed out while waiting for activity to start finishing");
}
Thread.sleep(50);
}
}
/**
* Invokes the {@link Activity}'s {@code onBackPressed()} on the UI thread and blocks (with
* a timeout) the calling thread until the invocation completes. If the calling thread is the UI
* thread, the {@code finish} is invoked directly and without a timeout.
*/
public static void invokeActivityOnBackPressedOnUiThread(final Activity activity)
throws InterruptedException, TimeoutException {
FutureTask<Void> finishTask = new FutureTask<Void>(new Runnable() {
@Override
public void run() {
activity.onBackPressed();
}
}, null);
activity.runOnUiThread(finishTask);
try {
finishTask.get(UI_ACTION_EFFECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw new RuntimeException("Activity.onBackPressed() failed", e);
}
}
/**
* Invokes the {@link Activity}'s {@code finish()} on the UI thread and blocks (with
* a timeout) the calling thread until the invocation completes. If the calling thread is the UI
* thread, the {@code finish} is invoked directly and without a timeout.
*/
public static void invokeFinishActivityOnUiThread(final Activity activity)
throws InterruptedException, TimeoutException {
FutureTask<Void> finishTask = new FutureTask<Void>(new Runnable() {
@Override
public void run() {
activity.finish();
}
}, null);
activity.runOnUiThread(finishTask);
try {
finishTask.get(UI_ACTION_EFFECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw new RuntimeException("Activity.finish() failed", e);
}
}
private static boolean isViewAndAllItsParentsVisible(View view) {
if (view.getVisibility() != View.VISIBLE) {
return false;
}
ViewParent parent = view.getParent();
if (!(parent instanceof View)) {
// This View is the root of the View hierarche, and it's visible (checked above)
return true;
}
// This View itself is actually visible only all of its parents are visible.
return isViewAndAllItsParentsVisible((View) parent);
}
private static boolean isViewOrAnyParentVisibilityGone(View view) {
if (view.getVisibility() == View.GONE) {
return true;
}
ViewParent parent = view.getParent();
if (!(parent instanceof View)) {
// This View is the root of the View hierarchy, and its visibility is not GONE (checked above)
return false;
}
// This View itself is actually visible only all of its parents are visible.
return isViewOrAnyParentVisibilityGone((View) parent);
}
/**
* Asserts that the provided {@link View} and all its parents are visible.
*/
public static void assertViewAndAllItsParentsVisible(View view) {
Assert.assertTrue(isViewAndAllItsParentsVisible(view));
}
/**
* Asserts that the provided {@link View} and all its parents are visible.
*/
public static void assertViewOrAnyParentVisibilityGone(View view) {
Assert.assertTrue(isViewOrAnyParentVisibilityGone(view));
}
/**
* Asserts that the provided {@link View} is on the screen and is visible (which means its parent
* and the parent of its parent and so forth are visible too).
*/
public static void assertViewVisibleOnScreen(View view) {
ViewAsserts.assertOnScreen(view.getRootView(), view);
assertViewAndAllItsParentsVisible(view);
}
/**
* Opens the options menu of the provided {@link Activity} and invokes the menu item with the
* provided ID.
*
* Note: This method cannot be invoked on the main thread.
*/
public static void openOptionsMenuAndInvokeItem(
Instrumentation instrumentation, final Activity activity, final int itemId) {
if (!instrumentation.invokeMenuActionSync(activity, itemId, 0)) {
throw new RuntimeException("Failed to invoke options menu item ID " + itemId);
}
instrumentation.waitForIdleSync();
}
/**
* Opens the context menu for the provided {@link View} and invokes the menu item with the
* provided ID.
*
* Note: This method cannot be invoked on the main thread.
*/
public static void openContextMenuAndInvokeItem(
Instrumentation instrumentation, final Activity activity, final View view, final int itemId) {
// IMPLEMENTATION NOTE: Instrumentation.invokeContextMenuAction would've been much simpler, but
// it doesn't work on ICS because its KEY_UP event times out.
FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() {
// Use performLongClick instead of showContextMenu to exercise more of the code path that
// is invoked when the user normally opens a context menu.
view.performLongClick();
return activity.getWindow().performContextMenuIdentifierAction(itemId, 0);
}
});
instrumentation.runOnMainSync(task);
try {
if (!task.get()) {
throw new RuntimeException("Failed to invoke context menu item with ID " + itemId);
}
} catch (Exception e) {
throw new RuntimeException("Failed to open context menu and select a menu item", e);
}
instrumentation.waitForIdleSync();
}
/**
* Asserts that the provided {@link Activity} displayed a dialog with the provided ID at some
* point in the past. Note that this does not necessarily mean that the dialog is still being
* displayed.
*
* <p>
* <b>Note:</b> this method resets the "was displayed" state of the dialog. This means that a
* consecutive invocation of this method for the same dialog ID will fail unless the dialog
* was displayed again prior to the invocation of this method.
*/
public static void assertDialogWasDisplayed(Activity activity, int dialogId) {
// IMPLEMENTATION NOTE: This code below relies on the fact that, if a dialog with the ID was
// every displayed, then dismissDialog will succeed, whereas if the dialog with the ID has
// never been shown, then dismissDialog throws an IllegalArgumentException.
try {
activity.dismissDialog(dialogId);
// Reset the "was displayed" state
activity.removeDialog(dialogId);
} catch (IllegalArgumentException e) {
Assert.fail("No dialog with ID " + dialogId + " was ever displayed");
}
}
/**
* Taps the positive button of a currently displayed dialog. This method assumes that a button
* of the dialog is currently selected.
*
* @see #tapDialogNegativeButton(InstrumentationTestCase)
*/
public static void tapDialogNegativeButton(InstrumentationTestCase testCase) {
// The order of the buttons is reversed from ICS onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
testCase.sendKeys("DPAD_RIGHT DPAD_CENTER");
} else {
testCase.sendKeys("DPAD_LEFT DPAD_CENTER");
}
}
/**
* Taps the negative button of a currently displayed dialog. This method assumes that a button
* of the dialog is currently selected.
*
* @see #tapDialogNegativeButton(InstrumentationTestCase)
*/
public static void tapDialogPositiveButton(InstrumentationTestCase testCase) {
// The order of the buttons is reversed from ICS onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
testCase.sendKeys("DPAD_LEFT DPAD_CENTER");
} else {
testCase.sendKeys("DPAD_RIGHT DPAD_CENTER");
}
}
/**
* Taps the negative button of a currently displayed 3 button dialog. This method assumes
* that a button of the dialog is currently selected.
*/
public static void tapNegativeButtonIn3ButtonDialog(InstrumentationTestCase testCase) {
// The order of the buttons is reversed from ICS onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
testCase.sendKeys("DPAD_RIGHT DPAD_RIGHT DPAD_CENTER");
} else {
testCase.sendKeys("DPAD_LEFT DPAD_LEFT DPAD_CENTER");
}
}
/**
* Taps the neutral button of a currently displayed 3 button dialog. This method assumes
* that a button of the dialog is currently selected.
*/
public static void tapNeutralButtonIn3ButtonDialog(InstrumentationTestCase testCase) {
// The order of the buttons is reversed from ICS onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
testCase.sendKeys("DPAD_RIGHT DPAD_CENTER");
} else {
testCase.sendKeys("DPAD_RIGHT DPAD_CENTER");
}
}
/**
* Taps the positive button of a currently displayed 3 button dialog. This method assumes
* that a button of the dialog is currently selected.
*/
public static void tapPositiveButtonIn3ButtonDialog(InstrumentationTestCase testCase) {
// The order of the buttons is reversed from ICS onwards
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
testCase.sendKeys("DPAD_LEFT DPAD_LEFT DPAD_CENTER");
} else {
testCase.sendKeys("DPAD_RIGHT DPAD_RIGHT DPAD_CENTER");
}
}
/**
* Configures the {@link DependencyInjector} with a {@link StartActivityListener} that prevents
* activity launches.
*/
public static void withLaunchPreventingStartActivityListenerInDependencyResolver() {
StartActivityListener mockListener = Mockito.mock(StartActivityListener.class);
doReturn(true).when(mockListener).onStartActivityInvoked(
Mockito.<Context>anyObject(), Mockito.<Intent>anyObject());
DependencyInjector.setStartActivityListener(mockListener);
}
/**
* Verifies (with a timeout of {@link #UI_ACTION_EFFECT_TIMEOUT_MILLIS}) that an activity launch
* has been attempted and returns the {@link Intent} with which the attempt occurred.
*
* <p><b>NOTE: This method assumes that the {@link DependencyInjector} was configured
* using {@link #withLaunchPreventingStartActivityListenerInDependencyResolver()}.</b>
*/
public static Intent verifyWithTimeoutThatStartActivityAttemptedExactlyOnce() {
StartActivityListener mockListener = DependencyInjector.getStartActivityListener();
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mockListener, timeout(UI_ACTION_EFFECT_TIMEOUT_MILLIS))
.onStartActivityInvoked(Mockito.<Context>anyObject(), intentCaptor.capture());
return intentCaptor.getValue();
}
public static void assertLessThanOrEquals(long expected, long actual) {
if (actual > expected) {
Assert.fail(actual + " > " + expected);
}
}
/*
* Returns the x and y coordinates of center of view in pixels.
*/
public static Point getCenterOfViewOnScreen(
InstrumentationTestCase instr, View view) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int width = view.getWidth();
int height = view.getHeight();
final int center_x = location[0] + width / 2;
final int center_y = location[1] + height / 2;
return new Point(center_x, center_y);
}
/*
* returns the pixel value at the right side end of the view.
*/
public static int getRightXofViewOnScreen(View view) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int width = view.getWidth();
return location[0] + width;
}
/*
* returns the pixel value at the left side end of the view.
*/
public static int getLeftXofViewOnScreen(View view) {
int[] location = new int[2];
view.getLocationOnScreen(location);
return location[0];
}
/*
* Drags from the center of the view to the toX value.
* This methods exists in TouchUtil, however, it has a bug which causes it to work
* while dragging on the left side, but not on the right side, hence, we
* had to recreate it here.
*/
public static int dragViewToX(InstrumentationTestCase test, View v, int gravity, int toX) {
if (gravity != Gravity.CENTER) {
throw new IllegalArgumentException("Can only handle Gravity.CENTER.");
}
Point point = getCenterOfViewOnScreen(test, v);
final int fromX = point.x;
final int fromY = point.y;
int deltaX = Math.abs(fromX - toX);
TouchUtils.drag(test, fromX, toX, fromY, fromY, deltaX);
return deltaX;
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/TestUtilities.java | Java | asf20 | 20,683 |
/*
* 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 com.google.android.apps.authenticator;
import junit.framework.TestCase;
/**
* Unit tests for {@link Preconditions}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class PreconditionsTest extends TestCase {
public void testCheckNotNullSingleArg() {
Object reference = "test";
assertSame(reference, Preconditions.checkNotNull(reference));
try {
Preconditions.checkNotNull(null);
fail("NullPointerException should have been thrown");
} catch (NullPointerException e) {
// Expected
}
}
public void testCheckArgumentSingleArg() {
Preconditions.checkArgument(true);
try {
Preconditions.checkArgument(false);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException e) {
// Expected
}
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/PreconditionsTest.java | Java | asf20 | 1,441 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.PasscodeGenerator.Signer;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
import java.util.ArrayList;
import java.util.Collection;
/**
* Unit tests for {@link AccountDb}.
* @author sarvar@google.com (Sarvar Patel)
*
* TestCases belonging to the same test suite that are run simultaneously may interfere
* with each other because AccountDb instances in this class point to the same underlying database.
* For the time being this is not an issue since tests for android are run sequentially.
*/
public class AccountDbTest extends AndroidTestCase {
private static final String MESSAGE = "hello";
private static final String SIGNATURE = "2GOH22N7HTHRAC3C4IY24TWH6FEFEOZ7";
private static final String SECRET = "7777777777777777"; // 16 sevens
private static final String SECRET2 = "2222222222222222"; // 16 twos
private Collection<String> result = new ArrayList<String>();
private AccountDb accountDb;
@Override
public void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getContext());
accountDb = DependencyInjector.getAccountDb();
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
private void addSomeRecords() {
accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null);
accountDb.update("amywinehouse@aol.com", SECRET2, "amywinehouse@aol.com", OtpType.TOTP, null);
accountDb.update("maryweiss@yahoo.com", SECRET, "maryweiss@yahoo.com", OtpType.HOTP, 0);
}
public void testNoRecords() throws Exception {
assertEquals(0, accountDb.getNames(result));
assertEquals(0, result.size());
assertEquals(false, accountDb.nameExists("johndoe@gmail.com"));
assertEquals(null, accountDb.getSecret("johndoe@gmail.com"));
}
public void testGetNames() throws Exception {
addSomeRecords();
accountDb.getNames(result);
MoreAsserts.assertContentsInAnyOrder(result,
"johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com");
// check nameExists()
assertTrue(accountDb.nameExists("johndoe@gmail.com"));
assertTrue(accountDb.nameExists("amywinehouse@aol.com"));
assertTrue(accountDb.nameExists("maryweiss@yahoo.com"));
assertFalse(accountDb.nameExists("marywinehouse@aol.com")); // non-existent email.
}
public void testGetSecret() throws Exception {
addSomeRecords();
assertEquals(SECRET, accountDb.getSecret("johndoe@gmail.com"));
assertEquals(SECRET2, accountDb.getSecret("amywinehouse@aol.com"));
assertEquals(null, accountDb.getSecret("marywinehouse@aol.com")); // non-existent email.
}
public void testGetAndIncrementCounter() throws Exception {
addSomeRecords();
assertEquals(0, (int) accountDb.getCounter("maryweiss@yahoo.com"));
accountDb.incrementCounter("maryweiss@yahoo.com");
assertEquals(1, (int) accountDb.getCounter("maryweiss@yahoo.com"));
assertEquals(null, accountDb.getCounter("marywinehouse@yahoo.com")); // non-existent record.
assertEquals(0, (int) accountDb.getCounter("amywinehouse@aol.com")); // TOTP record
}
public void testGetAndSetType() throws Exception {
addSomeRecords();
assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP));
assertTrue(accountDb.getType("maryweiss@yahoo.com").equals(OtpType.HOTP));
assertFalse(accountDb.getType("amywinehouse@aol.com").equals(OtpType.HOTP));
accountDb.setType("johndoe@gmail.com", OtpType.HOTP);
assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.HOTP));
// check that the counter retains its values.
assertEquals(0, (int) accountDb.getCounter("johndoe@gmail.com"));
// check that it can be reset to original value
accountDb.setType("johndoe@gmail.com", OtpType.TOTP);
assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP));
}
public void testGetAndSetAccountType() throws Exception {
addSomeRecords();
assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP));
assertTrue(accountDb.getType("maryweiss@yahoo.com").equals(OtpType.HOTP));
assertFalse(accountDb.getType("amywinehouse@aol.com").equals(OtpType.HOTP));
accountDb.setType("johndoe@gmail.com", OtpType.HOTP);
assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.HOTP));
// check that the counter retains its values.
assertEquals(0, (int) accountDb.getCounter("johndoe@gmail.com"));
// check that it can be reset to original value
accountDb.setType("johndoe@gmail.com", OtpType.TOTP);
assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP));
}
public void testDelete() throws Exception {
addSomeRecords();
accountDb.delete("johndoe@gmail.com");
assertEquals(2, accountDb.getNames(result));
assertFalse(accountDb.nameExists("johndoe@gmail.com"));
// re-add johndoe.
accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null);
assertTrue(accountDb.nameExists("johndoe@gmail.com"));
}
public void testUpdate() throws Exception {
addSomeRecords();
// check updates with existing records - that it doesn't increase the records.
accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null);
accountDb.getNames(result);
MoreAsserts.assertContentsInAnyOrder(result,
"johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com");
// add new record.
accountDb.update("johndoenew@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null);
result.clear();
accountDb.getNames(result);
MoreAsserts.assertContentsInAnyOrder(result,
"johndoenew@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com");
// re-update with the original name
accountDb.update("johndoe@gmail.com", SECRET, "johndoenew@gmail.com", OtpType.TOTP, null);
result.clear();
accountDb.getNames(result);
MoreAsserts.assertContentsInAnyOrder(result,
"johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com");
}
public void testIsGoogleAccount() {
accountDb.update("1@b.c", SECRET, "1@b.c", OtpType.TOTP, null, true);
accountDb.update("2@gmail.com", SECRET, "2@gmail.com", OtpType.TOTP, null);
accountDb.update("3@google.com", SECRET, "3@google.com", OtpType.TOTP, null);
accountDb.update("4", SECRET, "4", OtpType.HOTP, 3, true);
accountDb.update("5@yahoo.co.uk", SECRET, "5@yahoo.co.uk", OtpType.TOTP, null);
accountDb.update("gmail.com", SECRET, "gmail.com", OtpType.TOTP, null);
accountDb.update(
"Google Internal 2Factor", SECRET, "Google Internal 2Factor", OtpType.HOTP, null);
assertTrue(accountDb.isGoogleAccount("1@b.c"));
assertTrue(accountDb.isGoogleAccount("2@gmail.com"));
assertTrue(accountDb.isGoogleAccount("3@google.com"));
assertTrue(accountDb.isGoogleAccount("4"));
assertFalse(accountDb.isGoogleAccount("5@yahoo.co.uk"));
assertFalse(accountDb.isGoogleAccount("gmail.com"));
assertTrue(accountDb.isGoogleAccount("Google Internal 2Factor"));
assertFalse(accountDb.isGoogleAccount("non-existent account"));
}
public void testUpdateWithoutSourceValuePreservesSourceValue() {
accountDb.update("a@b.c", SECRET, "a@b.c", OtpType.TOTP, null, true);
accountDb.update("test@gmail.com", SECRET, "test@gmail.com", OtpType.TOTP, null);
assertTrue(accountDb.isGoogleAccount("a@b.c"));
assertTrue(accountDb.isGoogleAccount("test@gmail.com"));
accountDb.update("b@a.c", SECRET, "a@b.c", OtpType.TOTP, null);
accountDb.update("test@yahoo.com", SECRET, "test@gmail.com", OtpType.TOTP, null);
assertTrue(accountDb.isGoogleAccount("b@a.c"));
assertFalse(accountDb.isGoogleAccount("test@yahoo.com"));
}
public void testConstruct_whenNoDatabase() {
deleteAccountDb();
accountDb = DependencyInjector.getAccountDb();
}
public void testConstruct_whenDatabaseWithoutProviderColumn() {
deleteAccountDb();
SQLiteDatabase database =
DependencyInjector.getContext().openOrCreateDatabase(
AccountDb.PATH, Context.MODE_PRIVATE, null);
database.execSQL("CREATE TABLE " + AccountDb.TABLE_NAME + " (first INTEGER)");
MoreAsserts.assertContentsInAnyOrder(
AccountDb.listTableColumnNamesLowerCase(database, AccountDb.TABLE_NAME),
"first");
database.close();
database = null;
accountDb = DependencyInjector.getAccountDb();
MoreAsserts.assertContentsInAnyOrder(
AccountDb.listTableColumnNamesLowerCase(accountDb.mDatabase, AccountDb.TABLE_NAME),
"first", AccountDb.PROVIDER_COLUMN);
}
private void deleteAccountDb() {
if (accountDb != null) {
accountDb.close();
accountDb = null;
}
DependencyInjector.setAccountDb(null);
assertTrue(DependencyInjector.getContext().deleteDatabase(AccountDb.PATH));
}
public void testSigningOracle() throws Exception {
Signer signer = AccountDb.getSigningOracle(SECRET);
assertEquals(SIGNATURE, Base32String.encode(signer.sign(MESSAGE.getBytes())));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/AccountDbTest.java | Java | asf20 | 10,052 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
import android.os.Build;
import android.os.Bundle;
import android.test.InstrumentationTestRunner;
import org.mockito.Mockito;
/**
* {@link InstrumentationTestRunner} that makes it possible to use Mockito on Eclair
* without changing any other code. The runner by the framework is created before any tests are run
* and thus has the opportunity to fix Mockito on Eclair.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class MockitoWorkaroundForEclairInstrumentationTestRunner
extends InstrumentationTestRunner {
@Override
public void onCreate(Bundle arguments) {
// This is a workaround for Eclair for http://code.google.com/p/mockito/issues/detail?id=354.
// Mockito loads the Android-specific MockMaker (provided by DexMaker) using the current
// thread's context ClassLoader. On Eclair this ClassLoader is set to the system ClassLoader
// which doesn't know anything about this app (which includes DexMaker). The workaround is to
// use the app's ClassLoader.
// TODO(klyubin): Remove this workaround (and most likely this whole class) once Eclair is no
// longer supported.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
// Make Mockito look up a MockMaker using the app's ClassLoader, by asking Mockito to create
// a mock.
ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Mockito.class.getClassLoader());
Mockito.mock(Runnable.class);
Thread.currentThread().setContextClassLoader(originalContextClassLoader);
}
super.onCreate(arguments);
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/MockitoWorkaroundForEclairInstrumentationTestRunner.java | Java | asf20 | 2,313 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.MoreAsserts;
import android.test.ViewAsserts;
import android.view.View;
import android.widget.TextView;
/**
* Unit tests for {@link CheckCodeActivity}.
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class CheckCodeActivityTest extends ActivityInstrumentationTestCase2<CheckCodeActivity> {
public CheckCodeActivityTest() {
super(TestUtilities.APP_PACKAGE_NAME, CheckCodeActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
AccountDb accountDb = DependencyInjector.getAccountDb();
accountDb.update(
"johndoe@gmail.com", "7777777777777777", "johndoe@gmail.com", OtpType.TOTP, null);
accountDb.update(
"shadowmorton@aol.com", "2222222222222222", "shadowmorton@aol.com", OtpType.HOTP, null);
accountDb.update(
"maryweiss@yahoo.com", "7777777777777777", "maryweiss@yahoo.com", OtpType.HOTP, 0);
setActivityInitialTouchMode(false);
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testWithTimeBasedAccount() {
// For TOTP accounts, AuthenticatorActivity never calls CheckCodeActivity, however, the
// code exists and we check its behavior here.
setActivityIntent(new Intent(Intent.ACTION_MAIN).putExtra("user", "johndoe@gmail.com"));
CheckCodeActivity mActivity = getActivity();
TextView mCodeTextView = (TextView) mActivity.findViewById(R.id.code_value);
TextView mCheckCodeTextView = (TextView) mActivity.findViewById(R.id.check_code);
TextView mCounterValue = (TextView) mActivity.findViewById(R.id.counter_value);
// check existence of fields
assertNotNull(mActivity);
assertNotNull(mCheckCodeTextView);
assertNotNull(mCodeTextView);
assertNotNull(mCounterValue);
// check visibility
View origin = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(origin, mCheckCodeTextView);
ViewAsserts.assertOnScreen(origin, mCodeTextView);
assertTrue(mActivity.findViewById(R.id.code_area).isShown()); // layout area
assertFalse(mCounterValue.isShown()); // TOTP has no counter value to show.
assertFalse(mActivity.findViewById(R.id.counter_area).isShown()); // layout area
// check values
MoreAsserts.assertContainsRegex("johndoe@gmail.com", mCheckCodeTextView.getText().toString());
assertEquals("724477", mCodeTextView.getText().toString());
}
public void testWithCounterBasedAccount() {
setActivityIntent(new Intent(Intent.ACTION_MAIN).putExtra("user", "maryweiss@yahoo.com"));
CheckCodeActivity mActivity = getActivity();
TextView mCodeTextView = (TextView) mActivity.findViewById(R.id.code_value);
TextView mCheckCodeTextView = (TextView) mActivity.findViewById(R.id.check_code);
TextView mCounterValue = (TextView) mActivity.findViewById(R.id.counter_value);
// check existence of fields
assertNotNull(mCheckCodeTextView);
assertNotNull(mCodeTextView);
assertNotNull(mCounterValue);
// check visibility
View origin = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(origin, mCheckCodeTextView);
ViewAsserts.assertOnScreen(origin, mCodeTextView);
ViewAsserts.assertOnScreen(origin, mCounterValue);
assertTrue(mActivity.findViewById(R.id.code_area).isShown()); // layout area
assertTrue(mActivity.findViewById(R.id.counter_area).isShown()); // layout area
// check values
MoreAsserts.assertContainsRegex("maryweiss@yahoo.com", mCheckCodeTextView.getText().toString());
assertEquals("724477", mCodeTextView.getText().toString());
assertEquals("0", mCounterValue.getText().toString());
}
public void testWithAnotherCounterBasedAccount() {
setActivityIntent(new Intent(Intent.ACTION_MAIN).putExtra("user", "shadowmorton@aol.com"));
CheckCodeActivity mActivity = getActivity();
TextView mCodeTextView = (TextView) mActivity.findViewById(R.id.code_value);
TextView mCheckCodeTextView = (TextView) mActivity.findViewById(R.id.check_code);
MoreAsserts.assertContainsRegex(
"shadowmorton@aol.com", mCheckCodeTextView.getText().toString());
assertEquals("086620", mCodeTextView.getText().toString());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/CheckCodeActivityTest.java | Java | asf20 | 5,287 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.content.ComponentName;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
/**
* Unit tests for {@link AddOtherAccountActivity}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class AddOtherAccountActivityTest
extends ActivityInstrumentationTestCase2<AddOtherAccountActivity> {
public AddOtherAccountActivityTest() {
super(TestUtilities.APP_PACKAGE_NAME, AddOtherAccountActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver();
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testScanBarcode() throws Exception {
TestUtilities.clickView(getInstrumentation(), getActivity().findViewById(R.id.scan_barcode));
Intent actualIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
Intent expectedIntent = AuthenticatorActivity.getLaunchIntentActionScanBarcode(getActivity());
assertEquals(expectedIntent.getAction(), actualIntent.getAction());
assertEquals(expectedIntent.getComponent(), actualIntent.getComponent());
}
public void testManuallyAddAccount() throws Exception {
TestUtilities.clickView(
getInstrumentation(), getActivity().findViewById(R.id.manually_add_account));
Intent actualIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
assertEquals(
new ComponentName(getActivity(), EnterKeyActivity.class),
actualIntent.getComponent());
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/AddOtherAccountActivityTest.java | Java | asf20 | 2,534 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.content.Intent;
import android.preference.Preference;
import android.test.ActivityInstrumentationTestCase2;
/**
* Unit tests for {@link SettingsAboutActivity}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SettingsAboutActivityTest
extends ActivityInstrumentationTestCase2<SettingsAboutActivity> {
public SettingsAboutActivityTest() {
super(TestUtilities.APP_PACKAGE_NAME, SettingsAboutActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver();
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testVersionTakenFromPackageVersion() throws Exception {
Preference preference = getActivity().findPreference("version");
String expectedVersion =
getInstrumentation().getTargetContext().getPackageManager().getPackageInfo(
getActivity().getPackageName(), 0).versionName;
assertEquals(expectedVersion, preference.getSummary());
}
public void testOpenSourcePreferenceOpensUrl() throws Exception {
Intent intent = tapOnPreferenceAndCatchFiredIntent("opensource");
assertDefaultViewActionIntent(
getInstrumentation().getTargetContext().getString(R.string.opensource_page_url),
intent);
}
public void testTermsOfServicePreferenceOpensUrl() throws Exception {
Intent intent = tapOnPreferenceAndCatchFiredIntent("terms");
assertDefaultViewActionIntent(
getInstrumentation().getTargetContext().getString(R.string.terms_page_url),
intent);
}
public void testPrivacyPolicyPreferenceOpensUrl() throws Exception {
Intent intent = tapOnPreferenceAndCatchFiredIntent("privacy");
assertDefaultViewActionIntent(
getInstrumentation().getTargetContext().getString(R.string.privacy_page_url),
intent);
}
private static void assertDefaultViewActionIntent(String expectedData, Intent intent) {
assertEquals("android.intent.action.VIEW", intent.getAction());
assertEquals(expectedData, intent.getDataString());
}
private Intent tapOnPreferenceAndCatchFiredIntent(String preferenceKey) {
TestUtilities.tapPreference(this, getActivity(), getActivity().findPreference(preferenceKey));
return TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce();
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/SettingsAboutActivityTest.java | Java | asf20 | 3,325 |
/*
* 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 com.google.android.apps.authenticator;
import junit.framework.TestCase;
/**
* Unit tests for {@link TotpCounter}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class TotpCounterTest extends TestCase {
public void testConstruct_withInvalidDuration() {
try {
new TotpCounter(0);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException e) {
// Expected
}
try {
new TotpCounter(-3);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException e) {
// Expected
}
}
public void testConstruct_withNegativeStartTime() {
try {
new TotpCounter(1, -3);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException e) {
// Expected
}
}
public void testConstruct_withDurationAndStartTime() {
TotpCounter counter = new TotpCounter(3, 7);
assertEquals(3, counter.getTimeStep());
assertEquals(7, counter.getStartTime());
}
public void testConstruct_withDefaultStartTime() {
TotpCounter counter = new TotpCounter(11);
assertEquals(11, counter.getTimeStep());
assertEquals(0, counter.getStartTime());
}
public void testGetValueAtTime_withNegativeTime() {
TotpCounter counter = new TotpCounter(3);
try {
counter.getValueAtTime(-7);
fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException e) {
// Expected
}
}
public void testGetValueAtTime_withTimeBeforeStartTime() {
TotpCounter counter = new TotpCounter(3, 11);
assertEquals(-1, counter.getValueAtTime(10));
}
public void testGetValueAtTime() {
TotpCounter counter = new TotpCounter(7, 123);
assertEquals(-18, counter.getValueAtTime(0));
assertEquals(-2, counter.getValueAtTime(115));
assertEquals(-1, counter.getValueAtTime(116));
assertEquals(-1, counter.getValueAtTime(117));
assertEquals(-1, counter.getValueAtTime(122));
assertEquals(0, counter.getValueAtTime(123));
assertEquals(0, counter.getValueAtTime(124));
assertEquals(0, counter.getValueAtTime(129));
assertEquals(1, counter.getValueAtTime(130));
assertEquals(1, counter.getValueAtTime(131));
assertEquals(100, counter.getValueAtTime(823));
assertEquals(10000000000L, counter.getValueAtTime(70000000123L));
}
public void testGetValueStartTime() {
TotpCounter counter = new TotpCounter(7, 123);
assertEquals(-577, counter.getValueStartTime(-100));
assertEquals(116, counter.getValueStartTime(-1));
assertEquals(123, counter.getValueStartTime(0));
assertEquals(130, counter.getValueStartTime(1));
assertEquals(137, counter.getValueStartTime(2));
assertEquals(823, counter.getValueStartTime(100));
assertEquals(70000000123L, counter.getValueStartTime(10000000000L));
}
public void testValueIncreasesByOneEveryTimeStep() {
TotpCounter counter = new TotpCounter(7, 123);
assertValueIncreasesByOneEveryTimeStep(counter, 11, 500);
assertValueIncreasesByOneEveryTimeStep(counter, Long.MAX_VALUE - 1234567, 500);
}
public void testValueStartTimeInRangeOverTime() {
TotpCounter counter = new TotpCounter(11, 123);
assertValueStartTimeInRangeOverTime(counter, 0, 500);
assertValueStartTimeInRangeOverTime(counter, Long.MAX_VALUE - 1234567, 500);
}
private static void assertValueIncreasesByOneEveryTimeStep(
TotpCounter counter, long startTime, long duration) {
long previousValue = counter.getValueAtTime(startTime);
long previousValueStartTime = counter.getValueStartTime(previousValue);
// Adjust the start time so that it starts when the counter first assumes the current value
long startTimeAdjustment = startTime - previousValueStartTime;
startTime -= startTimeAdjustment;
duration += startTimeAdjustment;
for (long time = startTime, endTime = startTime + duration; time <= endTime; time++) {
long value = counter.getValueAtTime(time);
if (value != previousValue) {
if (value == previousValue + 1) {
long timeSincePreviousValueStart = time - previousValueStartTime;
if (timeSincePreviousValueStart != counter.getTimeStep()) {
fail("Value incremented by 1 at the wrong time: " + time);
}
previousValue = value;
previousValueStartTime = time;
} else {
fail("Value changed by an unexpected amount " + (value - previousValue)
+ " at time " + time);
}
} else if ((time - previousValueStartTime) == counter.getTimeStep()) {
fail("Counter value did not change at time " + time);
}
}
}
/**
* Asserts that during the specified time interval the start time of each value from that
* interval is not in the future and also is no older than {@code timeStep - 1}.
*/
private static void assertValueStartTimeInRangeOverTime(
TotpCounter counter, long startTime, long duration) {
for (long time = startTime, endTime = startTime + duration; time <= endTime; time++) {
long value = counter.getValueAtTime(time);
long valueStartTime = counter.getValueStartTime(value);
if ((valueStartTime > time) || (valueStartTime <= time - counter.getTimeStep())) {
fail("Start time of value " + value + " out of range: time: " + time
+ ", valueStartTime: " + startTime
+ ", timeStep: " + counter.getTimeStep());
}
}
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/TotpCounterTest.java | Java | asf20 | 6,145 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
import android.test.MoreAsserts;
import junit.framework.TestCase;
/**
* Unit tests for {@link HexEncoding}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class HexEncodingTest extends TestCase {
public void testEncodeNull() {
try {
HexEncoding.encode(null);
fail();
} catch (NullPointerException expected) {}
}
public void testEncodeEmpty() {
assertEquals("", HexEncoding.encode(new byte[0]));
}
public void testEncodeAllDigits() {
assertEquals("0123456789abcdef", HexEncoding.encode(
new byte[] {0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}));
}
public void testDecodeNull() {
try {
HexEncoding.decode(null);
fail();
} catch (NullPointerException expected) {}
}
public void testDecodeEmpty() {
MoreAsserts.assertEquals(new byte[0], HexEncoding.decode(""));
}
public void testDecodeAllDigits() {
MoreAsserts.assertEquals(
new byte[] {0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef},
HexEncoding.decode("0123456789abcdef"));
}
public void testDecodeOddNumberOfDigits() {
MoreAsserts.assertEquals(
new byte[] {0x0f, 0x23, 0x45},
HexEncoding.decode("f2345"));
}
public void testDecodeOneDigit() {
MoreAsserts.assertEquals(
new byte[] {0x03},
HexEncoding.decode("3"));
}
public void testDecode_withSpaces() {
try {
HexEncoding.decode("01 23");
fail();
} catch (IllegalArgumentException expected) {}
}
public void testDecode_withUpperCaseDigits() {
MoreAsserts.assertEquals(
new byte[] {(byte) 0xab, (byte) 0xcd, (byte) 0xef},
HexEncoding.decode("ABCDEF"));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/HexEncodingTest.java | Java | asf20 | 2,407 |
/*
* 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 com.google.android.apps.authenticator.testability;
import android.os.Build;
import android.test.AndroidTestCase;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
/**
* Unit tests for {@link HttpClientFactory}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class HttpClientFactoryTest extends AndroidTestCase {
private HttpClient mClient;
@Override
protected void setUp() throws Exception {
super.setUp();
mClient = HttpClientFactory.createHttpClient(getContext());
}
@Override
protected void tearDown() throws Exception {
if (mClient != null) {
ClientConnectionManager connectionManager = mClient.getConnectionManager();
if (connectionManager != null) {
connectionManager.shutdown();
}
}
super.tearDown();
}
public void testClientClass() throws Exception {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ECLAIR_MR1) {
assertEquals(
getContext().getClassLoader().loadClass(DefaultHttpClient.class.getName()),
mClient.getClass());
} else {
assertEquals(
getContext().getClassLoader().loadClass("android.net.http.AndroidHttpClient"),
mClient.getClass());
}
}
public void testClientConfiguration() throws Exception {
HttpParams params = mClient.getParams();
assertFalse(HttpClientParams.isRedirecting(params));
assertFalse(HttpClientParams.isAuthenticating(params));
assertEquals(
HttpClientFactory.DEFAULT_CONNECT_TIMEOUT_MILLIS,
HttpConnectionParams.getConnectionTimeout(params));
assertEquals(
HttpClientFactory.DEFAULT_READ_TIMEOUT_MILLIS,
HttpConnectionParams.getSoTimeout(params));
assertEquals(
HttpClientFactory.DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS,
ConnManagerParams.getTimeout(params));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/testability/HttpClientFactoryTest.java | Java | asf20 | 2,765 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.Base32String.DecodingException;
import android.test.MoreAsserts;
import java.io.UnsupportedEncodingException;
import junit.framework.TestCase;
/**
* Unit test for {@link Base32String}
* @author sarvar@google.com (Sarvar Patel)
*/
public class Base32StringTest extends TestCase {
// regression input and output values taken from RFC 4648
// but stripped of the "=" padding from encoded output as required by the
// implemented encoding in Base32String.java
private static final byte[] INPUT1 = string2Bytes("foo");
private static final byte[] INPUT2 = string2Bytes("foob");
private static final byte[] INPUT3 = string2Bytes("fooba");
private static final byte[] INPUT4 = string2Bytes("foobar");
// RFC 4648 expected encodings for above inputs are:
// "MZXW6===", "MZXW6YQ=", "MZXW6YTB", MZXW6YTBOI======".
// Base32String encoding, however, drops the "=" padding.
private static final String OUTPUT1 = "MZXW6";
private static final String OUTPUT2 = "MZXW6YQ";
private static final String OUTPUT3 = "MZXW6YTB";
private static final String OUTPUT4 = "MZXW6YTBOI";
private static byte[] string2Bytes(String s) {
try {
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding is unsupported");
}
}
public void testRegressionValuesFromRfc4648() throws DecodingException {
// check encoding
assertEquals(OUTPUT1, Base32String.encode(INPUT1));
assertEquals(OUTPUT2, Base32String.encode(INPUT2));
assertEquals(OUTPUT3, Base32String.encode(INPUT3));
assertEquals(OUTPUT4, Base32String.encode(INPUT4));
// check decoding
MoreAsserts.assertEquals(INPUT1, Base32String.decode(OUTPUT1));
MoreAsserts.assertEquals(INPUT2, Base32String.decode(OUTPUT2));
MoreAsserts.assertEquals(INPUT3, Base32String.decode(OUTPUT3));
MoreAsserts.assertEquals(INPUT4, Base32String.decode(OUTPUT4));
}
/**
* Base32String implementation is not the same as that of RFC 4648, it drops
* the last incomplete chunk and thus accepts encoded strings that should have
* been rejected; also this results in multiple encoded strings being decoded
* to the same byte array.
* This test will catch any changes made regarding this behavior.
*/
public void testAmbiguousDecoding() throws DecodingException {
byte[] b16 = Base32String.decode("7777777777777777"); // 16 7s.
byte[] b17 = Base32String.decode("77777777777777777"); // 17 7s.
MoreAsserts.assertEquals(b16, b17);
}
// returns true if decoded, else false.
private byte[] checkDecoding(String s) {
try {
return Base32String.decode(s);
} catch (DecodingException e) {
return null; // decoding failed.
}
}
public void testSmallDecodingsAndFailures() {
// decoded, but not enough to return any bytes.
assertEquals(0, checkDecoding("A").length);
assertEquals(0, checkDecoding("").length);
assertEquals(0, checkDecoding(" ").length);
// decoded successfully and returned 1 byte.
assertEquals(1, checkDecoding("AA").length);
assertEquals(1, checkDecoding("AAA").length);
// decoded successfully and returned 2 bytes.
assertEquals(2, checkDecoding("AAAA").length);
// acceptable separators " " and "-" which should be ignored
assertEquals(2, checkDecoding("AA-AA").length);
assertEquals(2, checkDecoding("AA-AA").length);
MoreAsserts.assertEquals(checkDecoding("AA-AA"), checkDecoding("AA AA"));
MoreAsserts.assertEquals(checkDecoding("AAAA"), checkDecoding("AA AA"));
// 1, 8, 9, 0 are not a valid character, decoding should fail
assertNull(checkDecoding("11"));
assertNull(checkDecoding("A1"));
assertNull(checkDecoding("AAA8"));
assertNull(checkDecoding("AAA9"));
assertNull(checkDecoding("AAA0"));
// non-alphanumerics (except =) are not valid characters and decoding should fail
assertNull(checkDecoding("AAA,"));
assertNull(checkDecoding("AAA;"));
assertNull(checkDecoding("AAA."));
assertNull(checkDecoding("AAA!"));
// this just documents that a null string causes a nullpointerexception.
try {
checkDecoding(null);
fail();
} catch (NullPointerException e) {
// expected.
}
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/Base32StringTest.java | Java | asf20 | 4,981 |
/*
* 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 com.google.android.apps.authenticator;
import static org.mockito.Mockito.doReturn;
import static org.mockito.MockitoAnnotations.initMocks;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.Collection;
/**
* Unit tests for {@link OtpProvider}.
* @author sarvar@google.com (Sarvar Patel)
*
*/
public class OtpProviderTest extends AndroidTestCase {
private static final String SECRET = "7777777777777777"; // 16 sevens
private static final String SECRET2 = "2222222222222222"; // 16 twos
private Collection<String> result = new ArrayList<String>();
private OtpProvider otpProvider;
private AccountDb accountDb;
@Mock private TotpClock mockTotpClock;
@Override
public void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getContext());
initMocks(this);
DependencyInjector.setTotpClock(mockTotpClock);
accountDb = DependencyInjector.getAccountDb();
otpProvider = new OtpProvider(accountDb, mockTotpClock);
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
private void addSomeRecords() {
accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null);
accountDb.update("amywinehouse@aol.com", SECRET2, "amywinehouse@aol.com", OtpType.TOTP, null);
accountDb.update("maryweiss@yahoo.com", SECRET, "maryweiss@yahoo.com", OtpType.HOTP, 0);
}
public void testEnumerateAccountsNoRecords() throws Exception {
assertEquals(0, otpProvider.enumerateAccounts(result));
MoreAsserts.assertEmpty(result);
}
public void testEnumerateAccounts() throws Exception {
addSomeRecords();
otpProvider.enumerateAccounts(result);
MoreAsserts.assertContentsInAnyOrder(result,
"johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com");
}
public void testGetNextCode() throws Exception {
addSomeRecords();
// HOTP, counter at 0, check getNextcode response.
assertEquals("683298", otpProvider.getNextCode("maryweiss@yahoo.com"));
// counter updated to 1, check response has changed.
assertEquals("891123", otpProvider.getNextCode("maryweiss@yahoo.com"));
// TOTP: HOTP with current time (seconds / 30) as the counter
withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 1);
assertEquals("683298", otpProvider.getNextCode("johndoe@gmail.com"));
withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 2);
assertEquals("891123", otpProvider.getNextCode("johndoe@gmail.com"));
// Different TOTP account/secret
withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 1234567890L);
assertEquals("817746", otpProvider.getNextCode("amywinehouse@aol.com"));
}
public void testGetNextCodeWithEmptyAccountName() throws Exception {
accountDb.update("", SECRET, "", OtpType.HOTP, null);
// HOTP, counter at 0, check getNextcode response.
assertEquals("683298", otpProvider.getNextCode(""));
}
public void testRespondToChallengeWithNullChallenge() throws Exception {
addSomeRecords();
assertEquals("683298", otpProvider.respondToChallenge("maryweiss@yahoo.com", null));
}
public void testRespondToChallenge() throws Exception {
addSomeRecords();
assertEquals("308683298", otpProvider.respondToChallenge("maryweiss@yahoo.com", ""));
assertEquals("561472261",
otpProvider.respondToChallenge("maryweiss@yahoo.com", "this is my challenge"));
// TOTP: HOTP with current time (seconds / 30) as the counter
withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 1);
assertEquals("308683298", otpProvider.respondToChallenge("johndoe@gmail.com", ""));
withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 2);
assertEquals("561472261",
otpProvider.respondToChallenge("johndoe@gmail.com", "this is my challenge"));
// Different TOTP account/secret
withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 9876543210L);
assertEquals("834647199",
otpProvider.respondToChallenge("amywinehouse@aol.com", "this is my challenge"));
}
private void withTotpClockCurrentTimeSeconds(long timeSeconds) {
doReturn(Utilities.secondsToMillis(timeSeconds)).when(mockTotpClock).currentTimeMillis();
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/OtpProviderTest.java | Java | asf20 | 5,163 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.test.MoreAsserts;
import android.test.ViewAsserts;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Collection;
/**
* Unit tests for {@link EnterKeyActivity}.
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class EnterKeyActivityTest extends ActivityInstrumentationTestCase2<EnterKeyActivity> {
private EnterKeyActivity mActivity;
private Instrumentation mInstr;
private EditText mKeyEntryField;
private EditText mAccountName;
private Spinner mType;
private Button mSubmitButton;
private Collection<String> result = new ArrayList<String>();
private AccountDb mAccountDb;
public EnterKeyActivityTest() {
super(TestUtilities.APP_PACKAGE_NAME, EnterKeyActivity.class);
}
@Override
public void setUp() throws Exception {
// TODO(sarvar): sending keys require that emulators have their keyguards
// unlocked. We could do this with code here, this would require giving
// permission in the apps AndroidManifest.xml. Consider if this is needed.
super.setUp();
DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext());
TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver();
mAccountDb = DependencyInjector.getAccountDb();
setActivityInitialTouchMode(false);
mInstr = getInstrumentation();
mActivity = getActivity();
mAccountName = (EditText) mActivity.findViewById(R.id.account_name);
mKeyEntryField = (EditText) mActivity.findViewById(R.id.key_value);
mType = (Spinner) mActivity.findViewById(R.id.type_choice);
mSubmitButton = (Button) mActivity.findViewById(R.id.button_right);
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testPreconditions() {
// check that the test has input fields
assertNotNull(mAccountName);
assertNotNull(mKeyEntryField);
assertNotNull(mType);
assertNotNull(mType.getAdapter());
assertEquals(2, mType.getAdapter().getCount());
}
public void testStartingFieldValues() {
assertEquals("", mAccountName.getText().toString());
assertEquals("", mKeyEntryField.getText().toString());
}
public void testFieldsAreOnScreen() {
Window window = mActivity.getWindow();
View origin = window.getDecorView();
ViewAsserts.assertOnScreen(origin, mAccountName);
ViewAsserts.assertOnScreen(origin, mKeyEntryField);
ViewAsserts.assertOnScreen(origin, mType);
ViewAsserts.assertOnScreen(origin, mSubmitButton);
}
private void checkCorrectEntry(AccountDb.OtpType type) {
// enter account name
assertEquals("johndoe@gmail.com",
TestUtilities.setText(mInstr, mAccountName, "johndoe@gmail.com"));
// enter key
assertEquals("7777777777777777",
TestUtilities.setText(mInstr, mKeyEntryField, "7777777777777777"));
// select TOTP/HOTP type
assertEquals(mActivity.getResources().getStringArray(R.array.type)[type.value],
TestUtilities.selectSpinnerItem(mInstr, mType, type.value));
assertFalse(mActivity.isFinishing());
// save
TestUtilities.clickView(mInstr, mSubmitButton);
// check activity's resulting update of database.
assertEquals(1, mAccountDb.getNames(result));
MoreAsserts.assertContentsInOrder(result, "johndoe@gmail.com");
assertEquals(type, mAccountDb.getType("johndoe@gmail.com"));
assertEquals(0, mAccountDb.getCounter("johndoe@gmail.com").intValue());
assertTrue(mActivity.isFinishing());
}
public void testCorrectEntryTOTP() {
checkCorrectEntry(AccountDb.OtpType.TOTP);
}
public void testCorrectEntryHOTP() {
checkCorrectEntry(AccountDb.OtpType.HOTP);
}
public void testSubmitFailsWithShortKey() {
assertEquals("johndoe@gmail.com",
TestUtilities.setText(mInstr, mAccountName, "johndoe@gmail.com"));
TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value);
assertEquals(
mActivity.getResources().getStringArray(R.array.type)[AccountDb.OtpType.TOTP.value],
TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value));
// enter bad key without submitting, check status message
assertEquals("@@",
TestUtilities.setText(mInstr, mKeyEntryField, "@@"));
assertEquals(mActivity.getString(R.string.enter_key_illegal_char), mKeyEntryField.getError());
// clear bad keys, see status message is cleared.
assertEquals("", TestUtilities.setText(mInstr, mKeyEntryField, ""));
assertEquals(null, mKeyEntryField.getError());
// enter short key, check status message is empty
assertEquals("77777",
TestUtilities.setText(mInstr, mKeyEntryField, "77777"));
assertEquals(null, mKeyEntryField.getError());
// submit short key, and verify no updates to database and check status msg.
TestUtilities.clickView(getInstrumentation(), mSubmitButton);
assertFalse(mActivity.isFinishing());
assertEquals(0, mAccountDb.getNames(result));
assertEquals(mActivity.getString(R.string.enter_key_too_short), mKeyEntryField.getError());
// check key field is unchanged.
assertEquals("77777", mKeyEntryField.getText().toString());
// submit empty key.
assertEquals("",
TestUtilities.setText(mInstr, mKeyEntryField, ""));
TestUtilities.clickView(getInstrumentation(), mSubmitButton);
assertFalse(mActivity.isFinishing());
assertEquals(0, mAccountDb.getNames(result));
assertEquals(mActivity.getString(R.string.enter_key_too_short), mKeyEntryField.getError());
}
// TODO(sarvar): Consider not allowing acceptance of such bad account names.
public void testSubmitWithEmptyAccountName() {
assertEquals("7777777777777777",
TestUtilities.setText(mInstr, mKeyEntryField, "7777777777777777"));
assertEquals(
mActivity.getResources().getStringArray(R.array.type)[AccountDb.OtpType.TOTP.value],
TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value));
// enter empty name
assertEquals("",
TestUtilities.setText(mInstr, mAccountName, ""));
TestUtilities.clickView(mInstr, mSubmitButton);
assertEquals(1, mAccountDb.getNames(result));
assertEquals("7777777777777777", mAccountDb.getSecret(""));
}
// TODO(sarvar): Consider not allowing acceptance of such bad account names.
public void testSubmitWithWierdAccountName() {
assertEquals("7777777777777777",
TestUtilities.setText(mInstr, mKeyEntryField, "7777777777777777"));
assertEquals(
mActivity.getResources().getStringArray(R.array.type)[AccountDb.OtpType.TOTP.value],
TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value));
// enter empty name
assertEquals(",,",
TestUtilities.setText(mInstr, mAccountName, ",,"));
TestUtilities.clickView(getInstrumentation(), mSubmitButton);
assertEquals(1, mAccountDb.getNames(result));
assertEquals("7777777777777777", mAccountDb.getSecret(",,"));
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/EnterKeyActivityTest.java | Java | asf20 | 8,044 |
/*
* 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 com.google.android.apps.authenticator.dataimport;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.MockitoAnnotations.initMocks;
import com.google.android.apps.authenticator.AccountDb;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
/**
* Unit tests for {@link Importer}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class ImporterTest extends AndroidTestCase {
private Importer mImporter;
private AccountDb mAccountDb;
@Mock private SharedPreferences mMockPreferences;
@Mock private SharedPreferences.Editor mMockPreferencesEditor;
@Override
protected void setUp() throws Exception {
super.setUp();
DependencyInjector.resetForIntegrationTesting(getContext());
initMocks(this);
doReturn(mMockPreferencesEditor).when(mMockPreferences).edit();
doReturn(true).when(mMockPreferencesEditor).commit();
mAccountDb = DependencyInjector.getAccountDb();
mImporter = new Importer();
}
@Override
protected void tearDown() throws Exception {
DependencyInjector.close();
super.tearDown();
}
public void testImport_withNullBundle() {
try {
mImporter.importFromBundle(null, mAccountDb, mMockPreferences);
fail("NullPointerExcepton should have been thrown");
} catch (NullPointerException e) {
// Expected
}
}
public void testImport_withNullAccountDb() {
mImporter.importFromBundle(new Bundle(), null, mMockPreferences);
}
public void testImport_withNullPreferences() {
mImporter.importFromBundle(new Bundle(), mAccountDb, null);
}
public void testImportAccountDb_withAccounts() {
String account2 = "a@gmail.com";
String account1 = "b@gmail.com";
Bundle bundle = bundle(
accountsBundle(
accountBundle(account1, "ABCDEFGHI", "hotp", 12345),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account1, account2);
assertAccountInDb(account1, "ABCDEFGHI", OtpType.HOTP, 12345);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDbDoesNotOverwriteExistingAccounts() {
String account2 = "a@gmail.com";
String account1 = "b@gmail.com";
mAccountDb.update(account1, "AAAAAAAA", account1, OtpType.TOTP, 13);
Bundle bundle = bundle(
accountsBundle(
accountBundle(account1, "ABCDEFGHI", "hotp", 12345),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account1, account2);
assertAccountInDb(account1, "AAAAAAAA", OtpType.TOTP, 13);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDb_withAccountsWithMissingName() {
// First account's name is missing
String account2 = "a@gmail.com";
Bundle bundle = bundle(
accountsBundle(
accountBundle(null, "ABCDEFGHI", "hotp", 12345),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account2);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDb_withAccountsWithMissingSecret() {
// First account's secret is missing
String account2 = "a@gmail.com";
Bundle bundle = bundle(
accountsBundle(
accountBundle("test", null, "hotp", 12345),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account2);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDb_withAccountsWithMissingType() {
// First account's type is missing
String account2 = "a@gmail.com";
Bundle bundle = bundle(
accountsBundle(
accountBundle("test", "ABCDEFGHI", null, 12345),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account2);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDb_withAccountsWithMissingHotpCounter() {
// First account's HOTP counter is missing
String account2 = "a@gmail.com";
Bundle bundle = bundle(
accountsBundle(
accountBundle("test", "ABCDEFGHI", "hotp", null),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account2);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDb_withAccountsWithMissingTotpCounter() {
// Second account's TOTP counter is missing, but it doesn't matter as it's not needed
String account1 = "b@gmail.com";
String account2 = "a@gmail.com";
Bundle bundle = bundle(
accountsBundle(
accountBundle(account1, "ABCDEFGHI", "hotp", 12345),
accountBundle(account2, "ABCDEF", "totp", null)),
null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder(account1, account2);
assertAccountInDb(account1, "ABCDEFGHI", OtpType.HOTP, 12345);
assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0);
}
public void testImportAccountDb_withNoAccounts() {
Bundle bundle = bundle(accountsBundle(), null);
mImporter.importFromBundle(bundle, mAccountDb, null);
assertAccountsInDbInOrder();
}
public void testGetDataExportPreferences_withPreferences() {
Bundle prefBundle = new Bundle();
prefBundle.putBoolean("bool", true);
prefBundle.putInt("int", 9);
prefBundle.putFloat("float", 3.14f);
prefBundle.putString("string", "testing");
prefBundle.putLong("long", 0x123456DEADBEEFL);
prefBundle.putStringArray("stringarray", new String[] {"1", "2", "3"});
Bundle bundle = new Bundle();
bundle.putBundle("preferences", prefBundle);
mImporter.importFromBundle(bundle, null, mMockPreferences);
verify(mMockPreferencesEditor).putBoolean("bool", true);
verify(mMockPreferencesEditor).putInt("int", 9);
verify(mMockPreferencesEditor).putFloat("float", 3.14f);
verify(mMockPreferencesEditor).putString("string", "testing");
verify(mMockPreferencesEditor).putLong("long", 0x123456DEADBEEFL);
verify(mMockPreferencesEditor).commit();
verifyNoMoreInteractions(mMockPreferencesEditor);
}
public void testGetDataExportPreferences_withEmptyPreferences() {
Bundle prefBundle = new Bundle();
Bundle bundle = new Bundle();
bundle.putBundle("preferences", prefBundle);
mImporter.importFromBundle(bundle, null, mMockPreferences);
verify(mMockPreferencesEditor).commit();
verifyNoMoreInteractions(mMockPreferencesEditor);
}
public void testImportPreferences_withNullPreferences() {
mImporter.importFromBundle(new Bundle(), null, mMockPreferences);
verifyZeroInteractions(mMockPreferences);
}
private static Bundle accountBundle(
String name, String encodedSecret, String type, Integer counter) {
Bundle result = new Bundle();
if (name != null) {
result.putString(Importer.KEY_NAME, name);
}
if (encodedSecret != null) {
result.putString(Importer.KEY_ENCODED_SECRET, encodedSecret);
}
if (type != null) {
result.putString(Importer.KEY_TYPE, type);
}
if (counter != null) {
result.putInt(Importer.KEY_COUNTER, counter);
}
return result;
}
private static Bundle accountsBundle(Bundle... accountBundles) {
Bundle result = new Bundle();
if (accountBundles != null) {
for (int i = 0, len = accountBundles.length; i < len; i++) {
result.putBundle(String.valueOf(i), accountBundles[i]);
}
}
return result;
}
private static Bundle bundle(Bundle accountsBundle, Bundle preferencesBundle) {
Bundle result = new Bundle();
if (accountsBundle != null) {
result.putBundle(Importer.KEY_ACCOUNTS, accountsBundle);
}
if (preferencesBundle != null) {
result.putBundle(Importer.KEY_PREFERENCES, preferencesBundle);
}
return result;
}
private void assertAccountInDb(String name, String encodedSecret, OtpType type, int counter) {
assertEquals(encodedSecret, mAccountDb.getSecret(name));
assertEquals(type, mAccountDb.getType(name));
assertEquals(new Integer(counter), mAccountDb.getCounter(name));
}
private void assertAccountsInDbInOrder(String... expectedNames) {
List<String> actualNames = new ArrayList<String>();
mAccountDb.getNames(actualNames);
MoreAsserts.assertContentsInOrder(actualNames, (Object[]) expectedNames);
}
}
| zzhyjun- | tests/src/com/google/android/apps/authenticator/dataimport/ImporterTest.java | Java | asf20 | 9,964 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.TestablePreferenceActivity;
import com.google.android.apps.authenticator2.R;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
/**
* Activity that displays the "About" preferences.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SettingsAboutActivity extends TestablePreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_about);
String packageVersion = "";
try {
packageVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {}
findPreference("version").setSummary(packageVersion);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/SettingsAboutActivity.java | Java | asf20 | 1,476 |
/*
* Copyright 2009 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 com.google.android.apps.authenticator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.google.android.apps.authenticator.Base32String.DecodingException;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* The activity that displays the integrity check value for a key.
* The user is passed in via the extra bundle in "user".
*
* @author sweis@google.com (Steve Weis)
*/
public class CheckCodeActivity extends Activity {
private TextView mCheckCodeTextView;
private TextView mCodeTextView;
private TextView mCounterValue;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_code);
mCodeTextView = (TextView) findViewById(R.id.code_value);
mCheckCodeTextView = (TextView) findViewById(R.id.check_code);
mCounterValue = (TextView) findViewById(R.id.counter_value);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String user = extras.getString("user");
AccountDb accountDb = DependencyInjector.getAccountDb();
AccountDb.OtpType type = accountDb.getType(user);
if (type == AccountDb.OtpType.HOTP) {
mCounterValue.setText(accountDb.getCounter(user).toString());
findViewById(R.id.counter_area).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.counter_area).setVisibility(View.GONE);
}
String secret = accountDb.getSecret(user);
String checkCode = null;
String errorMessage = null;
try {
checkCode = getCheckCode(secret);
} catch (GeneralSecurityException e) {
errorMessage = getString(R.string.general_security_exception);
} catch (DecodingException e) {
errorMessage = getString(R.string.decoding_exception);
}
if (errorMessage != null) {
mCheckCodeTextView.setText(errorMessage);
return;
}
mCodeTextView.setText(checkCode);
String checkCodeMessage = String.format(getString(R.string.check_code),
TextUtils.htmlEncode(user));
CharSequence styledCheckCode = Html.fromHtml(checkCodeMessage);
mCheckCodeTextView.setText(styledCheckCode);
mCheckCodeTextView.setVisibility(View.VISIBLE);
findViewById(R.id.code_area).setVisibility(View.VISIBLE);
}
static String getCheckCode(String secret) throws GeneralSecurityException,
DecodingException {
final byte[] keyBytes = Base32String.decode(secret);
Mac mac = Mac.getInstance("HMACSHA1");
mac.init(new SecretKeySpec(keyBytes, ""));
PasscodeGenerator pcg = new PasscodeGenerator(mac);
return pcg.generateResponseCode(0L);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/CheckCodeActivity.java | Java | asf20 | 3,619 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator2.R;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
/**
* Circular countdown indicator. The indicator is a filled arc which starts as a full circle ({@code
* 360} degrees) and shrinks to {@code 0} degrees the less time is remaining.
* @author klyubin@google.com (Alex Klyubin)
*/
public class CountdownIndicator extends View {
private final Paint mRemainingSectorPaint;
private final Paint mBorderPaint;
private static final int DEFAULT_COLOR = 0xff3060c0;
/**
* Countdown phase starting with {@code 1} when a full cycle is remaining and shrinking to
* {@code 0} the closer the countdown is to zero.
*/
private double mPhase;
public CountdownIndicator(Context context) {
this(context, null);
}
public CountdownIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
int color = DEFAULT_COLOR;
Resources.Theme theme = context.getTheme();
TypedArray appearance = theme.obtainStyledAttributes(
attrs, R.styleable.CountdownIndicator, 0, 0);
if (appearance != null) {
int n = appearance.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = appearance.getIndex(i);
switch (attr) {
case R.styleable.CountdownIndicator_color:
color = appearance.getColor(attr, DEFAULT_COLOR);
break;
}
}
}
mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBorderPaint.setStrokeWidth(0); // hairline
mBorderPaint.setStyle(Style.STROKE);
mBorderPaint.setColor(color);
mRemainingSectorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mRemainingSectorPaint.setColor(mBorderPaint.getColor());
}
@Override
protected void onDraw(Canvas canvas) {
float remainingSectorSweepAngle = (float) (mPhase * 360);
float remainingSectorStartAngle = 270 - remainingSectorSweepAngle;
// Draw the sector/filled arc
// We need to leave the leftmost column and the topmost row out of the drawingRect because
// in anti-aliased mode drawArc and drawOval use these areas for some reason.
RectF drawingRect = new RectF(1, 1, getWidth() - 1, getHeight() - 1);
if (remainingSectorStartAngle < 360) {
canvas.drawArc(
drawingRect,
remainingSectorStartAngle,
remainingSectorSweepAngle,
true,
mRemainingSectorPaint);
} else {
// 360 degrees is equivalent to 0 degrees for drawArc, hence the drawOval below.
canvas.drawOval(drawingRect, mRemainingSectorPaint);
}
// Draw the outer border
canvas.drawOval(drawingRect, mBorderPaint);
}
/**
* Sets the phase of this indicator.
*
* @param phase phase {@code [0, 1]}: {@code 1} when the maximum amount of time is remaining,
* {@code 0} when no time is remaining.
*/
public void setPhase(double phase) {
if ((phase < 0) || (phase > 1)) {
throw new IllegalArgumentException("phase: " + phase);
}
mPhase = phase;
invalidate();
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/CountdownIndicator.java | Java | asf20 | 3,933 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Clock input for the time-based OTPs (TOTP). The input is based on the current system time
* and is adjusted by a persistently stored correction value (offset in minutes).
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class TotpClock {
// @VisibleForTesting
static final String PREFERENCE_KEY_OFFSET_MINUTES = "timeCorrectionMinutes";
private final SharedPreferences mPreferences;
private final Object mLock = new Object();
/**
* Cached value of time correction (in minutes) or {@code null} if not cached. The value is cached
* because it's read very frequently (once every 100ms) and is modified very infrequently.
*
* @GuardedBy {@link #mLock}
*/
private Integer mCachedCorrectionMinutes;
public TotpClock(Context context) {
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
/**
* Gets the number of milliseconds since epoch.
*/
public long currentTimeMillis() {
return System.currentTimeMillis() + getTimeCorrectionMinutes() * Utilities.MINUTE_IN_MILLIS;
}
/**
* Gets the currently used time correction value.
*
* @return number of minutes by which this device is behind the correct time.
*/
public int getTimeCorrectionMinutes() {
synchronized (mLock) {
if (mCachedCorrectionMinutes == null) {
mCachedCorrectionMinutes = mPreferences.getInt(PREFERENCE_KEY_OFFSET_MINUTES, 0);
}
return mCachedCorrectionMinutes;
}
}
/**
* Sets the currently used time correction value.
*
* @param minutes number of minutes by which this device is behind the correct time.
*/
public void setTimeCorrectionMinutes(int minutes) {
synchronized (mLock) {
mPreferences.edit().putInt(PREFERENCE_KEY_OFFSET_MINUTES, minutes).commit();
// Invalidate the cache to force reading actual settings from time to time
mCachedCorrectionMinutes = null;
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/TotpClock.java | Java | asf20 | 2,710 |
/*
* 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 com.google.android.apps.authenticator.howitworks;
import com.google.android.apps.authenticator.wizard.WizardPageActivity;
import com.google.android.apps.authenticator2.R;
import android.os.Bundle;
import java.io.Serializable;
/**
* The page of the "How it works" that explains that occasionally the user might need to enter a
* verification code generated by this application. The user simply needs to click the Next button
* to go to the next page.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class IntroEnterCodeActivity extends WizardPageActivity<Serializable> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPageContentView(R.layout.howitworks_enter_code);
setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_enter_code_details);
}
@Override
protected void onRightButtonPressed() {
startPageActivity(IntroVerifyDeviceActivity.class);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/howitworks/IntroEnterCodeActivity.java | Java | asf20 | 1,591 |
/*
* 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 com.google.android.apps.authenticator.howitworks;
import com.google.android.apps.authenticator.wizard.WizardPageActivity;
import com.google.android.apps.authenticator2.R;
import android.os.Bundle;
import java.io.Serializable;
/**
* The page of the "How it works" flow that explains that the user can ask Google not to
* ask for verification codes every time the user signs in from a verified computer or device.
* The user needs to click the Exit button to exit the flow.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class IntroVerifyDeviceActivity extends WizardPageActivity<Serializable> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPageContentView(R.layout.howitworks_verify_device);
setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_verify_device_details);
mRightButton.setText(R.string.button_exit_howitworks_flow);
}
@Override
protected void onRightButtonPressed() {
exitWizard();
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/howitworks/IntroVerifyDeviceActivity.java | Java | asf20 | 1,649 |
/*
* 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 com.google.android.apps.authenticator.howitworks;
import com.google.android.apps.authenticator.wizard.WizardPageActivity;
import com.google.android.apps.authenticator2.R;
import android.os.Bundle;
import java.io.Serializable;
/**
* The start page of the "How it works" flow that explains that in addition to entering the password
* during sign in a verification code may be required. The user simply needs to click the Next
* button to go to the next page.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class IntroEnterPasswordActivity extends WizardPageActivity<Serializable> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPageContentView(R.layout.howitworks_enter_password);
setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_enter_password_details);
}
@Override
protected void onRightButtonPressed() {
startPageActivity(IntroEnterCodeActivity.class);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/howitworks/IntroEnterPasswordActivity.java | Java | asf20 | 1,607 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.wizard.WizardPageActivity;
import com.google.android.apps.authenticator2.R;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import java.io.Serializable;
/**
* The page of the "Add account" flow that offers the user to add an account.
* The page offers the user to scan a barcode or manually enter the account details.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class AddOtherAccountActivity extends WizardPageActivity<Serializable> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPageContentView(R.layout.add_other_account);
findViewById(R.id.scan_barcode).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scanBarcode();
}
});
findViewById(R.id.manually_add_account).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
manuallyEnterAccountDetails();
}
});
mRightButton.setVisibility(View.INVISIBLE);
}
private void manuallyEnterAccountDetails() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(this, EnterKeyActivity.class);
startActivity(intent);
}
private void scanBarcode() {
startActivity(AuthenticatorActivity.getLaunchIntentActionScanBarcode(this));
finish();
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/AddOtherAccountActivity.java | Java | asf20 | 2,104 |
/*
* Copyright 2009 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 com.google.android.apps.authenticator;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import javax.crypto.Mac;
/**
* An implementation of the HOTP generator specified by RFC 4226. Generates
* short passcodes that may be used in challenge-response protocols or as
* timeout passcodes that are only valid for a short period.
*
* The default passcode is a 6-digit decimal code. The maximum passcode length is 9 digits.
*
* @author sweis@google.com (Steve Weis)
*
*/
public class PasscodeGenerator {
private static final int MAX_PASSCODE_LENGTH = 9;
/** Default time interval */
public static final int INTERVAL = OtpProvider.DEFAULT_INTERVAL;
/** Default decimal passcode length */
private static final int PASS_CODE_LENGTH = 6;
/** The number of previous and future intervals to check */
private static final int ADJACENT_INTERVALS = 1;
private final Signer signer;
private final int codeLength;
/**
* Using an interface to allow us to inject different signature
* implementations.
*/
interface Signer {
/**
* @param data Preimage to sign, represented as sequence of arbitrary bytes
* @return Signature as sequence of bytes.
* @throws GeneralSecurityException
*/
byte[] sign(byte[] data) throws GeneralSecurityException;
}
/**
* @param mac A {@link Mac} used to generate passcodes
*/
public PasscodeGenerator(Mac mac) {
this(mac, PASS_CODE_LENGTH);
}
public PasscodeGenerator(Signer signer) {
this(signer, PASS_CODE_LENGTH);
}
/**
* @param mac A {@link Mac} used to generate passcodes
* @param passCodeLength The length of the decimal passcode
*/
public PasscodeGenerator(final Mac mac, int passCodeLength) {
this(new Signer() {
@Override
public byte[] sign(byte[] data){
return mac.doFinal(data);
}
}, passCodeLength);
}
public PasscodeGenerator(Signer signer, int passCodeLength) {
if ((passCodeLength < 0) || (passCodeLength > MAX_PASSCODE_LENGTH)) {
throw new IllegalArgumentException(
"PassCodeLength must be between 1 and " + MAX_PASSCODE_LENGTH
+ " digits.");
}
this.signer = signer;
this.codeLength = passCodeLength;
}
private String padOutput(int value) {
String result = Integer.toString(value);
for (int i = result.length(); i < codeLength; i++) {
result = "0" + result;
}
return result;
}
/**
* @param state 8-byte integer value representing internal OTP state.
* @return A decimal response code
* @throws GeneralSecurityException If a JCE exception occur
*/
public String generateResponseCode(long state)
throws GeneralSecurityException {
byte[] value = ByteBuffer.allocate(8).putLong(state).array();
return generateResponseCode(value);
}
/**
* @param state 8-byte integer value representing internal OTP state.
* @param challenge Optional challenge as array of bytes.
* @return A decimal response code
* @throws GeneralSecurityException If a JCE exception occur
*/
public String generateResponseCode(long state, byte[] challenge)
throws GeneralSecurityException {
if (challenge == null) {
return generateResponseCode(state);
} else {
// Allocate space for combination and store.
byte value[] = ByteBuffer.allocate(8 + challenge.length)
.putLong(state) // Write out OTP state
.put(challenge, 0, challenge.length) // Concatenate with challenge.
.array();
return generateResponseCode(value);
}
}
/**
* @param challenge An arbitrary byte array used as a challenge
* @return A decimal response code
* @throws GeneralSecurityException If a JCE exception occur
*/
public String generateResponseCode(byte[] challenge)
throws GeneralSecurityException {
byte[] hash = signer.sign(challenge);
// Dynamically truncate the hash
// OffsetBits are the low order bits of the last byte of the hash
int offset = hash[hash.length - 1] & 0xF;
// Grab a positive integer value starting at the given offset.
int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF;
int pinValue = truncatedHash % (int) Math.pow(10, codeLength);
return padOutput(pinValue);
}
/**
* Grabs a positive integer value from the input array starting at
* the given offset.
* @param bytes the array of bytes
* @param start the index into the array to start grabbing bytes
* @return the integer constructed from the four bytes in the array
*/
private int hashToInt(byte[] bytes, int start) {
DataInput input = new DataInputStream(
new ByteArrayInputStream(bytes, start, bytes.length - start));
int val;
try {
val = input.readInt();
} catch (IOException e) {
throw new IllegalStateException(e);
}
return val;
}
/**
* @param challenge A challenge to check a response against
* @param response A response to verify
* @return True if the response is valid
*/
public boolean verifyResponseCode(long challenge, String response)
throws GeneralSecurityException {
String expectedResponse = generateResponseCode(challenge, null);
return expectedResponse.equals(response);
}
/**
* Verify a timeout code. The timeout code will be valid for a time
* determined by the interval period and the number of adjacent intervals
* checked.
*
* @param timeoutCode The timeout code
* @return True if the timeout code is valid
*/
public boolean verifyTimeoutCode(long currentInterval, String timeoutCode)
throws GeneralSecurityException {
return verifyTimeoutCode(timeoutCode, currentInterval,
ADJACENT_INTERVALS, ADJACENT_INTERVALS);
}
/**
* Verify a timeout code. The timeout code will be valid for a time
* determined by the interval period and the number of adjacent intervals
* checked.
*
* @param timeoutCode The timeout code
* @param pastIntervals The number of past intervals to check
* @param futureIntervals The number of future intervals to check
* @return True if the timeout code is valid
*/
public boolean verifyTimeoutCode(String timeoutCode,
long currentInterval,
int pastIntervals,
int futureIntervals) throws GeneralSecurityException {
// Ensure that look-ahead and look-back counts are not negative.
pastIntervals = Math.max(pastIntervals, 0);
futureIntervals = Math.max(futureIntervals, 0);
// Try upto "pastIntervals" before current time, and upto "futureIntervals" after.
for (int i = -pastIntervals; i <= futureIntervals; ++i) {
String candidate = generateResponseCode(currentInterval - i, null);
if (candidate.equals(timeoutCode)) {
return true;
}
}
return false;
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/PasscodeGenerator.java | Java | asf20 | 7,747 |
/*
* 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 com.google.android.apps.authenticator;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
/**
* Interface for providing functionality not available in Market builds without having to modify
* the codebase shared between the Market and non-Market builds.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public interface OptionalFeatures {
/**
* Invoked when the {@link AuthenticatorActivity} {@code onCreate} is almost done.
*/
void onAuthenticatorActivityCreated(AuthenticatorActivity activity);
/**
* Invoked when the {@link AuthenticatorActivity} saves an account/seed.
*/
void onAuthenticatorActivityAccountSaved(Context context, String account);
/**
* Creates the {@link OtpSource} instance used for OTP generation by the app.
*/
OtpSource createOtpSource(AccountDb accountDb, TotpClock totpClock);
/**
* Invoked when a HOTP OTP could not be generated by {@link AuthenticatorActivity}
* for the provided account.
*/
void onAuthenticatorActivityGetNextOtpFailed(
AuthenticatorActivity activity, String accountName, OtpSourceException exception);
/**
* Invoked by {@link AuthenticatorActivity#onCreateDialog(int)} for dialog IDs not directly
* handled by the {@link AuthenticatorActivity} class.
*
* @return dialog or {@code null} for the default behavior.
*/
Dialog onAuthenticatorActivityCreateDialog(AuthenticatorActivity activity, int id);
/**
* Invoked when {@link AuthenticatorActivity} was asked to initiate the Add Account flow.
*/
void onAuthenticatorActivityAddAccount(AuthenticatorActivity activity);
/**
* Invoked when a URI has been scanned.
*
* @return {@code true} if the URI has been consumed by these optional features, {@code false}
* otherwise.
*/
boolean interpretScanResult(Context context, Uri scanResult);
/**
* Invoked when data have been successfully imported from the old Authenticator app.
*/
void onDataImportedFromOldApp(Context context);
/**
* Gets the {@link SharedPreferences} into which to import preferences from the old Authenticator
* app.
*
* @return preferences or {@code null} to skip the importing of preferences.
*/
SharedPreferences getSharedPreferencesForDataImportFromOldApp(Context context);
/**
* Appends the Learn more link to data import dialog text.
*
* @return text with the link.
*/
String appendDataImportLearnMoreLink(Context context, String text);
}
| zzhyjun- | src/com/google/android/apps/authenticator/OptionalFeatures.java | Java | asf20 | 3,174 |
/*
* 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 com.google.android.apps.authenticator.wizard;
import com.google.android.apps.authenticator.AuthenticatorActivity;
import com.google.android.apps.authenticator.testability.TestableActivity;
import com.google.android.apps.authenticator2.R;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.io.Serializable;
/**
* Base class for a page of a wizard.
*
* <p>
* The main features are:
* <ul>
* <li>Layout consists of a settable contents page (see {@link #setPageContentView(int)})
* and a button bar at the bottom of the page,</li>
* <li>Supports three modes: Back + Next buttons, middle button only, and progress bar (with
* indeterminate progress) with a Cancel button. Back + Next buttons is the default.</li>
* <li>Automatically passes the status of the wizard through the pages if they are launched with
* {@link #startPageActivity(Class)}.</li>
* </ul>
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class WizardPageActivity<WizardState extends Serializable> extends TestableActivity {
// @VisibleForTesting
public static final String KEY_WIZARD_STATE = "wizardState";
/** Type of the button bar displayed at the bottom of the page. */
private enum ButtonBarType {
LEFT_RIGHT_BUTTONS,
MIDDLE_BUTTON_ONLY,
CANCEL_BUTTON_ONLY,
}
private WizardState mWizardState;
private View mLeftRightButtonBar;
private View mMiddleButtonOnlyBar;
private View mCancelButtonOnlyBar;
private View mInlineProgressView;
private ViewGroup mPageContentView;
protected Button mLeftButton;
protected Button mRightButton;
protected Button mMiddleButton;
protected View mCancelButton;
private ButtonBarType mButtonBarType;
private ButtonBarType mButtonBarTypeBeforeInlineProgressDisplayed;
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WizardState wizardState;
if (savedInstanceState == null) {
wizardState = getWizardStateFromIntent(getIntent());
} else {
wizardState = (WizardState) savedInstanceState.getSerializable(KEY_WIZARD_STATE);
}
checkWizardStateValidity(wizardState);
mWizardState = wizardState;
setContentView(R.layout.wizard_page);
mLeftRightButtonBar = findViewById(R.id.button_bar_left_right_buttons);
mMiddleButtonOnlyBar = findViewById(R.id.button_bar_middle_button_only);
mPageContentView = (ViewGroup) findViewById(R.id.page_content);
mLeftButton = (Button) mLeftRightButtonBar.findViewById(R.id.button_left);
mLeftButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onLeftButtonPressed();
}
});
mRightButton = (Button) findViewById(R.id.button_right);
mRightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onRightButtonPressed();
}
});
mMiddleButton = (Button) findViewById(R.id.button_middle);
mMiddleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onMiddleButtonPressed();
}
});
mCancelButtonOnlyBar = findViewById(R.id.button_bar_cancel_only);
mInlineProgressView = findViewById(R.id.inline_progress);
mCancelButton = findViewById(R.id.button_cancel);
setButtonBarType(ButtonBarType.LEFT_RIGHT_BUTTONS);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_WIZARD_STATE, mWizardState);
}
protected WizardState getWizardState() {
return mWizardState;
}
protected void setWizardState(WizardState wizardState) {
mWizardState = wizardState;
}
protected View setPageContentView(int resId) {
View view = getLayoutInflater().inflate(resId, null);
mPageContentView.removeAllViews();
mPageContentView.addView(view);
return view;
}
protected void setButtonBarModeMiddleButtonOnly() {
setButtonBarType(ButtonBarType.MIDDLE_BUTTON_ONLY);
}
/**
* Invoked when the left button is pressed. The default implementation invokes
* {@link #onBackPressed()}.
*/
protected void onLeftButtonPressed() {
onBackPressed();
}
/**
* Invoked when the right button is pressed. The default implementation does nothing.
*/
protected void onRightButtonPressed() {}
/**
* Invoked when the middle button is pressed. The default implementation does nothing.
*/
protected void onMiddleButtonPressed() {}
/**
* Launches/displays the specified page of the wizard. The page will get a copy of the current
* state of the wizard.
*/
protected void startPageActivity(Class<? extends WizardPageActivity<WizardState>> activityClass) {
Intent intent = new Intent(this, activityClass);
intent.putExtra(KEY_WIZARD_STATE, getWizardState());
startActivity(intent);
}
/**
* Launches/displays the specified page of the wizard. The page will get a copy of the current
* state of the wizard.
*/
protected void startPageActivityForResult(
Class<? extends WizardPageActivity<WizardState>> activityClass, int requestCode) {
Intent intent = new Intent(this, activityClass);
intent.putExtra(KEY_WIZARD_STATE, getWizardState());
startActivityForResult(intent, requestCode);
}
/**
* Extracts the state of the wizard from the provided Intent.
*
* @return state or {@code null} if not found.
*/
@SuppressWarnings("unchecked")
protected WizardState getWizardStateFromIntent(Intent intent) {
return (intent != null)
? (WizardState) intent.getSerializableExtra(KEY_WIZARD_STATE)
: null;
}
/**
* Sets the contents of the {@code TextView} to the HTML contained in the string resource.
*/
protected void setTextViewHtmlFromResource(int viewId, int resId) {
setTextViewHtmlFromResource((TextView) findViewById(viewId), resId);
}
/**
* Sets the contents of the {@code TextView} to the HTML contained in the string resource.
*/
protected void setTextViewHtmlFromResource(TextView view, int resId) {
view.setText(Html.fromHtml(getString(resId)));
}
/**
* Sets the contents of the {@code TextView} to the provided HTML.
*/
protected void setTextViewHtml(int viewId, String html) {
setTextViewHtml((TextView) findViewById(viewId), html);
}
/**
* Sets the contents of the {@code TextView} to the provided HTML.
*/
protected void setTextViewHtml(TextView view, String html) {
view.setText(Html.fromHtml(html));
}
/**
* Sets the type of the button bar displayed at the bottom of the page.
*/
private void setButtonBarType(ButtonBarType type) {
mButtonBarType = type;
switch (type) {
case LEFT_RIGHT_BUTTONS:
mLeftRightButtonBar.setVisibility(View.VISIBLE);
mMiddleButtonOnlyBar.setVisibility(View.GONE);
mCancelButtonOnlyBar.setVisibility(View.GONE);
break;
case MIDDLE_BUTTON_ONLY:
mMiddleButtonOnlyBar.setVisibility(View.VISIBLE);
mLeftRightButtonBar.setVisibility(View.GONE);
mCancelButtonOnlyBar.setVisibility(View.GONE);
break;
case CANCEL_BUTTON_ONLY:
mCancelButtonOnlyBar.setVisibility(View.VISIBLE);
mLeftRightButtonBar.setVisibility(View.GONE);
mMiddleButtonOnlyBar.setVisibility(View.GONE);
break;
default:
throw new IllegalArgumentException(String.valueOf(type));
}
}
/**
* Changes this page to show an indefinite progress bar with a Cancel button.
*
* @param cancelListener listener invoked when the Cancel button is pressed.
*
* @see #dismissInlineProgress()
*/
protected void showInlineProgress(View.OnClickListener cancelListener) {
mCancelButton.setOnClickListener(cancelListener);
mCancelButton.setEnabled(true);
mInlineProgressView.setVisibility(View.VISIBLE);
if (mButtonBarType != ButtonBarType.CANCEL_BUTTON_ONLY) {
mButtonBarTypeBeforeInlineProgressDisplayed = mButtonBarType;
}
setButtonBarType(ButtonBarType.CANCEL_BUTTON_ONLY);
}
/**
* Changes this page to hide the indefinite progress bar with a Cancel button. The page reverts
* to the usual layout with the left and right buttons.
*
* @see #showInlineProgress(android.view.View.OnClickListener)
*/
protected void dismissInlineProgress() {
mCancelButton.setOnClickListener(null);
setButtonBarType(mButtonBarTypeBeforeInlineProgressDisplayed);
}
protected void exitWizard() {
Intent intent = new Intent(this, AuthenticatorActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
/**
* Checks the validity of the current state of the wizard.
*
* @throws IllegalStateException if the state is invalid.
*/
protected void checkWizardStateValidity(@SuppressWarnings("unused") WizardState wizardState) {}
}
| zzhyjun- | src/com/google/android/apps/authenticator/wizard/WizardPageActivity.java | Java | asf20 | 9,768 |
/*
* Copyright 2010 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.AccountDb.OtpType;
import com.google.android.apps.authenticator.PasscodeGenerator.Signer;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Collection;
/**
* Class containing implementation of HOTP/TOTP.
* Generates OTP codes for one or more accounts.
* @author Steve Weis (sweis@google.com)
* @author Cem Paya (cemp@google.com)
*/
public class OtpProvider implements OtpSource {
private static final int PIN_LENGTH = 6; // HOTP or TOTP
private static final int REFLECTIVE_PIN_LENGTH = 9; // ROTP
@Override
public int enumerateAccounts(Collection<String> result) {
return mAccountDb.getNames(result);
}
@Override
public String getNextCode(String accountName) throws OtpSourceException {
return getCurrentCode(accountName, null);
}
// This variant is used when an additional challenge, such as URL or
// transaction details, are included in the OTP request.
// The additional string is appended to standard HOTP/TOTP state before
// applying the MAC function.
@Override
public String respondToChallenge(String accountName, String challenge) throws OtpSourceException {
if (challenge == null) {
return getCurrentCode(accountName, null);
}
try {
byte[] challengeBytes = challenge.getBytes("UTF-8");
return getCurrentCode(accountName, challengeBytes);
} catch (UnsupportedEncodingException e) {
return "";
}
}
@Override
public TotpCounter getTotpCounter() {
return mTotpCounter;
}
@Override
public TotpClock getTotpClock() {
return mTotpClock;
}
private String getCurrentCode(String username, byte[] challenge) throws OtpSourceException {
// Account name is required.
if (username == null) {
throw new OtpSourceException("No account name");
}
OtpType type = mAccountDb.getType(username);
String secret = getSecret(username);
long otp_state = 0;
if (type == OtpType.TOTP) {
// For time-based OTP, the state is derived from clock.
otp_state =
mTotpCounter.getValueAtTime(Utilities.millisToSeconds(mTotpClock.currentTimeMillis()));
} else if (type == OtpType.HOTP){
// For counter-based OTP, the state is obtained by incrementing stored counter.
mAccountDb.incrementCounter(username);
Integer counter = mAccountDb.getCounter(username);
otp_state = counter.longValue();
}
return computePin(secret, otp_state, challenge);
}
public OtpProvider(AccountDb accountDb, TotpClock totpClock) {
this(DEFAULT_INTERVAL, accountDb, totpClock);
}
public OtpProvider(int interval, AccountDb accountDb, TotpClock totpClock) {
mAccountDb = accountDb;
mTotpCounter = new TotpCounter(interval);
mTotpClock = totpClock;
}
/**
* Computes the one-time PIN given the secret key.
*
* @param secret the secret key
* @param otp_state current token state (counter or time-interval)
* @param challenge optional challenge bytes to include when computing passcode.
* @return the PIN
*/
private String computePin(String secret, long otp_state, byte[] challenge)
throws OtpSourceException {
if (secret == null || secret.length() == 0) {
throw new OtpSourceException("Null or empty secret");
}
try {
Signer signer = AccountDb.getSigningOracle(secret);
PasscodeGenerator pcg = new PasscodeGenerator(signer,
(challenge == null) ? PIN_LENGTH : REFLECTIVE_PIN_LENGTH);
return (challenge == null) ?
pcg.generateResponseCode(otp_state) :
pcg.generateResponseCode(otp_state, challenge);
} catch (GeneralSecurityException e) {
throw new OtpSourceException("Crypto failure", e);
}
}
/**
* Reads the secret key that was saved on the phone.
* @param user Account name identifying the user.
* @return the secret key as base32 encoded string.
*/
String getSecret(String user) {
return mAccountDb.getSecret(user);
}
/** Default passcode timeout period (in seconds) */
public static final int DEFAULT_INTERVAL = 30;
private final AccountDb mAccountDb;
/** Counter for time-based OTPs (TOTP). */
private final TotpCounter mTotpCounter;
/** Clock input for time-based OTPs (TOTP). */
private final TotpClock mTotpClock;
}
| zzhyjun- | src/com/google/android/apps/authenticator/OtpProvider.java | Java | asf20 | 5,037 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.TestablePreferenceActivity;
import com.google.android.apps.authenticator2.R;
import android.os.Bundle;
/**
* Top-level preferences Activity.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SettingsActivity extends TestablePreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/SettingsActivity.java | Java | asf20 | 1,151 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.timesync;
import com.google.android.apps.authenticator.wizard.WizardPageActivity;
import com.google.android.apps.authenticator2.R;
import android.os.Bundle;
import java.io.Serializable;
/**
* Activity that displays more information about the Time Correction/Sync feature.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class AboutActivity extends WizardPageActivity<Serializable> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPageContentView(R.layout.timesync_about);
setTextViewHtmlFromResource(R.id.details, R.string.timesync_about_feature_screen_details);
setButtonBarModeMiddleButtonOnly();
mMiddleButton.setText(R.string.ok);
}
@Override
protected void onMiddleButtonPressed() {
onBackPressed();
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/timesync/AboutActivity.java | Java | asf20 | 1,483 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.timesync;
import com.google.android.apps.authenticator.RunOnThisLooperThreadExecutor;
import com.google.android.apps.authenticator.TotpClock;
import com.google.android.apps.authenticator.Utilities;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Controller of the {@link SyncNowActivity}. As soon as started, the controller attempts to
* obtain the network time using a {@link NetworkTimeProvider}, then computes the offset between
* the device's system time and the network time and updates {@link TotpClock} to use that as
* its time correction value.
*
* @author klyubin@google.com (Alex Klyubin)
*/
class SyncNowController {
enum Result {
TIME_CORRECTED,
TIME_ALREADY_CORRECT,
CANCELLED_BY_USER,
ERROR_CONNECTIVITY_ISSUE,
}
/** Presentation layer. */
interface Presenter {
/** Invoked when the controller starts up. */
void onStarted();
/** Invoked when the controller is finished. */
void onDone(Result result);
}
private enum State {
NOT_STARTED,
IN_PROGRESS,
DONE,
}
private static final String LOG_TAG = "TimeSync";
private final TotpClock mTotpClock;
private final NetworkTimeProvider mNetworkTimeProvider;
private final Executor mBackgroundExecutor;
private final Executor mCallbackFromBackgroundExecutor;
private final boolean mBackgroundExecutorServiceOwnedByThisController;
private Presenter mPresenter;
private State mState = State.NOT_STARTED;
private Result mResult;
// @VisibleForTesting
SyncNowController(
TotpClock totpClock,
NetworkTimeProvider networkTimeProvider,
Executor backgroundExecutor,
boolean backgroundExecutorServiceOwnedByThisController,
Executor callbackFromBackgroundExecutor) {
mTotpClock = totpClock;
mNetworkTimeProvider = networkTimeProvider;
mBackgroundExecutor = backgroundExecutor;
mBackgroundExecutorServiceOwnedByThisController =
backgroundExecutorServiceOwnedByThisController;
mCallbackFromBackgroundExecutor = callbackFromBackgroundExecutor;
}
SyncNowController(TotpClock totpClock, NetworkTimeProvider networkTimeProvider) {
this(
totpClock,
networkTimeProvider,
Executors.newSingleThreadExecutor(),
true,
new RunOnThisLooperThreadExecutor());
}
/**
* Attaches the provided presentation layer to this controller. The previously attached
* presentation layer (if any) stops receiving events from this controller.
*/
void attach(Presenter presenter) {
mPresenter = presenter;
switch (mState) {
case NOT_STARTED:
start();
break;
case IN_PROGRESS:
if (mPresenter != null) {
mPresenter.onStarted();
}
break;
case DONE:
if (mPresenter != null) {
mPresenter.onDone(mResult);
}
break;
default:
throw new IllegalStateException(String.valueOf(mState));
}
}
/**
* Detaches the provided presentation layer from this controller. Does nothing if the presentation
* layer is not the same as the layer currently attached to the controller.
*/
void detach(Presenter presenter) {
if (presenter != mPresenter) {
return;
}
switch (mState) {
case NOT_STARTED:
case IN_PROGRESS:
onCancelledByUser();
break;
case DONE:
break;
default:
throw new IllegalStateException(String.valueOf(mState));
}
}
/**
* Requests that this controller abort its operation. Does nothing if the provided presentation
* layer is not the same as the layer attached to this controller.
*/
void abort(Presenter presenter) {
if (mPresenter != presenter) {
return;
}
onCancelledByUser();
}
/**
* Starts this controller's operation (initiates a Time Sync).
*/
private void start() {
mState = State.IN_PROGRESS;
if (mPresenter != null) {
mPresenter.onStarted();
}
// Avoid blocking this thread on the Time Sync operation by invoking it on a different thread
// (provided by the Executor) and posting the results back to this thread.
mBackgroundExecutor.execute(new Runnable() {
@Override
public void run() {
runBackgroundSyncAndPostResult(mCallbackFromBackgroundExecutor);
}
});
}
private void onCancelledByUser() {
finish(Result.CANCELLED_BY_USER);
}
/**
* Invoked when the time correction value was successfully obtained from the network time
* provider.
*
* @param timeCorrectionMinutes number of minutes by which this device is behind the correct time.
*/
private void onNewTimeCorrectionObtained(int timeCorrectionMinutes) {
if (mState != State.IN_PROGRESS) {
// Don't apply the new time correction if this controller is not waiting for this.
// This callback may be invoked after the Time Sync operation has been cancelled or stopped
// prematurely.
return;
}
long oldTimeCorrectionMinutes = mTotpClock.getTimeCorrectionMinutes();
Log.i(LOG_TAG, "Obtained new time correction: "
+ timeCorrectionMinutes + " min, old time correction: "
+ oldTimeCorrectionMinutes + " min");
if (timeCorrectionMinutes == oldTimeCorrectionMinutes) {
finish(Result.TIME_ALREADY_CORRECT);
} else {
mTotpClock.setTimeCorrectionMinutes(timeCorrectionMinutes);
finish(Result.TIME_CORRECTED);
}
}
/**
* Terminates this controller's operation with the provided result/outcome.
*/
private void finish(Result result) {
if (mState == State.DONE) {
// Not permitted to change state when already DONE
return;
}
if (mBackgroundExecutorServiceOwnedByThisController) {
((ExecutorService) mBackgroundExecutor).shutdownNow();
}
mState = State.DONE;
mResult = result;
if (mPresenter != null) {
mPresenter.onDone(result);
}
}
/**
* Obtains the time correction value (<b>may block for a while</b>) and posts the result/error
* using the provided {@link Handler}.
*/
private void runBackgroundSyncAndPostResult(Executor callbackExecutor) {
long networkTimeMillis;
try {
networkTimeMillis = mNetworkTimeProvider.getNetworkTime();
} catch (IOException e) {
Log.w(LOG_TAG, "Failed to obtain network time due to connectivity issues");
callbackExecutor.execute(new Runnable() {
@Override
public void run() {
finish(Result.ERROR_CONNECTIVITY_ISSUE);
}
});
return;
}
long timeCorrectionMillis = networkTimeMillis - System.currentTimeMillis();
final int timeCorrectionMinutes = (int) Math.round(
((double) timeCorrectionMillis) / Utilities.MINUTE_IN_MILLIS);
callbackExecutor.execute(new Runnable() {
@Override
public void run() {
onNewTimeCorrectionObtained(timeCorrectionMinutes);
}
});
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/timesync/SyncNowController.java | Java | asf20 | 7,754 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.timesync;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;
import java.io.IOException;
import java.util.Date;
/**
* Provider of network time that obtains the time by making a network request to Google.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class NetworkTimeProvider {
private static final String LOG_TAG = NetworkTimeProvider.class.getSimpleName();
private static final String URL = "https://www.google.com";
private final HttpClient mHttpClient;
public NetworkTimeProvider(HttpClient httpClient) {
mHttpClient = httpClient;
}
/**
* Gets the system time by issuing a request over the network.
*
* @return time (milliseconds since epoch).
*
* @throws IOException if an I/O error occurs.
*/
public long getNetworkTime() throws IOException {
HttpHead request = new HttpHead(URL);
Log.i(LOG_TAG, "Sending request to " + request.getURI());
HttpResponse httpResponse;
try {
httpResponse = mHttpClient.execute(request);
} catch (ClientProtocolException e) {
throw new IOException(String.valueOf(e));
} catch (IOException e) {
throw new IOException("Failed due to connectivity issues: " + e);
}
try {
Header dateHeader = httpResponse.getLastHeader("Date");
Log.i(LOG_TAG, "Received response with Date header: " + dateHeader);
if (dateHeader == null) {
throw new IOException("No Date header in response");
}
String dateHeaderValue = dateHeader.getValue();
try {
Date networkDate = DateUtils.parseDate(dateHeaderValue);
return networkDate.getTime();
} catch (DateParseException e) {
throw new IOException(
"Invalid Date header format in response: \"" + dateHeaderValue + "\"");
}
} finally {
// Consume all of the content of the response to facilitate HTTP 1.1 persistent connection
// reuse and to avoid running out of connections when this methods is scheduled on different
// threads.
try {
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null) {
responseEntity.consumeContent();
}
} catch (IOException e) {
// Ignored because this is not an error that is relevant to clients of this transport.
}
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/timesync/NetworkTimeProvider.java | Java | asf20 | 3,309 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.timesync;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Activity that adjusts the application's internal system time offset (for the purposes of
* computing TOTP verification codes) by making a network request to Google and comparing Google's
* time to the device's time.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SyncNowActivity extends Activity implements SyncNowController.Presenter {
// IMPLEMENTATION NOTE: This class implements a Passive View pattern. All state and business logic
// are kept in the Controller which pushes the relevant state into this Activity. This helps with
// testing the business logic and also with preserving state across the creation/destruction of
// Activity instances due to screen orientation changes. Activity instances being destroyed
// detach from the controller, and new instances being created attach to the controller. Once an
// instance has attached, the controller will set up the Activity into the correct state and will
// continue pushing state changes into the Activity until it detaches.
private SyncNowController mController;
private Dialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getLastNonConfigurationInstance() != null) {
mController = (SyncNowController) getLastNonConfigurationInstance();
} else {
mController = new SyncNowController(
DependencyInjector.getTotpClock(),
new NetworkTimeProvider(DependencyInjector.getHttpClient()));
}
mController.attach(this);
}
@Override
protected void onStop() {
if (isFinishing()) {
mController.detach(this);
}
super.onStop();
}
@Override
public Object onRetainNonConfigurationInstance() {
return mController;
}
@Override
public void onBackPressed() {
mController.abort(this);
}
// --------- SyncNowController.Presenter interface implementation ------
@Override
public void onStarted() {
if (isFinishing()) {
// Ignore this callback if this Activity is already finishing or is already finished
return;
}
showInProgressDialog();
}
@Override
public void onDone(SyncNowController.Result result) {
if (isFinishing()) {
// Ignore this callback if this Activity is already finishing or is already finished
return;
}
dismissInProgressDialog();
switch (result) {
case TIME_ALREADY_CORRECT:
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.timesync_sync_now_time_already_correct_dialog_title)
.setMessage(R.string.timesync_sync_now_time_already_correct_dialog_details)
.setIcon(android.R.drawable.ic_dialog_info)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
break;
case TIME_CORRECTED:
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.timesync_sync_now_time_corrected_dialog_title)
.setMessage(R.string.timesync_sync_now_time_corrected_dialog_details)
.setIcon(android.R.drawable.ic_dialog_info)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
break;
case ERROR_CONNECTIVITY_ISSUE:
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.timesync_sync_now_connectivity_error_dialog_title)
.setMessage(R.string.timesync_sync_now_connectivity_error_dialog_details)
.setIcon(android.R.drawable.ic_dialog_alert)
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
break;
case CANCELLED_BY_USER:
finish();
break;
default:
throw new IllegalArgumentException(String.valueOf(result));
}
}
// --------- SyncNowController.Presenter interface implementation END ------
private void showInProgressDialog() {
mProgressDialog = ProgressDialog.show(
this,
getString(R.string.timesync_sync_now_progress_dialog_title),
getString(R.string.timesync_sync_now_progress_dialog_details),
true,
true);
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
mController.abort(SyncNowActivity.this);
}
});
}
/**
* Dismisses the progress dialog. Does nothing if the dialog has not been or no longer is
* displayed.
*
* @see #showInProgressDialog()
*/
private void dismissInProgressDialog() {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/timesync/SyncNowActivity.java | Java | asf20 | 6,292 |
/*
* 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 com.google.android.apps.authenticator.timesync;
import com.google.android.apps.authenticator.testability.TestablePreferenceActivity;
import com.google.android.apps.authenticator2.R;
import android.os.Bundle;
/**
* Activity that displays the "Time correction" preferences.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SettingsTimeCorrectionActivity extends TestablePreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_time_correction);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/timesync/SettingsTimeCorrectionActivity.java | Java | asf20 | 1,216 |
/*
* 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 com.google.android.apps.authenticator;
import android.os.Handler;
/**
* Task that periodically notifies its listener about the time remaining until the value of a TOTP
* counter changes.
*
* @author klyubin@google.com (Alex Klyubin)
*/
class TotpCountdownTask implements Runnable {
private final TotpCounter mCounter;
private final TotpClock mClock;
private final long mRemainingTimeNotificationPeriod;
private final Handler mHandler = new Handler();
private long mLastSeenCounterValue = Long.MIN_VALUE;
private boolean mShouldStop;
private Listener mListener;
/**
* Listener notified of changes to the time remaining until the counter value changes.
*/
interface Listener {
/**
* Invoked when the time remaining till the TOTP counter changes its value.
*
* @param millisRemaining time (milliseconds) remaining.
*/
void onTotpCountdown(long millisRemaining);
/** Invoked when the TOTP counter changes its value. */
void onTotpCounterValueChanged();
}
/**
* Constructs a new {@code TotpRefreshTask}.
*
* @param counter TOTP counter this task monitors.
* @param clock TOTP clock that drives this task.
* @param remainingTimeNotificationPeriod approximate interval (milliseconds) at which this task
* notifies its listener about the time remaining until the @{code counter} changes its
* value.
*/
TotpCountdownTask(TotpCounter counter, TotpClock clock, long remainingTimeNotificationPeriod) {
mCounter = counter;
mClock = clock;
mRemainingTimeNotificationPeriod = remainingTimeNotificationPeriod;
}
/**
* Sets the listener that this task will periodically notify about the state of the TOTP counter.
*
* @param listener listener or {@code null} for no listener.
*/
void setListener(Listener listener) {
mListener = listener;
}
/**
* Starts this task and immediately notifies the listener that the counter value has changed.
*
* <p>The immediate notification during startup ensures that the listener does not miss any
* updates.
*
* @throws IllegalStateException if the task has already been stopped.
*/
void startAndNotifyListener() {
if (mShouldStop) {
throw new IllegalStateException("Task already stopped and cannot be restarted.");
}
run();
}
/**
* Stops this task. This task will never notify the listener after the task has been stopped.
*/
void stop() {
mShouldStop = true;
}
@Override
public void run() {
if (mShouldStop) {
return;
}
long now = mClock.currentTimeMillis();
long counterValue = getCounterValue(now);
if (mLastSeenCounterValue != counterValue) {
mLastSeenCounterValue = counterValue;
fireTotpCounterValueChanged();
}
fireTotpCountdown(getTimeTillNextCounterValue(now));
scheduleNextInvocation();
}
private void scheduleNextInvocation() {
long now = mClock.currentTimeMillis();
long counterValueAge = getCounterValueAge(now);
long timeTillNextInvocation =
mRemainingTimeNotificationPeriod - (counterValueAge % mRemainingTimeNotificationPeriod);
mHandler.postDelayed(this, timeTillNextInvocation);
}
private void fireTotpCountdown(long timeRemaining) {
if ((mListener != null) && (!mShouldStop)) {
mListener.onTotpCountdown(timeRemaining);
}
}
private void fireTotpCounterValueChanged() {
if ((mListener != null) && (!mShouldStop)) {
mListener.onTotpCounterValueChanged();
}
}
/**
* Gets the value of the counter at the specified time instant.
*
* @param time time instant (milliseconds since epoch).
*/
private long getCounterValue(long time) {
return mCounter.getValueAtTime(Utilities.millisToSeconds(time));
}
/**
* Gets the time remaining till the counter assumes its next value.
*
* @param time time instant (milliseconds since epoch) for which to perform the query.
*
* @return time (milliseconds) till next value.
*/
private long getTimeTillNextCounterValue(long time) {
long currentValue = getCounterValue(time);
long nextValue = currentValue + 1;
long nextValueStartTime = Utilities.secondsToMillis(mCounter.getValueStartTime(nextValue));
return nextValueStartTime - time;
}
/**
* Gets the age of the counter value at the specified time instant.
*
* @param time time instant (milliseconds since epoch).
*
* @return age (milliseconds).
*/
private long getCounterValueAge(long time) {
return time - Utilities.secondsToMillis(mCounter.getValueStartTime(getCounterValue(time)));
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/TotpCountdownTask.java | Java | asf20 | 5,267 |
/*
* 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import android.app.Application;
/**
* Authenticator application which is one of the first things instantiated when our process starts.
* At the moment the only reason for the existence of this class is to initialize
* {@link DependencyInjector} with the application context so that the class can (later) instantiate
* the various objects it owns.
*
* Also restrict UNIX file permissions on application's persistent data directory to owner
* (this app's UID) only.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class AuthenticatorApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Try to restrict data dir file permissions to owner (this app's UID) only. This mitigates the
// security vulnerability where SQLite database transaction journals are world-readable.
// NOTE: This also prevents all files in the data dir from being world-accessible, which is fine
// because this application does not need world-accessible files.
try {
FileUtilities.restrictAccessToOwnerOnly(
getApplicationContext().getApplicationInfo().dataDir);
} catch (Throwable e) {
// Ignore this exception and don't log anything to avoid attracting attention to this fix
}
// During test runs the injector may have been configured already. Thus we take care to avoid
// overwriting any existing configuration here.
DependencyInjector.configureForProductionIfNotConfigured(getApplicationContext());
}
@Override
public void onTerminate() {
DependencyInjector.close();
super.onTerminate();
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/AuthenticatorApplication.java | Java | asf20 | 2,355 |
/*
* Copyright 2009 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 com.google.android.apps.authenticator;
import java.util.HashMap;
import java.util.Locale;
/**
* Encodes arbitrary byte arrays as case-insensitive base-32 strings.
* <p>
* The implementation is slightly different than in RFC 4648. During encoding,
* padding is not added, and during decoding the last incomplete chunk is not
* taken into account. The result is that multiple strings decode to the same
* byte array, for example, string of sixteen 7s ("7...7") and seventeen 7s both
* decode to the same byte array.
* TODO(sarvar): Revisit this encoding and whether this ambiguity needs fixing.
*
* @author sweis@google.com (Steve Weis)
* @author Neal Gafter
*/
public class Base32String {
// singleton
private static final Base32String INSTANCE =
new Base32String("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); // RFC 4648/3548
static Base32String getInstance() {
return INSTANCE;
}
// 32 alpha-numeric characters.
private String ALPHABET;
private char[] DIGITS;
private int MASK;
private int SHIFT;
private HashMap<Character, Integer> CHAR_MAP;
static final String SEPARATOR = "-";
protected Base32String(String alphabet) {
this.ALPHABET = alphabet;
DIGITS = ALPHABET.toCharArray();
MASK = DIGITS.length - 1;
SHIFT = Integer.numberOfTrailingZeros(DIGITS.length);
CHAR_MAP = new HashMap<Character, Integer>();
for (int i = 0; i < DIGITS.length; i++) {
CHAR_MAP.put(DIGITS[i], i);
}
}
public static byte[] decode(String encoded) throws DecodingException {
return getInstance().decodeInternal(encoded);
}
protected byte[] decodeInternal(String encoded) throws DecodingException {
// Remove whitespace and separators
encoded = encoded.trim().replaceAll(SEPARATOR, "").replaceAll(" ", "");
// Remove padding. Note: the padding is used as hint to determine how many
// bits to decode from the last incomplete chunk (which is commented out
// below, so this may have been wrong to start with).
encoded = encoded.replaceFirst("[=]*$", "");
// Canonicalize to all upper case
encoded = encoded.toUpperCase(Locale.US);
if (encoded.length() == 0) {
return new byte[0];
}
int encodedLength = encoded.length();
int outLength = encodedLength * SHIFT / 8;
byte[] result = new byte[outLength];
int buffer = 0;
int next = 0;
int bitsLeft = 0;
for (char c : encoded.toCharArray()) {
if (!CHAR_MAP.containsKey(c)) {
throw new DecodingException("Illegal character: " + c);
}
buffer <<= SHIFT;
buffer |= CHAR_MAP.get(c) & MASK;
bitsLeft += SHIFT;
if (bitsLeft >= 8) {
result[next++] = (byte) (buffer >> (bitsLeft - 8));
bitsLeft -= 8;
}
}
// We'll ignore leftover bits for now.
//
// if (next != outLength || bitsLeft >= SHIFT) {
// throw new DecodingException("Bits left: " + bitsLeft);
// }
return result;
}
public static String encode(byte[] data) {
return getInstance().encodeInternal(data);
}
protected String encodeInternal(byte[] data) {
if (data.length == 0) {
return "";
}
// SHIFT is the number of bits per output character, so the length of the
// output is the length of the input multiplied by 8/SHIFT, rounded up.
if (data.length >= (1 << 28)) {
// The computation below will fail, so don't do it.
throw new IllegalArgumentException();
}
int outputLength = (data.length * 8 + SHIFT - 1) / SHIFT;
StringBuilder result = new StringBuilder(outputLength);
int buffer = data[0];
int next = 1;
int bitsLeft = 8;
while (bitsLeft > 0 || next < data.length) {
if (bitsLeft < SHIFT) {
if (next < data.length) {
buffer <<= 8;
buffer |= (data[next++] & 0xff);
bitsLeft += 8;
} else {
int pad = SHIFT - bitsLeft;
buffer <<= pad;
bitsLeft += pad;
}
}
int index = MASK & (buffer >> (bitsLeft - SHIFT));
bitsLeft -= SHIFT;
result.append(DIGITS[index]);
}
return result.toString();
}
@Override
// enforce that this class is a singleton
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public static class DecodingException extends Exception {
public DecodingException(String message) {
super(message);
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/Base32String.java | Java | asf20 | 5,058 |
/*
* 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 com.google.android.apps.authenticator;
/**
* Counter whose value is a deterministic function of time as described in RFC 6238
* "TOTP: Time-Based One-Time Password Algorithm".
*
* <p>The 64-bit counter assumes the value {@code 0} at a predefined point in time and periodically
* increments its value by one periodically.
*
* <p>The value {@code V} of the counter at time instant {@code T} is:
* <pre>
* V = (T - T0) / TimeStep
* </pre>
* where {@code T0} is the earliest time instant at which the counter assumes the value {@code 0},
* and {@code TimeStep} is the duration of time for which the values of the counter remain constant.
*
* <p><em>Note: All time instants are in seconds since UNIX epoch, and all time durations are
* in seconds.</em>
*
* <p><em>Note: All time instants must be non-negative.</em>
*
* <p>Thread-safety: Instances of this class are immutable and are thus thread-safe.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class TotpCounter {
/** Interval of time (seconds) between successive changes of this counter's value. */
private final long mTimeStep;
/**
* Earliest time instant (seconds since UNIX epoch) at which this counter assumes the value of
* {@code 0}.
*/
private final long mStartTime;
/**
* Constructs a new {@code TotpCounter} that starts with the value {@code 0} at time instant
* {@code 0} (seconds since UNIX epoch) and increments its value with the specified frequency.
*
* @param timeStep interval of time (seconds) between successive changes of this counter's value.
*/
public TotpCounter(long timeStep) {
this(timeStep, 0);
}
/**
* Constructs a new {@code TotpCounter} that starts with the value {@code 0} at the specified
* time and increments its value with the specified frequency.
*
* @param timeStep interval of time (seconds) between successive changes of this counter's value.
* @param startTime the earliest time instant (seconds since UNIX epoch) at which this counter
* assumes the value {@code 0}.
*/
public TotpCounter(long timeStep, long startTime) {
if (timeStep < 1) {
throw new IllegalArgumentException("Time step must be positive: " + timeStep);
}
assertValidTime(startTime);
mTimeStep = timeStep;
mStartTime = startTime;
}
/**
* Gets the frequency with which the value of this counter changes.
*
* @return interval of time (seconds) between successive changes of this counter's value.
*/
public long getTimeStep() {
return mTimeStep;
}
/**
* Gets the earliest time instant at which this counter assumes the value {@code 0}.
*
* @return time (seconds since UNIX epoch).
*/
public long getStartTime() {
return mStartTime;
}
/**
* Gets the value of this counter at the specified time.
*
* @param time time instant (seconds since UNIX epoch) for which to obtain the value.
*
* @return value of the counter at the {@code time}.
*/
public long getValueAtTime(long time) {
assertValidTime(time);
// According to the RFC:
// T = (Current Unix time - T0) / X, where the default floor function is used.
// T - counter value,
// T0 - start time.
// X - time step.
// It's important to use a floor function instead of simple integer division. For example,
// assuming a time step of 3:
// Time since start time: -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6
// Correct value: -2 -2 -2 -1 -1 -1 0 0 0 1 1 1 2
// Simple division / 3: -2 -1 -1 -1 0 0 0 0 0 1 1 1 2
//
// To avoid using Math.floor which requires imprecise floating-point arithmetic, we
// we compute the value using integer division, but using a different equation for
// negative and non-negative time since start time.
long timeSinceStartTime = time - mStartTime;
if (timeSinceStartTime >= 0) {
return timeSinceStartTime / mTimeStep;
} else {
return (timeSinceStartTime - (mTimeStep - 1)) / mTimeStep;
}
}
/**
* Gets the time when the counter assumes the specified value.
*
* @param value value.
*
* @return earliest time instant (seconds since UNIX epoch) when the counter assumes the value.
*/
public long getValueStartTime(long value) {
return mStartTime + (value * mTimeStep);
}
private static void assertValidTime(long time) {
if (time < 0) {
throw new IllegalArgumentException("Negative time: " + time);
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/TotpCounter.java | Java | asf20 | 5,134 |
/*
* Copyright 2010 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 com.google.android.apps.authenticator;
import java.util.Collection;
/**
* Abstraction for collection of OTP tokens.
*
* @author cemp@google.com (Cem Paya)
*/
public interface OtpSource {
/**
* Enumerate list of accounts that this OTP token supports.
*
* @param result Collection to append usernames. This object is NOT cleared on
* entry; if there are existing items, they will not be removed.
* @return Number of accounts added to the collection.
*/
int enumerateAccounts(Collection<String> result);
/**
* Return the next OTP code for specified username.
* Invoking this function may change internal state of the OTP generator,
* for example advancing the counter.
*
* @param accountName Username, email address or other unique identifier for the account.
* @return OTP as string code.
*/
String getNextCode(String accountName) throws OtpSourceException;
/**
* Generate response to a given challenge based on next OTP code.
* Subclasses are not required to implement this method.
*
* @param accountName Username, email address or other unique identifier for the account.
* @param challenge Server specified challenge as UTF8 string.
* @return Response to the challenge.
* @throws UnsupportedOperationException if the token does not support
* challenge-response extension for this account.
*/
String respondToChallenge(String accountName, String challenge) throws OtpSourceException;
/**
* Gets the counter for generating or verifying TOTP codes.
*/
TotpCounter getTotpCounter();
/**
* Gets the clock for generating or verifying TOTP codes.
*/
TotpClock getTotpClock();
}
| zzhyjun- | src/com/google/android/apps/authenticator/OtpSource.java | Java | asf20 | 2,328 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
import android.os.Handler;
import java.util.concurrent.Executor;
/**
* {@link Executor} that invokes {@link Runnable} instances on the thread on which it was created.
* The assumption is that the thread has a {@link android.os.Looper} associated with it.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class RunOnThisLooperThreadExecutor implements Executor {
private final Handler mHandler = new Handler();
@Override
public void execute(Runnable command) {
if (Thread.currentThread() == mHandler.getLooper().getThread()) {
// The calling thread is the target thread of the Handler -- invoke immediately, blocking
// the calling thread.
command.run();
} else {
// The calling thread is not the same as the thread with which the Handler is associated --
// post to the Handler for later execution.
mHandler.post(command);
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/RunOnThisLooperThreadExecutor.java | Java | asf20 | 1,566 |
/*
* 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 com.google.android.apps.authenticator;
/**
* Simple static methods to be called at the start of your own methods to verify correct arguments
* and state. Inspired by Guava.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public final class Preconditions {
/** Hidden to avoid instantiation. */
private Preconditions() {}
/**
* Ensures that an object reference passed as a parameter to the calling method is not
* {@code null}.
*
* @return non-{@code null} reference that was validated.
*
* @throws NullPointerException if {@code reference} is {@code null}.
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @throws IllegalArgumentException if {@code expression} is {@code false}.
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(
boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/Preconditions.java | Java | asf20 | 2,625 |
/*
* 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 com.google.android.apps.authenticator;
import java.io.IOException;
/**
* A class for handling file system related methods, such as setting permissions.
*
* @author sarvar@google.com (Sarvar Patel)
*/
public class FileUtilities {
/** Hidden constructor to prevent instantiation. */
private FileUtilities() { }
/**
* Restricts the file permissions of the provided path so that only the owner (UID)
* can access it.
*/
public static void restrictAccessToOwnerOnly(String path) throws IOException {
// IMPLEMENTATION NOTE: The code below simply invokes the hidden API
// android.os.FileUtils.setPermissions(path, 0700, -1, -1) via Reflection.
int errorCode;
try {
errorCode = (Integer) Class.forName("android.os.FileUtils")
.getMethod("setPermissions", String.class, int.class, int.class, int.class)
.invoke(null, path, 0700, -1, -1);
} catch (Exception e) {
// Can't chain exception because IOException doesn't have the right constructor on Froyo
// and below
throw new IOException("Failed to set permissions: " + e);
}
if (errorCode != 0) {
throw new IOException("FileUtils.setPermissions failed with error code " + errorCode);
}
}
/*
* Uses reflection to call android.os.FileUtils.getFileStatus(path) which returns FileStatus.
*/
public static StatStruct getStat(String path) throws IOException {
boolean success;
try {
Object obj = Class.forName("android.os.FileUtils$FileStatus").newInstance();
success = (Boolean) Class.forName("android.os.FileUtils")
.getMethod("getFileStatus", String.class,
Class.forName("android.os.FileUtils$FileStatus"))
.invoke(null, path, obj);
if (success) {
StatStruct stat = new StatStruct();
stat.dev = getFileStatusInt(obj, "dev");
stat.ino = getFileStatusInt(obj, "ino");
stat.mode = getFileStatusInt(obj, "mode");
stat.nlink = getFileStatusInt(obj, "nlink");
stat.uid = getFileStatusInt(obj, "uid");
stat.gid = getFileStatusInt(obj, "gid");
stat.rdev = getFileStatusInt(obj, "rdev");
stat.size = getFileStatusLong(obj, "size");
stat.blksize = getFileStatusInt(obj, "blksize");
stat.blocks = getFileStatusLong(obj, "blocks");
stat.atime = getFileStatusLong(obj, "atime");
stat.mtime = getFileStatusLong(obj, "mtime");
stat.ctime = getFileStatusLong(obj, "ctime");
return stat;
} else {
throw new IOException("FileUtils.getFileStatus returned with failure.");
}
} catch (Exception e) {
// Can't chain exception because IOException doesn't have the right constructor on Froyo
// and below
throw new IOException("Failed to get FileStatus: " + e);
}
}
private static int getFileStatusInt(Object obj, String field) throws IllegalArgumentException,
IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
return Class.forName("android.os.FileUtils$FileStatus").getField(field).getInt(obj);
}
private static long getFileStatusLong(Object obj, String field) throws IllegalArgumentException,
IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
return Class.forName("android.os.FileUtils$FileStatus").getField(field).getLong(obj);
}
public static class StatStruct {
public int dev;
public int ino;
public int mode;
public int nlink;
public int uid;
public int gid;
public int rdev;
public long size;
public int blksize;
public long blocks;
public long atime;
public long mtime;
public long ctime;
@Override
public String toString() {
return new String(String.format("StatStruct{ dev: %d, ino: %d, mode: %o (octal), nlink: %d, "
+ "uid: %d, gid: %d, rdev: %d, size: %d, blksize: %d, blocks: %d, atime: %d, mtime: %d, "
+ "ctime: %d }\n",
dev, ino, mode, nlink, uid, gid, rdev, size, blksize, blocks, atime, mtime, ctime));
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/FileUtilities.java | Java | asf20 | 4,697 |
/*
* Copyright 2010 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator.Base32String.DecodingException;
import com.google.android.apps.authenticator.PasscodeGenerator.Signer;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Process;
import android.util.Log;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* A database of email addresses and secret values
*
* @author sweis@google.com (Steve Weis)
*/
public class AccountDb {
public static final Integer DEFAULT_HOTP_COUNTER = 0;
public static final String GOOGLE_CORP_ACCOUNT_NAME = "Google Internal 2Factor";
private static final String ID_COLUMN = "_id";
private static final String EMAIL_COLUMN = "email";
private static final String SECRET_COLUMN = "secret";
private static final String COUNTER_COLUMN = "counter";
private static final String TYPE_COLUMN = "type";
// @VisibleForTesting
static final String PROVIDER_COLUMN = "provider";
// @VisibleForTesting
static final String TABLE_NAME = "accounts";
// @VisibleForTesting
static final String PATH = "databases";
private static final String TABLE_INFO_COLUMN_NAME_COLUMN = "name";
private static final int PROVIDER_UNKNOWN = 0;
private static final int PROVIDER_GOOGLE = 1;
// @VisibleForTesting
SQLiteDatabase mDatabase;
private static final String LOCAL_TAG = "GoogleAuthenticator.AccountDb";
/**
* Types of secret keys.
*/
public enum OtpType { // must be the same as in res/values/strings.xml:type
TOTP (0), // time based
HOTP (1); // counter based
public final Integer value; // value as stored in SQLite database
OtpType(Integer value) {
this.value = value;
}
public static OtpType getEnum(Integer i) {
for (OtpType type : OtpType.values()) {
if (type.value.equals(i)) {
return type;
}
}
return null;
}
}
public AccountDb(Context context) {
mDatabase = openDatabase(context);
// Create the table if it doesn't exist
mDatabase.execSQL(String.format(
"CREATE TABLE IF NOT EXISTS %s" +
" (%s INTEGER PRIMARY KEY, %s TEXT NOT NULL, %s TEXT NOT NULL, " +
" %s INTEGER DEFAULT %s, %s INTEGER, %s INTEGER DEFAULT %s)",
TABLE_NAME, ID_COLUMN, EMAIL_COLUMN, SECRET_COLUMN, COUNTER_COLUMN,
DEFAULT_HOTP_COUNTER, TYPE_COLUMN,
PROVIDER_COLUMN, PROVIDER_UNKNOWN));
Collection<String> tableColumnNames = listTableColumnNamesLowerCase();
if (!tableColumnNames.contains(PROVIDER_COLUMN.toLowerCase(Locale.US))) {
// Migrate from old schema where the PROVIDER_COLUMN wasn't there
mDatabase.execSQL(String.format(
"ALTER TABLE %s ADD COLUMN %s INTEGER DEFAULT %s",
TABLE_NAME, PROVIDER_COLUMN, PROVIDER_UNKNOWN));
}
}
/*
* Tries three times to open database before throwing AccountDbOpenException.
*/
private SQLiteDatabase openDatabase(Context context) {
for (int count = 0; true; count++) {
try {
return context.openOrCreateDatabase(PATH, Context.MODE_PRIVATE, null);
} catch (SQLiteException e) {
if (count < 2) {
continue;
} else {
throw new AccountDbOpenException("Failed to open AccountDb database in three tries.\n"
+ getAccountDbOpenFailedErrorString(context), e);
}
}
}
}
private String getAccountDbOpenFailedErrorString(Context context) {
String dataPackageDir = context.getApplicationInfo().dataDir;
String databaseDirPathname = context.getDatabasePath(PATH).getParent();
String databasePathname = context.getDatabasePath(PATH).getAbsolutePath();
String[] dirsToStat = new String[] {dataPackageDir, databaseDirPathname, databasePathname};
StringBuilder error = new StringBuilder();
int myUid = Process.myUid();
for (String directory : dirsToStat) {
try {
FileUtilities.StatStruct stat = FileUtilities.getStat(directory);
String ownerUidName = null;
try {
if (stat.uid == 0) {
ownerUidName = "root";
} else {
PackageManager packageManager = context.getPackageManager();
ownerUidName = (packageManager != null) ? packageManager.getNameForUid(stat.uid) : null;
}
} catch (Exception e) {
ownerUidName = e.toString();
}
error.append(directory + " directory stat (my UID: " + myUid);
if (ownerUidName == null) {
error.append("): ");
} else {
error.append(", dir owner UID name: " + ownerUidName + "): ");
}
error.append(stat.toString() + "\n");
} catch (IOException e) {
error.append(directory + " directory stat threw an exception: " + e + "\n");
}
}
return error.toString();
}
/**
* Closes this database and releases any system resources held.
*/
public void close() {
mDatabase.close();
}
/**
* Lists the names of all the columns in the specified table.
*/
// @VisibleForTesting
static Collection<String> listTableColumnNamesLowerCase(
SQLiteDatabase database, String tableName) {
Cursor cursor =
database.rawQuery(String.format("PRAGMA table_info(%s)", tableName), new String[0]);
Collection<String> result = new ArrayList<String>();
try {
if (cursor != null) {
int nameColumnIndex = cursor.getColumnIndexOrThrow(TABLE_INFO_COLUMN_NAME_COLUMN);
while (cursor.moveToNext()) {
result.add(cursor.getString(nameColumnIndex).toLowerCase(Locale.US));
}
}
return result;
} finally {
tryCloseCursor(cursor);
}
}
/**
* Lists the names of all the columns in the accounts table.
*/
private Collection<String> listTableColumnNamesLowerCase() {
return listTableColumnNamesLowerCase(mDatabase, TABLE_NAME);
}
/*
* deleteAllData() will remove all rows. Useful for testing.
*/
public boolean deleteAllData() {
mDatabase.delete(AccountDb.TABLE_NAME, null, null);
return true;
}
public boolean nameExists(String email) {
Cursor cursor = getAccount(email);
try {
return !cursorIsEmpty(cursor);
} finally {
tryCloseCursor(cursor);
}
}
public String getSecret(String email) {
Cursor cursor = getAccount(email);
try {
if (!cursorIsEmpty(cursor)) {
cursor.moveToFirst();
return cursor.getString(cursor.getColumnIndex(SECRET_COLUMN));
}
} finally {
tryCloseCursor(cursor);
}
return null;
}
static Signer getSigningOracle(String secret) {
try {
byte[] keyBytes = decodeKey(secret);
final Mac mac = Mac.getInstance("HMACSHA1");
mac.init(new SecretKeySpec(keyBytes, ""));
// Create a signer object out of the standard Java MAC implementation.
return new Signer() {
@Override
public byte[] sign(byte[] data) {
return mac.doFinal(data);
}
};
} catch (DecodingException error) {
Log.e(LOCAL_TAG, error.getMessage());
} catch (NoSuchAlgorithmException error) {
Log.e(LOCAL_TAG, error.getMessage());
} catch (InvalidKeyException error) {
Log.e(LOCAL_TAG, error.getMessage());
}
return null;
}
private static byte[] decodeKey(String secret) throws DecodingException {
return Base32String.decode(secret);
}
public Integer getCounter(String email) {
Cursor cursor = getAccount(email);
try {
if (!cursorIsEmpty(cursor)) {
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(COUNTER_COLUMN));
}
} finally {
tryCloseCursor(cursor);
}
return null;
}
void incrementCounter(String email) {
ContentValues values = new ContentValues();
values.put(EMAIL_COLUMN, email);
Integer counter = getCounter(email);
values.put(COUNTER_COLUMN, counter + 1);
mDatabase.update(TABLE_NAME, values, whereClause(email), null);
}
public OtpType getType(String email) {
Cursor cursor = getAccount(email);
try {
if (!cursorIsEmpty(cursor)) {
cursor.moveToFirst();
Integer value = cursor.getInt(cursor.getColumnIndex(TYPE_COLUMN));
return OtpType.getEnum(value);
}
} finally {
tryCloseCursor(cursor);
}
return null;
}
void setType(String email, OtpType type) {
ContentValues values = new ContentValues();
values.put(EMAIL_COLUMN, email);
values.put(TYPE_COLUMN, type.value);
mDatabase.update(TABLE_NAME, values, whereClause(email), null);
}
public boolean isGoogleAccount(String email) {
Cursor cursor = getAccount(email);
try {
if (!cursorIsEmpty(cursor)) {
cursor.moveToFirst();
if (cursor.getInt(cursor.getColumnIndex(PROVIDER_COLUMN)) == PROVIDER_GOOGLE) {
// The account is marked as source: Google
return true;
}
// The account is from an unknown source. Could be a Google account added by scanning
// a QR code or by manually entering a key
String emailLowerCase = email.toLowerCase(Locale.US);
return(emailLowerCase.endsWith("@gmail.com"))
|| (emailLowerCase.endsWith("@google.com"))
|| (email.equals(GOOGLE_CORP_ACCOUNT_NAME));
}
} finally {
tryCloseCursor(cursor);
}
return false;
}
/**
* Finds the Google corp account in this database.
*
* @return the name of the account if it is present or {@code null} if the account does not exist.
*/
public String findGoogleCorpAccount() {
return nameExists(GOOGLE_CORP_ACCOUNT_NAME) ? GOOGLE_CORP_ACCOUNT_NAME : null;
}
private static String whereClause(String email) {
return EMAIL_COLUMN + " = " + DatabaseUtils.sqlEscapeString(email);
}
public void delete(String email) {
mDatabase.delete(TABLE_NAME, whereClause(email), null);
}
/**
* Save key to database, creating a new user entry if necessary.
* @param email the user email address. When editing, the new user email.
* @param secret the secret key.
* @param oldEmail If editing, the original user email, otherwise null.
* @param type hotp vs totp
* @param counter only important for the hotp type
*/
public void update(String email, String secret, String oldEmail,
OtpType type, Integer counter) {
update(email, secret, oldEmail, type, counter, null);
}
/**
* Save key to database, creating a new user entry if necessary.
* @param email the user email address. When editing, the new user email.
* @param secret the secret key.
* @param oldEmail If editing, the original user email, otherwise null.
* @param type hotp vs totp
* @param counter only important for the hotp type
* @param googleAccount whether the key is for a Google account or {@code null} to preserve
* the previous value (or use a default if adding a key).
*/
public void update(String email, String secret, String oldEmail,
OtpType type, Integer counter, Boolean googleAccount) {
ContentValues values = new ContentValues();
values.put(EMAIL_COLUMN, email);
values.put(SECRET_COLUMN, secret);
values.put(TYPE_COLUMN, type.ordinal());
values.put(COUNTER_COLUMN, counter);
if (googleAccount != null) {
values.put(
PROVIDER_COLUMN,
(googleAccount.booleanValue()) ? PROVIDER_GOOGLE : PROVIDER_UNKNOWN);
}
int updated = mDatabase.update(TABLE_NAME, values,
whereClause(oldEmail), null);
if (updated == 0) {
mDatabase.insert(TABLE_NAME, null, values);
}
}
private Cursor getNames() {
return mDatabase.query(TABLE_NAME, null, null, null, null, null, null, null);
}
private Cursor getAccount(String email) {
return mDatabase.query(TABLE_NAME, null, EMAIL_COLUMN + "= ?",
new String[] {email}, null, null, null);
}
/**
* Returns true if the cursor is null, or contains no rows.
*/
private static boolean cursorIsEmpty(Cursor c) {
return c == null || c.getCount() == 0;
}
/**
* Closes the cursor if it is not null and not closed.
*/
private static void tryCloseCursor(Cursor c) {
if (c != null && !c.isClosed()) {
c.close();
}
}
/**
* Get list of all account names.
* @param result Collection of strings-- account names are appended, without
* clearing this collection on entry.
* @return Number of accounts added to the output parameter.
*/
public int getNames(Collection<String> result) {
Cursor cursor = getNames();
try {
if (cursorIsEmpty(cursor))
return 0;
int nameCount = cursor.getCount();
int index = cursor.getColumnIndex(AccountDb.EMAIL_COLUMN);
for (int i = 0; i < nameCount; ++i) {
cursor.moveToPosition(i);
String username = cursor.getString(index);
result.add(username);
}
return nameCount;
} finally {
tryCloseCursor(cursor);
}
}
private static class AccountDbOpenException extends RuntimeException {
public AccountDbOpenException(String message, Exception e) {
super(message, e);
}
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/AccountDb.java | Java | asf20 | 14,285 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
/**
* Indicates that {@link OtpSource} failed to generate an OTP because OTP generation is not
* permitted for the specified account.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class OtpGenerationNotPermittedException extends OtpSourceException {
public OtpGenerationNotPermittedException(String message) {
super(message);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/OtpGenerationNotPermittedException.java | Java | asf20 | 1,018 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator;
/**
* Indicates that {@link OtpSource} failed to performed the requested operation.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class OtpSourceException extends Exception {
public OtpSourceException(String message) {
super(message);
}
public OtpSourceException(String message, Throwable cause) {
super(message, cause);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/OtpSourceException.java | Java | asf20 | 1,021 |
/*
* Copyright 2010 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 com.google.android.apps.authenticator;
import com.google.android.apps.authenticator2.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Custom view that shows the user, pin, and "Get New Code" button (if enabled).
* The layout for this is under res/layout/user_row.xml
* For better accessibility, we have created this custom class to generate
* accessibility events that are better suited for this widget.
*
* @author clchen@google.com (Charles L. Chen)
*/
public class UserRowView extends LinearLayout {
public UserRowView(Context context) {
super(context);
}
public UserRowView(Context context, AttributeSet attrset) {
super(context, attrset);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent accessEvent) {
Context ctx = this.getContext();
String message = "";
CharSequence pinText = ((TextView) findViewById(R.id.pin_value)).getText();
if (ctx.getString(R.string.empty_pin).equals(pinText)){
message = ctx.getString(R.string.counter_pin);
} else {
for (int i = 0; i < pinText.length(); i++) {
message = message + pinText.charAt(i) + " ";
}
}
CharSequence userText = ((TextView) findViewById(R.id.current_user)).getText();
message = message + " " + userText;
accessEvent.setClassName(getClass().getName());
accessEvent.setPackageName(ctx.getPackageName());
accessEvent.getText().add(message);
return true;
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/UserRowView.java | Java | asf20 | 2,237 |
/*
* 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 com.google.android.apps.authenticator.testability;
import com.google.android.apps.authenticator.AccountDb;
import com.google.android.apps.authenticator.AuthenticatorActivity;
import com.google.android.apps.authenticator.MarketBuildOptionalFeatures;
import com.google.android.apps.authenticator.OptionalFeatures;
import com.google.android.apps.authenticator.OtpSource;
import com.google.android.apps.authenticator.TotpClock;
import com.google.android.apps.authenticator.dataimport.ExportServiceBasedImportController;
import com.google.android.apps.authenticator.dataimport.ImportController;
import android.content.Context;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.test.RenamingDelegatingContext;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
/**
* Dependency injector that decouples the clients of various objects from their
* creators/constructors and enables the injection of these objects for testing purposes.
*
* <p>The injector is singleton. It needs to be configured for production or test use using
* {@link #configureForProductionIfNotConfigured(Context)} or
* {@link #resetForIntegrationTesting(Context)}.
* After that its clients can access the various objects such as {@link AccountDb} using the
* respective getters (e.g., {@link #getAccountDb()}.
*
* <p>When testing, this class provides the means to inject different implementations of the
* injectable objects (e.g., {@link #setAccountDb(AccountDb) setAccountDb}). To avoid inter-test
* state-leakage, each test should invoke {@link #resetForIntegrationTesting(Context)}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public final class DependencyInjector {
private static Context sContext;
private static AccountDb sAccountDb;
private static OtpSource sOtpProvider;
private static TotpClock sTotpClock;
private static PackageManager sPackageManager;
private static StartActivityListener sStartActivityListener;
private static HttpClient sHttpClient;
private static ImportController sImportController;
private static OptionalFeatures sOptionalFeatures;
private enum Mode {
PRODUCTION,
INTEGRATION_TEST,
}
private static Mode sMode;
private DependencyInjector() {}
/**
* Gets the {@link Context} passed the instances created by this injector.
*/
public static synchronized Context getContext() {
if (sContext == null) {
throw new IllegalStateException("Context not set");
}
return sContext;
}
/**
* Sets the {@link AccountDb} instance returned by this injector. This will prevent the injector
* from creating its own instance.
*/
public static synchronized void setAccountDb(AccountDb accountDb) {
if (sAccountDb != null) {
sAccountDb.close();
}
sAccountDb = accountDb;
}
public static synchronized AccountDb getAccountDb() {
if (sAccountDb == null) {
sAccountDb = new AccountDb(getContext());
if (sMode != Mode.PRODUCTION) {
sAccountDb.deleteAllData();
}
}
return sAccountDb;
}
/**
* Sets the {@link OtpSource} instance returned by this injector. This will prevent the injector
* from creating its own instance.
*/
public static synchronized void setOtpProvider(OtpSource otpProvider) {
sOtpProvider = otpProvider;
}
public static synchronized OtpSource getOtpProvider() {
if (sOtpProvider == null) {
sOtpProvider = getOptionalFeatures().createOtpSource(getAccountDb(), getTotpClock());
}
return sOtpProvider;
}
/**
* Sets the {@link TotpClock} instance returned by this injector. This will prevent the injector
* from creating its own instance.
*/
public static synchronized void setTotpClock(TotpClock totpClock) {
sTotpClock = totpClock;
}
public static synchronized TotpClock getTotpClock() {
if (sTotpClock == null) {
sTotpClock = new TotpClock(getContext());
}
return sTotpClock;
}
/**
* Sets the {@link PackageManager} instance returned by this injector. This will prevent the
* injector from creating its own instance.
*/
public static synchronized void setPackageManager(PackageManager packageManager) {
sPackageManager = packageManager;
}
public static synchronized PackageManager getPackageManager() {
if (sPackageManager == null) {
sPackageManager = getContext().getPackageManager();
}
return sPackageManager;
}
/**
* Sets the {@link StartActivityListener} instance returned by this injector.
*/
public static synchronized void setStartActivityListener(StartActivityListener listener) {
sStartActivityListener = listener;
}
public static synchronized StartActivityListener getStartActivityListener() {
// Don't create an instance on demand -- the default behavior when the listener is null is to
// proceed with launching activities.
return sStartActivityListener;
}
/**
* Sets the {@link ImportController} instance returned by this injector. This will prevent the
* injector from creating its own instance.
*/
public static synchronized void setDataImportController(ImportController importController) {
sImportController = importController;
}
public static synchronized ImportController getDataImportController() {
if (sImportController == null) {
if (sMode == Mode.PRODUCTION) {
sImportController = new ExportServiceBasedImportController();
} else {
// By default, use a no-op controller during tests to avoid them being dependent on the
// presence of the "old" app on the device under test.
sImportController = new ImportController() {
@Override
public void start(Context context, Listener listener) {}
};
}
}
return sImportController;
}
/**
* Sets the {@link HttpClient} instance returned by this injector. This will prevent the
* injector from creating its own instance.
*/
public static synchronized void setHttpClient(HttpClient httpClient) {
sHttpClient = httpClient;
}
public static synchronized HttpClient getHttpClient() {
if (sHttpClient == null) {
sHttpClient = HttpClientFactory.createHttpClient(getContext());
}
return sHttpClient;
}
public static synchronized void setOptionalFeatures(OptionalFeatures optionalFeatures) {
sOptionalFeatures = optionalFeatures;
}
public static synchronized OptionalFeatures getOptionalFeatures() {
if (sOptionalFeatures == null) {
try {
Class<?> resultClass = Class.forName(
AuthenticatorActivity.class.getPackage().getName() + ".NonMarketBuildOptionalFeatures");
try {
sOptionalFeatures = (OptionalFeatures) resultClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to instantiate optional features module", e);
}
} catch (ClassNotFoundException e) {
sOptionalFeatures = new MarketBuildOptionalFeatures();
}
}
return sOptionalFeatures;
}
/**
* Clears any state and configures this injector for production use. Does nothing if the injector
* is already configured.
*/
public static synchronized void configureForProductionIfNotConfigured(Context context) {
if (sMode != null) {
return;
}
close();
sMode = Mode.PRODUCTION;
sContext = context;
}
/**
* Clears any state and configures this injector to provide objects that are suitable for
* integration testing.
*/
// @VisibleForTesting
public static synchronized void resetForIntegrationTesting(Context context) {
if (context == null) {
throw new NullPointerException("context == null");
}
close();
sMode = Mode.INTEGRATION_TEST;
RenamingDelegatingContext renamingContext = new RenamingDelegatingContext(context, "test_");
renamingContext.makeExistingFilesAndDbsAccessible();
sContext = new SharedPreferencesRenamingDelegatingContext(renamingContext, "test_");
PreferenceManager.getDefaultSharedPreferences(sContext).edit().clear().commit();
}
/**
* Closes any resources and objects held by this injector. To use the injector again, invoke
* {@link #resetForIntegrationTesting(Context)}.
*/
public static synchronized void close() {
if (sAccountDb != null) {
sAccountDb.close();
}
if (sHttpClient != null) {
ClientConnectionManager httpClientConnectionManager = sHttpClient.getConnectionManager();
if (httpClientConnectionManager != null) {
httpClientConnectionManager.shutdown();
}
}
sMode = null;
sContext = null;
sAccountDb = null;
sOtpProvider = null;
sTotpClock = null;
sPackageManager = null;
sStartActivityListener = null;
sHttpClient = null;
sImportController = null;
sOptionalFeatures = null;
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/testability/DependencyInjector.java | Java | asf20 | 9,557 |
/*
* 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 com.google.android.apps.authenticator.testability;
import android.app.Activity;
import android.content.Intent;
/**
* Base class for {@link Activity} instances to make them more testable.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class TestableActivity extends Activity {
@Override
public void startActivity(Intent intent) {
StartActivityListener listener = DependencyInjector.getStartActivityListener();
if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) {
return;
}
super.startActivity(intent);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
StartActivityListener listener = DependencyInjector.getStartActivityListener();
if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) {
return;
}
super.startActivityForResult(intent, requestCode);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/testability/TestableActivity.java | Java | asf20 | 1,528 |
/*
* Copyright 2012 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 com.google.android.apps.authenticator.testability;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
/**
* {@link ContextWrapper} that prefixes shared preference file names with the provided prefix and
* passes all other invocations through unmodified to the delegate {@link Context}.
*
* @author klyubin@google.com (Alex Klyubin)
*/
public class SharedPreferencesRenamingDelegatingContext extends ContextWrapper {
private final String mPrefix;
public SharedPreferencesRenamingDelegatingContext(Context delegate, String prefix) {
super(delegate);
mPrefix = prefix;
}
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return super.getSharedPreferences(mPrefix + name, mode);
}
}
| zzhyjun- | src/com/google/android/apps/authenticator/testability/SharedPreferencesRenamingDelegatingContext.java | Java | asf20 | 1,431 |