code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.fanfou.SavedSearch; import com.ch_linghu.fanfoudroid.fanfou.Trend; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.commonsware.cwac.merge.MergeAdapter; import com.ch_linghu.fanfoudroid.R; public class SearchActivity extends BaseActivity { private static final String TAG = SearchActivity.class.getSimpleName(); private static final int LOADING = 1; private static final int NETWORKERROR = 2; private static final int SUCCESS = 3; private EditText mSearchEdit; private ListView mSearchSectionList; private TextView trendsTitle; private TextView savedSearchTitle; private MergeAdapter mSearchSectionAdapter; private SearchAdapter trendsAdapter; private SearchAdapter savedSearchesAdapter; private ArrayList<SearchItem> trends; private ArrayList<SearchItem> savedSearch; private String initialQuery; private NavBar mNavbar; private Feedback mFeedback; private GenericTask trendsAndSavedSearchesTask; private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() { @Override public String getName() { return "trendsAndSavedSearchesTask"; } @Override public void onPreExecute(GenericTask task) { } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { refreshSearchSectionList(SearchActivity.SUCCESS); } else if (result == TaskResult.IO_ERROR) { refreshSearchSectionList(SearchActivity.NETWORKERROR); Toast.makeText( SearchActivity.this, getResources() .getString( R.string.login_status_network_or_connection_error), Toast.LENGTH_SHORT).show(); } } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()..."); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.search); mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); initView(); initSearchSectionList(); refreshSearchSectionList(SearchActivity.LOADING); doGetSavedSearches(); return true; } else { return false; } } private void initView() { mSearchEdit = (EditText) findViewById(R.id.search_edit); mSearchEdit.setOnKeyListener(enterKeyHandler); trendsTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); trendsTitle.setText(getResources().getString(R.string.trends_title)); savedSearchTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); savedSearchTitle.setText(getResources().getString( R.string.saved_search_title)); mSearchSectionAdapter = new MergeAdapter(); mSearchSectionList = (ListView) findViewById(R.id.search_section_list); mNavbar.getSearchButton().setOnClickListener( new View.OnClickListener() { public void onClick(View v) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } }); } @Override protected void onResume() { Log.d(TAG, "onResume()..."); super.onResume(); } private void doGetSavedSearches() { if (trendsAndSavedSearchesTask != null && trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask(); trendsAndSavedSearchesTask .setListener(trendsAndSavedSearchesTaskListener); trendsAndSavedSearchesTask.setFeedback(mFeedback); trendsAndSavedSearchesTask.execute(); } } private void initSearchSectionList() { trends = new ArrayList<SearchItem>(); savedSearch = new ArrayList<SearchItem>(); trendsAdapter = new SearchAdapter(this); savedSearchesAdapter = new SearchAdapter(this); mSearchSectionAdapter.addView(savedSearchTitle); mSearchSectionAdapter.addAdapter(savedSearchesAdapter); mSearchSectionAdapter.addView(trendsTitle); mSearchSectionAdapter.addAdapter(trendsAdapter); mSearchSectionList.setAdapter(mSearchSectionAdapter); } /** * 辅助计算位置的类 * * @author jmx * */ class PositionHelper { /** * 返回指定位置属于哪一个小节 * * @param position * 绝对位置 * @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置 */ public int getSectionIndex(int position) { int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); if (position > 0 && position < contentLength[0] + 1) { return 0; } else if (position > contentLength[0] + 1 && position < (contentLength[0] + contentLength[1] + 1) + 1) { return 1; } else { return -1; } } /** * 返回指定位置在自己所在小节的相对位置 * * @param position * 绝对位置 * @return 所在小节的相对位置,-1为无效位置 */ public int getRelativePostion(int position) { int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); int sectionIndex = getSectionIndex(position); int offset = 0; for (int i = 0; i < sectionIndex; ++i) { offset += contentLength[i] + 1; } return position - offset - 1; } } /** * flag: loading;network error;success */ PositionHelper pos_helper = new PositionHelper(); private void refreshSearchSectionList(int flag) { AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter()); SearchAdapter subAdapter = (SearchAdapter) adapter .getAdapter(position); // 计算针对subAdapter中的相对位置 int relativePos = pos_helper.getRelativePostion(position); SearchItem item = (SearchItem) (subAdapter.getItem(relativePos)); initialQuery = item.query; startSearch(); } }; if (flag == SearchActivity.LOADING) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter.refresh(getString(R.string.search_loading)); trendsAdapter.refresh(getString(R.string.search_loading)); } else if (flag == SearchActivity.NETWORKERROR) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter .refresh(getString(R.string.login_status_network_or_connection_error)); trendsAdapter .refresh(getString(R.string.login_status_network_or_connection_error)); } else { savedSearchesAdapter.refresh(savedSearch); trendsAdapter.refresh(trends); } if (flag == SearchActivity.SUCCESS) { mSearchSectionList .setOnItemClickListener(searchSectionListListener); } } protected boolean startSearch() { if (!TextUtils.isEmpty(initialQuery)) { // 以下这个方法在7可用,在8就报空指针 // triggerSearch(initialQuery, null); Intent i = new Intent(this, SearchResultActivity.class); i.putExtra(SearchManager.QUERY, initialQuery); startActivity(i); } else if (TextUtils.isEmpty(initialQuery)) { Toast.makeText(this, getResources().getString(R.string.search_box_null), Toast.LENGTH_SHORT).show(); return false; } return false; } // 搜索框回车键判断 private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } return true; } return false; } }; private class TrendsAndSavedSearchesTask extends GenericTask { Trend[] trendsList; List<SavedSearch> savedSearchsList; @Override protected TaskResult _doInBackground(TaskParams... params) { try { trendsList = getApi().getTrends().getTrends(); savedSearchsList = getApi().getSavedSearches(); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } trends.clear(); savedSearch.clear(); for (int i = 0; i < trendsList.length; i++) { SearchItem item = new SearchItem(); item.name = trendsList[i].getName(); item.query = trendsList[i].getQuery(); trends.add(item); } for (int i = 0; i < savedSearchsList.size(); i++) { SearchItem item = new SearchItem(); item.name = savedSearchsList.get(i).getName(); item.query = savedSearchsList.get(i).getQuery(); savedSearch.add(item); } return TaskResult.OK; } } } class SearchItem { public String name; public String query; } class SearchAdapter extends BaseAdapter { protected ArrayList<SearchItem> mSearchList; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; public SearchAdapter(Context context) { mSearchList = new ArrayList<SearchItem>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } public SearchAdapter(Context context, String prompt) { this(context); refresh(prompt); } public void refresh(ArrayList<SearchItem> searchList) { mSearchList = searchList; notifyDataSetChanged(); } public void refresh(String prompt) { SearchItem item = new SearchItem(); item.name = prompt; item.query = null; mSearchList.clear(); mSearchList.add(item); notifyDataSetChanged(); } @Override public int getCount() { return mSearchList.size(); } @Override public Object getItem(int position) { return mSearchList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.search_section_view, parent, false); TextView text = (TextView) view .findViewById(R.id.search_section_text); view.setTag(text); } else { view = convertView; } TextView text = (TextView) view.getTag(); SearchItem item = mSearchList.get(position); text.setText(item.name); return view; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.TextView; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetEdit; import com.ch_linghu.fanfoudroid.R; //FIXME: 将WriteDmActivity和WriteActivity进行整合。 /** * 撰写私信界面 * * @author lds * */ public class WriteDmActivity extends BaseActivity { public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW"; public static final String EXTRA_TEXT = "text"; public static final String REPLY_ID = "reply_id"; private static final String TAG = "WriteActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; // View private TweetEdit mTweetEdit; private EditText mTweetEditText; private TextView mProgressText; private Button mSendButton; // private AutoCompleteTextView mToEdit; private TextView mToEdit; private NavBar mNavbar; // Task private GenericTask mSendTask; private TaskListener mSendTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { disableEntry(); updateProgress(getString(R.string.page_status_updating)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mToEdit.setText(""); mTweetEdit.setText(""); updateProgress(""); enableEntry(); // 发送成功就直接关闭界面 finish(); // 关闭软键盘 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTweetEdit.getEditText() .getWindowToken(), 0); } else if (result == TaskResult.NOT_FOLLOWED_ERROR) { updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you)); enableEntry(); } else if (result == TaskResult.IO_ERROR) { // TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因 updateProgress(getString(R.string.page_status_unable_to_update)); enableEntry(); } } @Override public String getName() { return "DMSend"; } }; private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient // autocomplete. private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW"; public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } // sub menu // protected void createInsertPhotoDialog() { // // final CharSequence[] items = { // getString(R.string.write_label_take_a_picture), // getString(R.string.write_label_choose_a_picture) }; // // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(getString(R.string.write_label_insert_picture)); // builder.setItems(items, new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int item) { // // Toast.makeText(getApplicationContext(), items[item], // // Toast.LENGTH_SHORT).show(); // switch (item) { // case 0: // openImageCaptureMenu(); // break; // case 1: // openPhotoLibraryMenu(); // } // } // }); // AlertDialog alert = builder.create(); // alert.show(); // } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { // init View setContentView(R.layout.write_dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this); // Intent & Action & Extras Intent intent = getIntent(); Bundle extras = intent.getExtras(); // View mProgressText = (TextView) findViewById(R.id.progress_text); mTweetEditText = (EditText) findViewById(R.id.tweet_edit); TwitterDatabase db = getDb(); // FIXME: 暂时取消收件人自动完成功能 // FIXME: 可根据目前以后内容重新完成自动完成功能 // mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit); // Cursor cursor = db.getFollowerUsernames(""); // // startManagingCursor(cursor); // mFriendsAdapter = new FriendsAdapter(this, cursor); // mToEdit.setAdapter(mFriendsAdapter); mToEdit = (TextView) findViewById(R.id.to_edit); // Update status mTweetEdit = new TweetEdit(mTweetEditText, (TextView) findViewById(R.id.chars_text)); mTweetEdit.setOnKeyListener(editEnterHandler); mTweetEdit.addTextChangedListener(new MyTextWatcher( WriteDmActivity.this)); // With extras if (extras != null) { String to = extras.getString(EXTRA_USER); if (!TextUtils.isEmpty(to)) { mToEdit.setText(to); mTweetEdit.requestFocus(); } } View.OnClickListener sendListenner = new View.OnClickListener() { public void onClick(View v) { doSend(); } }; Button mTopSendButton = (Button) findViewById(R.id.top_send_btn); mTopSendButton.setOnClickListener(sendListenner); return true; } else { return false; } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); mTweetEdit.updateCharsRemain(); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { // Doesn't really cancel execution (we let it continue running). // See the SendTask code for more details. mSendTask.cancel(true); } // Don't need to cancel FollowersTask (assuming it ends properly). super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } public static Intent createNewTweetIntent(String text) { Intent intent = new Intent(NEW_TWEET_ACTION); intent.putExtra(EXTRA_TEXT, text); return intent; } private class MyTextWatcher implements TextWatcher { private WriteDmActivity _activity; public MyTextWatcher(WriteDmActivity activity) { _activity = activity; } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if (s.length() == 0) { } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } } private void doSend() { if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { String to = mToEdit.getText().toString(); String status = mTweetEdit.getText().toString(); if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) { mSendTask = new DmSendTask(); mSendTask.setListener(mSendTaskListener); mSendTask.execute(); } else if (TextUtils.isEmpty(status)) { updateProgress(getString(R.string.direct_meesage_status_texting_is_null)); } else if (TextUtils.isEmpty(to)) { updateProgress(getString(R.string.direct_meesage_status_user_is_null)); } } } private class DmSendTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String user = mToEdit.getText().toString(); String text = mTweetEdit.getText().toString(); DirectMessage directMessage = getApi().sendDirectMessage(user, text); Dm dm = Dm.create(directMessage, true); // if (!Utils.isEmpty(dm.profileImageUrl)) { // // Fetch image to cache. // try { // getImageManager().put(dm.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } getDb().createDm(dm, false); } catch (HttpException e) { Log.d(TAG, e.getMessage()); // TODO: check is this is actually the case. return TaskResult.NOT_FOLLOWED_ERROR; } return TaskResult.OK; } } private static class FriendsAdapter extends CursorAdapter { public FriendsAdapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME); } private LayoutInflater mInflater; private int mUserTextColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater .inflate(R.layout.dropdown_item, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view.findViewById(android.R.id.text1); view.setTag(holder); return view; } class ViewHolder { public TextView userText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); holder.userText.setText(cursor.getString(mUserTextColumn)); } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String filter = constraint == null ? "" : constraint.toString(); return TwitterApplication.mDb.getFollowerUsernames(filter); } @Override public String convertToString(Cursor cursor) { return cursor.getString(mUserTextColumn); } } private void enableEntry() { mTweetEdit.setEnabled(true); mSendButton.setEnabled(true); } private void disableEntry() { mTweetEdit.setEnabled(false); mSendButton.setEnabled(false); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private View.OnKeyListener editEnterHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doSend(); } return true; } return false; } }; }
Java
package com.ch_linghu.fanfoudroid; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.MessageTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.ch_linghu.fanfoudroid.R; public class DmActivity extends BaseActivity implements Refreshable { private static final String TAG = "DmActivity"; // Views. private ListView mTweetList; private Adapter mAdapter; private Adapter mInboxAdapter; private Adapter mSendboxAdapter; Button inbox; Button sendbox; Button newMsg; private int mDMType; private static final int DM_TYPE_ALL = 0; private static final int DM_TYPE_INBOX = 1; private static final int DM_TYPE_SENDBOX = 2; private TextView mProgressText; private NavBar mNavbar; private Feedback mFeedback; // Tasks. private GenericTask mRetrieveTask; private GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_deleting)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mAdapter.refresh(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmDeleteTask"; } }; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_refreshing)); } @Override public void onProgressUpdate(GenericTask task, Object params) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(Preferences.LAST_DM_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); draw(); goTop(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmRetrieve"; } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS"; public static Intent createIntent() { return createIntent(""); } public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(R.layout.dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavbar.setHeaderTitle("我的私信"); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); bindFooterButtonEvent(); mTweetList = (ListView) findViewById(R.id.tweet_list); mProgressText = (TextView) findViewById(R.id.progress_text); TwitterDatabase db = getDb(); // Mark all as read. db.markAllDmsRead(); setupAdapter(); // Make sure call bindFooterButtonEvent first boolean shouldRetrieve = false; long lastRefreshTime = mPreferences.getLong( Preferences.LAST_DM_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want // dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } // Want to be able to focus on the items with the trackball. // That way, we can navigate up and down by changing item focus. mTweetList.setItemsCanFocus(true); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } private static final String SIS_RUNNING_KEY = "running"; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } super.onDestroy(); } // UI helpers. private void bindFooterButtonEvent() { inbox = (Button) findViewById(R.id.inbox); sendbox = (Button) findViewById(R.id.sendbox); newMsg = (Button) findViewById(R.id.new_message); inbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_INBOX) { mDMType = DM_TYPE_INBOX; inbox.setEnabled(false); sendbox.setEnabled(true); mTweetList.setAdapter(mInboxAdapter); mInboxAdapter.refresh(); } } }); sendbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_SENDBOX) { mDMType = DM_TYPE_SENDBOX; inbox.setEnabled(true); sendbox.setEnabled(false); mTweetList.setAdapter(mSendboxAdapter); mSendboxAdapter.refresh(); } } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(DmActivity.this, WriteDmActivity.class); intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id startActivity(intent); } }); } private void setupAdapter() { Cursor cursor = getDb().fetchAllDms(-1); startManagingCursor(cursor); mAdapter = new Adapter(this, cursor); Cursor inboxCursor = getDb().fetchInboxDms(); startManagingCursor(inboxCursor); mInboxAdapter = new Adapter(this, inboxCursor); Cursor sendboxCursor = getDb().fetchSendboxDms(); startManagingCursor(sendboxCursor); mSendboxAdapter = new Adapter(this, sendboxCursor); mTweetList.setAdapter(mInboxAdapter); registerForContextMenu(mTweetList); inbox.setEnabled(false); } private class DmRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { List<DirectMessage> dmList; ArrayList<Dm> dms = new ArrayList<Dm>(); TwitterDatabase db = getDb(); // ImageManager imageManager = getImageManager(); String maxId = db.fetchMaxDmId(false); HashSet<String> imageUrls = new HashSet<String>(); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getDirectMessages(paging); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList)); for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } maxId = db.fetchMaxDmId(true); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getSentDirectMessages(paging); } else { dmList = getApi().getSentDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, true); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } db.addDms(dms, false); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(null); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // imageManager.put(imageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } return TaskResult.OK; } } private static class Adapter extends CursorAdapter { public Adapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); // TODO: 可使用: // DM dm = MessageTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor.getColumnIndexOrThrow(MessageTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT); mIsSentColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mIsSentColumn; private int mCreatedAtColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.direct_message, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); view.setTag(holder); return view; } class ViewHolder { public TextView userText; public TextView tweetText; public ImageView profileImage; public TextView metaText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); int isSent = cursor.getInt(mIsSentColumn); String user = cursor.getString(mUserTextColumn); if (0 == isSent) { holder.userText.setText(context .getString(R.string.direct_message_label_from_prefix) + user); } else { holder.userText.setText(context .getString(R.string.direct_message_label_to_prefix) + user); } TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader.get( profileImageUrl, new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { Adapter.this.refresh(); } })); } try { holder.metaText.setText(DateTimeHelper .getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER .parse(cursor.getString(mCreatedAtColumn)))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } public void refresh() { getCursor().requery(); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除 // case OPTIONS_MENU_ID_REFRESH: // doRetrieve(); // return true; case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; } return super.onOptionsItemSelected(item); } private static final int CONTEXT_REPLY_ID = 0; private static final int CONTEXT_DELETE_ID = 1; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Cursor cursor = (Cursor) mAdapter.getItem(info.position); if (cursor == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_REPLY_ID: String user_id = cursor.getString(cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_ID)); Intent intent = WriteDmActivity.createIntent(user_id); startActivity(intent); return true; case CONTEXT_DELETE_ID: int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID); String id = cursor.getString(idIndex); doDestroy(id); return true; default: return super.onContextItemSelected(item); } } private void doDestroy(String id) { Log.d(TAG, "Attempting delete."); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new DmDeleteTask(); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } private class DmDeleteTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String id = param.getString("id"); DirectMessage directMessage = getApi().destroyDirectMessage(id); Dm.create(directMessage, false); getDb().deleteDm(id); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new DmRetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } public void goTop() { mTweetList.setSelection(0); } public void draw() { mAdapter.refresh(); mInboxAdapter.refresh(); mSendboxAdapter.refresh(); } private void updateProgress(String msg) { mProgressText.setText(msg); } }
Java
package com.ch_linghu.fanfoudroid.util; import java.io.InputStream; import java.io.OutputStream; public class StreamUtils { public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { } } }
Java
package com.ch_linghu.fanfoudroid.util; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.HashMap; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; /** * Debug Timer * * Usage: -------------------------------- DebugTimer.start(); * DebugTimer.mark("my_mark1"); // optional DebugTimer.stop(); * * System.out.println(DebugTimer.__toString()); // get report * -------------------------------- * * @author LDS */ public class DebugTimer { public static final int START = 0; public static final int END = 1; private static HashMap<String, Long> mTime = new HashMap<String, Long>(); private static long mStartTime = 0; private static long mLastTime = 0; /** * Start a timer */ public static void start() { reset(); mStartTime = touch(); } /** * Mark current time * * @param tag * mark tag * @return */ public static long mark(String tag) { long time = System.currentTimeMillis() - mStartTime; mTime.put(tag, time); return time; } /** * Mark current time * * @param tag * mark tag * @return */ public static long between(String tag, int startOrEnd) { if (TwitterApplication.DEBUG) { Log.v("DEBUG", tag + " " + startOrEnd); } switch (startOrEnd) { case START: return mark(tag); case END: long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime); mTime.put(tag, time); // touch(); return time; default: return -1; } } public static long betweenStart(String tag) { return between(tag, START); } public static long betweenEnd(String tag) { return between(tag, END); } /** * Stop timer * * @return result */ public static String stop() { mTime.put("_TOTLE", touch() - mStartTime); return __toString(); } public static String stop(String tag) { mark(tag); return stop(); } /** * Get a mark time * * @param tag * mark tag * @return time(milliseconds) or NULL */ public static long get(String tag) { return get(tag, 0); } public static long get(String tag, long defaultValue) { if (mTime.containsKey(tag)) { return mTime.get(tag); } return defaultValue; } /** * Reset timer */ public static void reset() { mTime = new HashMap<String, Long>(); mStartTime = 0; mLastTime = 0; } /** * static toString() * * @return */ public static String __toString() { return "Debuger [time =" + mTime.toString() + "]"; } private static long touch() { return mLastTime = System.currentTimeMillis(); } public static DebugProfile[] getProfile() { DebugProfile[] profile = new DebugProfile[mTime.size()]; long totel = mTime.get("_TOTLE"); int i = 0; for (String key : mTime.keySet()) { long time = mTime.get(key); profile[i] = new DebugProfile(key, time, time / (totel * 1.0)); i++; } try { Arrays.sort(profile); } catch (NullPointerException e) { // in case item is null, do nothing } return profile; } public static String getProfileAsString() { StringBuilder sb = new StringBuilder(); for (DebugProfile p : getProfile()) { sb.append("TAG: "); sb.append(p.tag); sb.append("\t INC: "); sb.append(p.inc); sb.append("\t INCP: "); sb.append(p.incPercent); sb.append("\n"); } return sb.toString(); } @Override public String toString() { return __toString(); } } class DebugProfile implements Comparable<DebugProfile> { private static NumberFormat percent = NumberFormat.getPercentInstance(); public String tag; public long inc; public String incPercent; public DebugProfile(String tag, long inc, double incPercent) { this.tag = tag; this.inc = inc; percent = new DecimalFormat("0.00#%"); this.incPercent = percent.format(incPercent); } @Override public int compareTo(DebugProfile o) { // TODO Auto-generated method stub return (int) (o.inc - this.inc); } }
Java
package com.ch_linghu.fanfoudroid.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import android.util.Log; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; public class DateTimeHelper { private static final String TAG = "DateTimeHelper"; // Wed Dec 15 02:53:36 +0000 2010 public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat( "E MMM d HH:mm:ss Z yyyy", Locale.US); public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat( "E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ? public static final Date parseDateTime(String dateString) { try { Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TWITTER_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } // Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite public static final Date parseDateTimeFromSqlite(String dateString) { try { Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } public static final Date parseSearchApiDateTime(String dateString) { try { return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter search date string: " + dateString); return null; } } public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); public static String getRelativeDate(Date date) { Date now = new Date(); String prefix = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_prefix); String sec = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_sec); String min = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_min); String hour = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_hour); String day = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_day); String suffix = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_suffix); // Seconds. long diff = (now.getTime() - date.getTime()) / 1000; if (diff < 0) { diff = 0; } if (diff < 60) { return diff + sec + suffix; } // Minutes. diff /= 60; if (diff < 60) { return prefix + diff + min + suffix; } // Hours. diff /= 60; if (diff < 24) { return prefix + diff + hour + suffix; } return AGO_FULL_DATE_FORMATTER.format(date); } public static long getNowTime() { return Calendar.getInstance().getTime().getTime(); } }
Java
package com.ch_linghu.fanfoudroid.util; import java.io.File; import java.io.IOException; import android.os.Environment; /** * 对SD卡文件的管理 * * @author ch.linghu * */ public class FileHelper { private static final String TAG = "FileHelper"; private static final String BASE_PATH = "fanfoudroid"; public static File getBasePath() throws IOException { File basePath = new File(Environment.getExternalStorageDirectory(), BASE_PATH); if (!basePath.exists()) { if (!basePath.mkdirs()) { throw new IOException(String.format("%s cannot be created!", basePath.toString())); } } if (!basePath.isDirectory()) { throw new IOException(String.format("%s is not a directory!", basePath.toString())); } return basePath; } }
Java
package com.ch_linghu.fanfoudroid.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.Html; import android.text.util.Linkify; import android.util.Log; import android.widget.TextView; import android.widget.TextView.BufferType; public class TextHelper { private static final String TAG = "TextHelper"; public static String stringifyStream(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>(); private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s"); private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() { @Override public final boolean acceptMatch(final CharSequence s, final int start, final int end) { String name = s.subSequence(start + 1, end).toString().trim(); boolean result = _userLinkMapping.containsKey(name); return result; } }; private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() { @Override public String transformUrl(Matcher match, String url) { // TODO Auto-generated method stub String name = url.subSequence(1, url.length()).toString().trim(); return _userLinkMapping.get(name); } }; private static final String TWITTA_USER_URL = "twitta://users/"; public static void linkifyUsers(TextView view) { Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL, NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER); } private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#"); private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() { @Override public final String transformUrl(Matcher match, String url) { String result = url.substring(1, url.length() - 1); return result; } }; private static final String TWITTA_SEARCH_URL = "twitta://search/"; public static void linkifyTags(TextView view) { Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null, TAG_MATCHER_TRANSFORM_FILTER); } private static Pattern USER_LINK = Pattern .compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>"); private static String preprocessText(String text) { // 处理HTML格式返回的用户链接 Matcher m = USER_LINK.matcher(text); while (m.find()) { _userLinkMapping.put(m.group(2), m.group(1)); Log.d(TAG, String.format("Found mapping! %s=%s", m.group(2), m.group(1))); } // 将User Link的连接去掉 StringBuffer sb = new StringBuffer(); m = USER_LINK.matcher(text); while (m.find()) { m.appendReplacement(sb, "@$2"); } m.appendTail(sb); return sb.toString(); } public static String getSimpleTweetText(String text) { return Html.fromHtml(text).toString(); } public static void setSimpleTweetText(TextView textView, String text) { String processedText = getSimpleTweetText(text); textView.setText(processedText); } public static void setTweetText(TextView textView, String text) { String processedText = preprocessText(text); textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE); Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); linkifyUsers(textView); linkifyTags(textView); _userLinkMapping.clear(); } /** * 从消息中获取全部提到的人,将它们按先后顺序放入一个列表 * * @param msg * 消息文本 * @return 消息中@的人的列表,按顺序存放 */ public static List<String> getMentions(String msg) { ArrayList<String> mentionList = new ArrayList<String>(); final Pattern p = Pattern.compile("@(.*?)\\s"); final int MAX_NAME_LENGTH = 12; // 简化判断,无论中英文最长12个字 Matcher m = p.matcher(msg); while (m.find()) { String mention = m.group(1); // 过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度 if (mention.length() <= MAX_NAME_LENGTH + 1) { // 避免重复名字 if (!mentionList.contains(mention)) { mentionList.add(m.group(1)); } } } return mentionList; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.text.ClipboardManager; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.ImageCache; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.ch_linghu.fanfoudroid.R; public class StatusActivity extends BaseActivity { private static final String TAG = "StatusActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; private static final String EXTRA_TWEET = "tweet"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS"; static final private int CONTEXT_REFRESH_ID = 0x0001; static final private int CONTEXT_CLIPBOARD_ID = 0x0002; static final private int CONTEXT_DELETE_ID = 0x0003; // Task TODO: tasks private GenericTask mReplyTask; private GenericTask mStatusTask; private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取 private GenericTask mFavTask; private GenericTask mDeleteTask; private NavBar mNavbar; private Feedback mFeedback; private TaskListener mReplyTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { showReplyStatus(replyTweet); StatusActivity.this.mFeedback.success(""); } @Override public String getName() { return "GetReply"; } }; private TaskListener mStatusTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { clean(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { StatusActivity.this.mFeedback.success(""); draw(); } @Override public String getName() { return "GetStatus"; } }; private TaskListener mPhotoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { status_photo.setImageBitmap(mPhotoBitmap); } else { status_photo.setVisibility(View.GONE); } StatusActivity.this.mFeedback.success(""); } @Override public String getName() { // TODO Auto-generated method stub return "GetPhoto"; } }; private TaskListener mFavTaskListener = new TaskAdapter() { @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public String getName() { return "DeleteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onDeleteSuccess(); } else if (result == TaskResult.IO_ERROR) { onDeleteFailure(); } } }; // View private TextView tweet_screen_name; private TextView tweet_text; private TextView tweet_user_info; private ImageView profile_image; private TextView tweet_source; private TextView tweet_created_at; private ImageButton btn_person_more; private ImageView status_photo = null; // if exists private ViewGroup reply_wrap; private TextView reply_status_text = null; // if exists private TextView reply_status_date = null; // if exists private ImageButton tweet_fav; private Tweet tweet = null; private Tweet replyTweet = null; // if exists private HttpClient mClient; private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists public static Intent createIntent(Tweet tweet) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(EXTRA_TWEET, tweet); return intent; } private static Pattern PHOTO_PAGE_LINK = Pattern .compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])"); private static Pattern PHOTO_SRC_LINK = Pattern .compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\""); /** * 获得消息中的照片页面链接 * * @param text * 消息文本 * @param size * 照片尺寸 * @return 照片页面的链接,若不存在,则返回null */ public static String getPhotoPageLink(String text, String size) { Matcher m = PHOTO_PAGE_LINK.matcher(text); if (m.find()) { String THUMBNAIL = TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_thumbnail); String MIDDLE = TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_middle); String ORIGINAL = TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_original); if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) { return "http://m.fanfou.com" + m.group(1); } else if (size.endsWith(ORIGINAL)) { return m.group(0); } else { return null; } } else { return null; } } /** * 获得照片页面中的照片链接 * * @param pageHtml * 照片页面文本 * @return 照片链接,若不存在,则返回null */ public static String getPhotoURL(String pageHtml) { Matcher m = PHOTO_SRC_LINK.matcher(pageHtml); if (m.find()) { return m.group(1); } else { return null; } } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { mClient = getApi().getHttpClient(); // Intent & Action & Extras Intent intent = getIntent(); String action = intent.getAction(); Bundle extras = intent.getExtras(); // Must has extras if (null == extras) { Log.e(TAG, this.getClass().getName() + " must has extras."); finish(); return false; } setContentView(R.layout.status); mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); findView(); bindNavBarListener(); // Set view with intent data this.tweet = extras.getParcelable(EXTRA_TWEET); draw(); bindFooterBarListener(); bindReplyViewListener(); return true; } else { return false; } } private void findView() { tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name); tweet_user_info = (TextView) findViewById(R.id.tweet_user_info); tweet_text = (TextView) findViewById(R.id.tweet_text); tweet_source = (TextView) findViewById(R.id.tweet_source); profile_image = (ImageView) findViewById(R.id.profile_image); tweet_created_at = (TextView) findViewById(R.id.tweet_created_at); btn_person_more = (ImageButton) findViewById(R.id.person_more); tweet_fav = (ImageButton) findViewById(R.id.tweet_fav); reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_status_text = (TextView) findViewById(R.id.reply_status_text); reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at); status_photo = (ImageView) findViewById(R.id.status_photo); } private void bindNavBarListener() { mNavbar.getRefreshButton().setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { doGetStatus(tweet.id); } }); } private void bindFooterBarListener() { // person_more btn_person_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = ProfileActivity.createIntent(tweet.userId); startActivity(intent); } }); // Footer bar TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share); TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply); TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet); TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav); TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more); // 分享 footer_btn_share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra( Intent.EXTRA_TEXT, String.format("@%s %s", tweet.screenName, TextHelper.getSimpleTweetText(tweet.text))); startActivity(Intent.createChooser(intent, getString(R.string.cmenu_share))); } }); // 回复 footer_btn_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id); startActivity(intent); } }); // 转发 footer_btn_retweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewRepostIntent( StatusActivity.this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); } }); // 收藏/取消收藏 footer_btn_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tweet.favorited.equals("true")) { doFavorite("del", tweet.id); } else { doFavorite("add", tweet.id); } } }); // TODO: 更多操作 registerForContextMenu(footer_btn_more); footer_btn_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openContextMenu(v); } }); } private void bindReplyViewListener() { // 点击回复消息打开新的Status界面 OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) { if (replyTweet == null) { Log.w(TAG, "Selected item not available."); } else { launchActivity(StatusActivity.createIntent(replyTweet)); } } } }; reply_wrap.setOnClickListener(listener); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mReplyTask != null && mReplyTask.getStatus() == GenericTask.Status.RUNNING) { mReplyTask.cancel(true); } if (mPhotoTask != null && mPhotoTask.getStatus() == GenericTask.Status.RUNNING) { mPhotoTask.cancel(true); } if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } super.onDestroy(); } private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { profile_image.setImageBitmap(bitmap); } }; private void clean() { tweet_screen_name.setText(""); tweet_text.setText(""); tweet_created_at.setText(""); tweet_source.setText(""); tweet_user_info.setText(""); tweet_fav.setEnabled(false); profile_image.setImageBitmap(ImageCache.mDefaultBitmap); status_photo.setVisibility(View.GONE); ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_wrap.setVisibility(View.GONE); } private void draw() { Log.d(TAG, "draw"); String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none); String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail); String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle); String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original); SharedPreferences pref = getPreferences(); String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW, PHOTO_PREVIEW_TYPE_ORIGINAL); boolean forceShowAllImage = pref.getBoolean( Preferences.FORCE_SHOW_ALL_IMAGE, false); tweet_screen_name.setText(tweet.screenName); TextHelper.setTweetText(tweet_text, tweet.text); tweet_created_at.setText(DateTimeHelper .getRelativeDate(tweet.createdAt)); tweet_source.setText(getString(R.string.tweet_source_prefix) + tweet.source); tweet_user_info.setText(tweet.userId); boolean isFav = (tweet.favorited.equals("true")) ? true : false; tweet_fav.setEnabled(isFav); // Bitmap mProfileBitmap = // TwitterApplication.mImageManager.get(tweet.profileImageUrl); profile_image.setImageBitmap(TwitterApplication.mImageLoader.get( tweet.profileImageUrl, callback)); // has photo if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) { String photoLink; boolean isPageLink = false; if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) { photoLink = tweet.thumbnail_pic; } else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) { photoLink = tweet.bmiddle_pic; } else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) { photoLink = tweet.original_pic; } else { Log.e(TAG, "Invalid Photo Preview Size Type"); photoLink = ""; } // 如果选用了强制显示则再尝试分析图片链接 if (forceShowAllImage) { photoLink = getPhotoPageLink(tweet.text, photoPreviewSize); isPageLink = true; } if (!TextUtils.isEmpty(photoLink)) { status_photo.setVisibility(View.VISIBLE); status_photo.setImageBitmap(mPhotoBitmap); doGetPhoto(photoLink, isPageLink); } } else { status_photo.setVisibility(View.GONE); } // has reply if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) { ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_wrap.setVisibility(View.VISIBLE); reply_status_text = (TextView) findViewById(R.id.reply_status_text); reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at); doGetReply(tweet.inReplyToStatusId); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mReplyTask != null && mReplyTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } private String fetchWebPage(String url) throws HttpException { Log.d(TAG, "Fetching WebPage: " + url); Response res = mClient.get(url); return res.asString(); } private Bitmap fetchPhotoBitmap(String url) throws HttpException, IOException { Log.d(TAG, "Fetching Photo: " + url); Response res = mClient.get(url); // FIXME:这里使用了一个作废的方法,如何修正? InputStream is = res.asStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); is.close(); return bitmap; } private void doGetReply(String status_id) { Log.d(TAG, "Attempting get status task."); mFeedback.start(""); if (mReplyTask != null && mReplyTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mReplyTask = new GetReplyTask(); mReplyTask.setListener(mReplyTaskListener); TaskParams params = new TaskParams(); params.put("reply_id", status_id); mReplyTask.execute(params); } } private class GetReplyTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; com.ch_linghu.fanfoudroid.fanfou.Status status; try { String reply_id = param.getString("reply_id"); if (!TextUtils.isEmpty(reply_id)) { // 首先查看是否在数据库中,如不在再去获取 replyTweet = getDb().queryTweet(reply_id, -1); if (replyTweet == null) { status = getApi().showStatus(reply_id); replyTweet = Tweet.create(status); } } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } private void doGetStatus(String status_id) { Log.d(TAG, "Attempting get status task."); mFeedback.start(""); if (mStatusTask != null && mStatusTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mStatusTask = new GetStatusTask(); mStatusTask.setListener(mStatusTaskListener); TaskParams params = new TaskParams(); params.put("id", status_id); mStatusTask.execute(params); } } private class GetStatusTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; com.ch_linghu.fanfoudroid.fanfou.Status status; try { String id = param.getString("id"); if (!TextUtils.isEmpty(id)) { status = getApi().showStatus(id); mFeedback.update(80); tweet = Tweet.create(status); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } mFeedback.update(99); return TaskResult.OK; } } private void doGetPhoto(String photoPageURL, boolean isPageLink) { mFeedback.start(""); if (mPhotoTask != null && mPhotoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mPhotoTask = new GetPhotoTask(); mPhotoTask.setListener(mPhotoTaskListener); TaskParams params = new TaskParams(); params.put("photo_url", photoPageURL); params.put("is_page_link", isPageLink); mPhotoTask.execute(params); } } private class GetPhotoTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String photoURL = param.getString("photo_url"); boolean isPageLink = param.getBoolean("is_page_link"); if (!TextUtils.isEmpty(photoURL)) { if (isPageLink) { String pageHtml = fetchWebPage(photoURL); String photoSrcURL = getPhotoURL(pageHtml); if (photoSrcURL != null) { mPhotoBitmap = fetchPhotoBitmap(photoSrcURL); } } else { mPhotoBitmap = fetchPhotoBitmap(photoURL); } } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } catch (IOException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } private void showReplyStatus(Tweet tweet) { if (tweet != null) { String text = tweet.screenName + " : " + tweet.text; TextHelper.setSimpleTweetText(reply_status_text, text); reply_status_date.setText(DateTimeHelper .getRelativeDate(tweet.createdAt)); } else { String msg = MessageFormat.format( getString(R.string.status_status_reply_cannot_display), this.tweet.inReplyToScreenName); reply_status_text.setText(msg); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { finish(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { if (!TextUtils.isEmpty(id)) { Log.d(TAG, "doFavorite."); mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams param = new TaskParams(); param.put("action", action); param.put("id", id); mFavTask.execute(param); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals( TweetCommonTask.FavoriteTask.TYPE_ADD)) { tweet.favorited = "true"; tweet_fav.setEnabled(true); } else { tweet.favorited = "false"; tweet_fav.setEnabled(false); } } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } private void doDelete(String id) { if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new TweetCommonTask.DeleteTask(this); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case CONTEXT_REFRESH_ID: doGetStatus(tweet.id); return true; case CONTEXT_CLIPBOARD_ID: ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(TextHelper.getSimpleTweetText(tweet.text)); return true; case CONTEXT_DELETE_ID: doDelete(tweet.id); return true; } return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(getString(R.string.cmenu_more)); menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh); menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard); if (tweet.userId.equals(TwitterApplication.getMyselfId(false))) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; import com.ch_linghu.fanfoudroid.R; public class FollowingActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage = 1; String myself = ""; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId = TwitterApplication.getMyselfId(false); userName = TwitterApplication.getMyselfName(false); } if (super._onCreate(savedInstanceState)) { myself = TwitterApplication.getMyselfId(false); if (getUserId() == myself) { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), userName)); } return true; } else { return false; } } /* * 添加取消关注按钮 * * @see * com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu * (android.view.ContextMenu, android.view.View, * android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (getUserId() == myself) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); menu.add( 0, CONTENT_DEL_FRIEND, 0, getResources().getString( R.string.cmenu_user_addfriend_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_friend_suffix)); } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage += 1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { currentPage = 1; return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFriendsStatuses(userId, page); } }
Java
package com.ch_linghu.fanfoudroid; import java.util.HashSet; //import org.acra.ReportingInteractionMode; //import org.acra.annotation.ReportsCrashes; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.LazyImageLoader; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.Configuration; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; //@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ", // mode = ReportingInteractionMode.NOTIFICATION, // resNotifTickerText = R.string.crash_notif_ticker_text, // resNotifTitle = R.string.crash_notif_title, // resNotifText = R.string.crash_notif_text, // resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign // resDialogText = R.string.crash_dialog_text, // resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign // resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name // resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label // resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report. //) public class TwitterApplication extends Application { public static final String TAG = "TwitterApplication"; // public static ImageManager mImageManager; public static LazyImageLoader mImageLoader; public static TwitterDatabase mDb; public static Weibo mApi; // new API public static Context mContext; public static SharedPreferences mPref; public static int networkType = 0; public final static boolean DEBUG = Configuration.getDebug(); public GenericTask mUserInfoTask = new GetUserInfoTask(); // FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道 // 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器 // 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户 // 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。 // 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID // 到mPref. private static void fetchMyselfInfo() { User myself; try { myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi .getUserId()); TwitterApplication.mPref.edit() .putString(Preferences.CURRENT_USER_ID, myself.getId()) .commit(); TwitterApplication.mPref .edit() .putString(Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit(); } catch (HttpException e) { e.printStackTrace(); } } public static String getMyselfId(boolean forceGet) { if (!mPref.contains(Preferences.CURRENT_USER_ID)){ if (forceGet && mPref.getString(Preferences.CURRENT_USER_ID, "~") .startsWith("~")){ fetchMyselfInfo(); } } return mPref.getString(Preferences.CURRENT_USER_ID, "~"); } public static String getMyselfName(boolean forceGet) { if (!mPref.contains(Preferences.CURRENT_USER_ID) || !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)) { if (forceGet && mPref.getString(Preferences.CURRENT_USER_ID, "~") .startsWith("~")){ fetchMyselfInfo(); } } return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, ""); } @Override public void onCreate() { // FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。 // 因此将这些代码设成关闭状态,仅在做性能调试时才打开。 // //NOTE: StrictMode模式需要2.3+ API支持。 // if (DEBUG){ // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() // .detectAll() // .penaltyLog() // .build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() // .detectAll() // .penaltyLog() // .build()); // } super.onCreate(); mContext = this.getApplicationContext(); // mImageManager = new ImageManager(this); mImageLoader = new LazyImageLoader(); mApi = new Weibo(); mDb = TwitterDatabase.getInstance(this); mPref = PreferenceManager.getDefaultSharedPreferences(this); String username = mPref.getString(Preferences.USERNAME_KEY, ""); String password = mPref.getString(Preferences.PASSWORD_KEY, ""); password = LoginActivity.decryptPassword(password); if (Weibo.isValidCredentials(username, password)) { mApi.setCredentials(username, password); // Setup API and HttpClient doGetUserInfo(); } // 为cmwap用户设置代理上网 String type = getNetworkType(); if (null != type && type.equalsIgnoreCase("cmwap")) { Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT); mApi.getHttpClient().setProxy("10.0.0.172", 80, "http"); } } public String getNetworkType() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); // NetworkInfo mobNetInfo = connectivityManager // .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (activeNetInfo != null) { return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, // cmnet, // internet ... } else { return null; } } @Override public void onTerminate() { // FIXME: 根据android文档,onTerminate不会在真实机器上被执行到 // 因此这些清理动作需要再找合适的地方放置,以确保执行。 cleanupImages(); mDb.close(); Toast.makeText(this, "exit app", Toast.LENGTH_LONG); super.onTerminate(); } private void cleanupImages() { HashSet<String> keepers = new HashSet<String>(); Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME); if (cursor.moveToFirst()) { int imageIndex = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); do { keepers.add(cursor.getString(imageIndex)); } while (cursor.moveToNext()); } cursor.close(); cursor = mDb.fetchAllDms(-1); if (cursor.moveToFirst()) { int imageIndex = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); do { keepers.add(cursor.getString(imageIndex)); } while (cursor.moveToNext()); } cursor.close(); mImageLoader.getImageManager().cleanup(keepers); } public void doGetUserInfo() { if (mUserInfoTask != null && mUserInfoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mUserInfoTask = new GetUserInfoTask(); mUserInfoTask.setListener(new TaskAdapter(){ @Override public String getName() { return "GetUserInfo"; } }); mUserInfoTask.execute(); } } public class GetUserInfoTask extends GenericTask { public static final String TAG = "DeleteTask"; @Override protected TaskResult _doInBackground(TaskParams... params) { getMyselfId(true); getMyselfName(true); return TaskResult.OK; } } }
Java
package com.markupartist.android.widget; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.AbsListView.OnScrollListener; import com.ch_linghu.fanfoudroid.R; public class PullToRefreshListView extends ListView implements OnScrollListener, GestureDetector.OnGestureListener { private final int MAXHEIGHT = 20; private static final int TAP_TO_REFRESH = 1; private static final int PULL_TO_REFRESH = 2; private static final int RELEASE_TO_REFRESH = 3; private static final int REFRESHING = 4; // private static final int RELEASING = 5;//释放过程做动画用 private static final String TAG = "PullToRefreshListView"; private OnRefreshListener mOnRefreshListener; /** * Listener that will receive notifications every time the list scrolls. */ private OnScrollListener mOnScrollListener; private LayoutInflater mInflater; private LinearLayout mRefreshView; private TextView mRefreshViewText; private ImageView mRefreshViewImage; private ProgressBar mRefreshViewProgress; private TextView mRefreshViewLastUpdated; private int mCurrentScrollState; private int mRefreshState; private RotateAnimation mFlipAnimation; private RotateAnimation mReverseFlipAnimation; private int mRefreshViewHeight; private int mRefreshOriginalTopPadding; private int mLastMotionY; private GestureDetector mDetector; // private int mPadding; public PullToRefreshListView(Context context) { super(context); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { GestureDetector localGestureDetector = new GestureDetector(this); this.mDetector = localGestureDetector; // Load all of the animations we need in code rather than through XML mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(200); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(200); mReverseFlipAnimation.setFillAfter(true); mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRefreshView = (LinearLayout) mInflater.inflate( R.layout.pull_to_refresh_header, null); mRefreshViewText = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_text); mRefreshViewImage = (ImageView) mRefreshView .findViewById(R.id.pull_to_refresh_image); mRefreshViewProgress = (ProgressBar) mRefreshView .findViewById(R.id.pull_to_refresh_progress); mRefreshViewLastUpdated = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_updated_at); mRefreshViewImage.setMinimumHeight(50); mRefreshView.setOnClickListener(new OnClickRefreshListener()); mRefreshOriginalTopPadding = mRefreshView.getPaddingTop(); mRefreshState = TAP_TO_REFRESH; addHeaderView(mRefreshView); super.setOnScrollListener(this); measureView(mRefreshView); mRefreshViewHeight = mRefreshView.getMeasuredHeight(); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } /** * Set the listener that will receive notifications every time the list * scrolls. * * @param l * The scroll listener. */ @Override public void setOnScrollListener(AbsListView.OnScrollListener l) { mOnScrollListener = l; } /** * Register a callback to be invoked when this list should be refreshed. * * @param onRefreshListener * The callback to run. */ public void setOnRefreshListener(OnRefreshListener onRefreshListener) { mOnRefreshListener = onRefreshListener; } /** * Set a text to represent when the list was last updated. * * @param lastUpdated * Last updated at. */ public void setLastUpdated(CharSequence lastUpdated) { if (lastUpdated != null) { mRefreshViewLastUpdated.setVisibility(View.VISIBLE); mRefreshViewLastUpdated.setText(lastUpdated); } else { mRefreshViewLastUpdated.setVisibility(View.GONE); } } @Override /** * TODO:此方法重写 */ public boolean onTouchEvent(MotionEvent event) { GestureDetector localGestureDetector = this.mDetector; localGestureDetector.onTouchEvent(event); final int y = (int) event.getY(); Log.d(TAG, String.format( "[onTouchEvent]event.Action=%d, currState=%d, refreshState=%d,y=%d", event.getAction(), mCurrentScrollState, mRefreshState, y)); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (!isVerticalScrollBarEnabled()) { setVerticalScrollBarEnabled(true); } if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) { if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView .getTop() >= 0)) { // Initiate the refresh mRefreshState = REFRESHING; prepareForRefresh(); onRefresh(); } else if (mRefreshView.getBottom() < mRefreshViewHeight + MAXHEIGHT || mRefreshView.getTop() <= 0) { // Abort refresh and scroll down below the refresh view resetHeader(); setSelection(1); } } break; case MotionEvent.ACTION_DOWN: mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: applyHeaderPadding(event); break; } return super.onTouchEvent(event); } /** * TODO:此方法重写 * @param ev */ private void applyHeaderPadding(MotionEvent ev) { final int historySize = ev.getHistorySize(); Log.d(TAG, String.format( "[applyHeaderPadding]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); // Workaround for getPointerCount() which is unavailable in 1.5 // (it's always 1 in 1.5) int pointerCount = 1; try { Method method = MotionEvent.class.getMethod("getPointerCount"); pointerCount = (Integer) method.invoke(ev); } catch (NoSuchMethodException e) { pointerCount = 1; } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { System.err.println("unexpected " + e); } catch (InvocationTargetException e) { System.err.println("unexpected " + e); } if (mRefreshState == RELEASE_TO_REFRESH) { // this.offsetTopAndBottom(-mPadding); for (int h = 0; h < historySize; h++) { for (int p = 0; p < pointerCount; p++) { if (isVerticalFadingEdgeEnabled()) { setVerticalScrollBarEnabled(false); } int historicalY = 0; try { // For Android > 2.0 Method method = MotionEvent.class.getMethod( "getHistoricalY", Integer.TYPE, Integer.TYPE); historicalY = ((Float) method.invoke(ev, p, h)) .intValue(); } catch (NoSuchMethodException e) { // For Android < 2.0 historicalY = (int) (ev.getHistoricalY(h)); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { System.err.println("unexpected " + e); } catch (InvocationTargetException e) { System.err.println("unexpected " + e); } // Calculate the padding to apply, we divide by 1.7 to // simulate a more resistant effect during pull. int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 1.7); // Log.d(TAG, // String.format( // "[applyHeaderPadding]historicalY=%d,topPadding=%d,mRefreshViewHeight=%d,mLastMotionY=%d", // historicalY, topPadding, // mRefreshViewHeight, mLastMotionY)); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), topPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } } } } /** * Sets the header padding back to original size. */ private void resetHeaderPadding() { Log.d(TAG, String.format( "[resetHeaderPadding]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); // invalidate(); //this.mPadding=0; //this.offsetTopAndBottom(this.mPadding); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } /** * Resets the header to the original state. */ private void resetHeader() { Log.d(TAG, String.format("[resetHeader]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); if (mRefreshState != TAP_TO_REFRESH) { mRefreshState = TAP_TO_REFRESH; resetHeaderPadding(); // Set refresh view text to the pull label // mRefreshViewText.setText(R.string.pull_to_refresh_tap_label);//点击刷新是否有用 mRefreshViewText.setText(R.string.pull_to_refresh_pull_label); // Replace refresh drawable with arrow drawable mRefreshViewImage .setImageResource(R.drawable.ic_pulltorefresh_arrow); // Clear the full rotation animation mRefreshViewImage.clearAnimation(); // Hide progress bar and arrow. mRefreshViewImage.setVisibility(View.GONE); mRefreshViewProgress.setVisibility(View.GONE); } } private void measureView(View child) { Log.d(TAG, String.format("[measureView]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { Log.d(TAG, "List onScroll"); if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); mRefreshViewImage.setVisibility(View.INVISIBLE); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, firstVisibleItem, visibleItemCount, totalItemCount); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(view, scrollState); } } public void prepareForRefresh() { resetHeaderPadding(); mRefreshViewImage.setVisibility(View.GONE); // We need this hack, otherwise it will keep the previous drawable. mRefreshViewImage.setImageDrawable(null); mRefreshViewProgress.setVisibility(View.VISIBLE); // Set refresh view text to the refreshing label mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label); mRefreshState = REFRESHING; } public void onRefresh() { Log.d(TAG, "onRefresh"); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } /** * Resets the list to a normal state after a refresh. * * @param lastUpdated * Last updated at. */ public void onRefreshComplete(CharSequence lastUpdated) { setLastUpdated(lastUpdated); onRefreshComplete(); } /** * Resets the list to a normal state after a refresh. */ public void onRefreshComplete() { Log.d(TAG, "onRefreshComplete"); resetHeader(); // If refresh view is visible when loading completes, scroll down to // the next item. if (mRefreshView.getBottom() > 0) { invalidateViews(); // setSelection(1); } } /** * Invoked when the refresh view is clicked on. This is mainly used when * there's only a few items in the list and it's not possible to drag the * list. */ private class OnClickRefreshListener implements OnClickListener { @Override public void onClick(View v) { if (mRefreshState != REFRESHING) { prepareForRefresh(); onRefresh(); } } } /** * Interface definition for a callback to be invoked when list should be * refreshed. */ public interface OnRefreshListener { /** * Called when the list should be refreshed. * <p> * A call to {@link PullToRefreshListView #onRefreshComplete()} is * expected to indicate that the refresh has completed. */ public void onRefresh(); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { int firstVisibleItem = this.getFirstVisiblePosition(); // When the refresh view is completely visible, change the text to say // "Release to refresh..." and flip the arrow drawable. Log.d(TAG, String.format( "[OnScroll]first=%d, currState=%d, refreshState=%d", firstVisibleItem, mCurrentScrollState, mRefreshState)); if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && mRefreshState != REFRESHING) { if (firstVisibleItem == 0) { mRefreshViewImage.setVisibility(View.VISIBLE); // Log.d(TAG, // String.format( // "getBottom=%d,refreshViewHeight=%d,getTop=%d,mRefreshOriginalTopPadding=%d", // mRefreshView.getBottom(), mRefreshViewHeight // + MAXHEIGHT, // this.getTopPaddingOffset(), // mRefreshOriginalTopPadding)); if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView .getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) { //this.mPadding+=distanceY;//备用 mRefreshViewText .setText(R.string.pull_to_refresh_release_label); mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mFlipAnimation); mRefreshState = RELEASE_TO_REFRESH; } else if (mRefreshView.getBottom() < mRefreshViewHeight + MAXHEIGHT && mRefreshState != PULL_TO_REFRESH) { mRefreshViewText .setText(R.string.pull_to_refresh_pull_label); if (mRefreshState != TAP_TO_REFRESH) { mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mReverseFlipAnimation); } mRefreshState = PULL_TO_REFRESH; } } else { mRefreshViewImage.setVisibility(View.GONE); resetHeader(); } } /*not execute else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); }*/ return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub return false; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.query.jquery; import java.util.ArrayList; import java.util.List; /** * * @author namhh */ public class main { public static void main(String[] args) { BCol bCol1 = new BCol("A", 1); BCol bCol2 = new BCol("B", (Double).6876); BTable bTable = new BTable("AB"); bTable.addCol(bCol1).addCol(bCol2).addCol(bCol2); List l = new ArrayList(); l.add(bCol2); System.out.println( bTable.QUERY.setSelectedColumns(bCol1) .setSelectedColumns(bCol2) .addCondtion(BTable.TYPE.AND, bCol2, BTable.OPERATION.EQUAL, 1) .join(bTable.QUERY, BTable.JOIN_TYPE.INNER_JOIN, l) .toQueryString()); System.out.println(bTable.QUERY.toQueryString()); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.query.jquery; /** * * @author namhh * @param <_Type> */ public class BCol<_Type extends Object> implements Cloneable { private String colname; private _Type value; private boolean isPk = false; private int index = -1; public BCol(String colname, _Type value) { this.colname = colname; this.value = value; } public boolean isPrimaryKey() { return isPk; } public void setPrimaryKey() { isPk = true; } public void setPrimaryKey(boolean isPrimaryKey) { isPk = isPrimaryKey; } public _Type getValue() { return value; } public String getCoumnName() { return colname; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public void setValue(_Type value) { this.value = value; } @Override public String toString() { return this.colname; //To change body of generated methods, choose Tools | Templates. } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.query.jquery; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author namhh */ public class BTable { private String _tableName; public Query QUERY; public BTable(String tableName) { _tableName = tableName; QUERY = new Query(); } private Set<BCol> cols = new HashSet<>(); public BTable addCol(BCol bcol) { cols.add(bcol); return this; } public String aliasName() { return hashCode() + ""; } protected enum TYPE { AND(" AND "), OR(" OR "), INNER_JOIN(" INNER JOIN "); private final String type; private TYPE(String type) { this.type = type; } public String getVal() { return type; } } protected enum JOIN_TYPE { INNER_JOIN(" INNER JOIN "); private final String type; private JOIN_TYPE(String type) { this.type = type; } public String getVal() { return type; } } protected enum OPERATION { EQUAL(" = "), LESS_EQUAL(" <= "), GREATER_EQUAL(" >= "); private final String type; private OPERATION(String type) { this.type = type; } public String getVal() { return type; } } public class Query { private final List<BCol> selectedColumns = new ArrayList<BCol>(); private String _where = " "; private String _join = " "; public Query setSelectedColumns(BCol column) { selectedColumns.add(column); return this; } public String getEntityAlias() { return "t" + aliasName(); } public String getEntityOperation() { return "t" + aliasName() + "."; } private String getSELECT() { String ret = " SELECT "; if (!selectedColumns.isEmpty()) { for (int i = 0; i < selectedColumns.size(); i++) { ret += " " + getEntityOperation() + selectedColumns.get(i); if (i + 1 < selectedColumns.size()) { ret += " , "; } } } else { ret += " * "; } return ret; } private String getFROM() { return " FROM " + _tableName + " " + getEntityAlias(); } public Query addCondtion(TYPE type, BCol cols, OPERATION operation, Object val) { String col = getEntityOperation() + cols; if (val instanceof String) { val = "LOWER('" + val + "')"; col = "LOWER(" + cols + ")"; } if (_where.contains("WHERE")) { _where += type.getVal() + col + operation.getVal() + val; } else { _where += "WHERE " + col + operation.getVal() + val; } return this; } public Query join(Query other, JOIN_TYPE type, List<BCol> joinOn) { String on = ""; for (int i = 0; i < joinOn.size(); i++) { on += getEntityOperation() + joinOn.get(i) + " = " + other.getEntityOperation() + joinOn.get(i); if (i + 1 < joinOn.size()) { on += " AND "; } } _join = type.getVal() + "\n (" + other.toQueryString() + "\n" + " )" + other.getEntityAlias() + " \n ON" + "(" + on + ")"; return this; } public String toQueryString() { String ret = getSELECT() + "\n" + getFROM() + "\n" + _join + "\n" + _where; clear(); return ret; } public void clear() { selectedColumns.clear(); _join = ""; _where = ""; } } }
Java
import com.jh.jutil.worker.Pool; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class SimplePoolImp extends Pool{ }
Java
import com.jh.jutil.worker.MonitorPool; import com.jh.jutil.worker.Observer; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class PoolImp extends MonitorPool{ @Override public void alert(Observer observer, Object value) { System.out.println( " Recieve alert : " +value); } }
Java
import com.jh.jutil.worker.Subject; import com.jh.jutil.worker.AlertJob; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class AlertJobImp extends AlertJob { public AlertJobImp(Subject subject) { super(subject); } @Override public void run() { System.out.println("Run " + this.getJobName()); subject.alert(this, " DONE "); System.out.println( this.getJobName() + " DONE"); } @Override public int update(Object object) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int noftify(Object object) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
Java
import com.jh.jutil.worker.Job; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class JobImp extends Job{ @Override public void run() { System.out.println(this.getJobName() + "DONE"); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.jutil.sql.client; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * * @author root */ public class MysqlClient { private final String _host; private final int _port; private final String _dbname; private final String _user; private final String _password; private BlockingQueue<Connection> pool; private String url; public static MysqlClient _instance; public MysqlClient(String _host, int _port, String _dbname, String _user, String _password, int poolSize) { this._host = _host; this._port = _port; this._dbname = _dbname; this._user = _user; this._password = _password; init(poolSize); } private boolean init(int poolsize) { try { Class.forName("com.mysql.jdbc.Driver"); url = "jdbc:mysql://" + _host + ":" + _port + "/" + _dbname + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&interactiveClient=true&" + "&user=" + _user + "&password=" + _password; BlockingQueue<Connection> cnnPool = new ArrayBlockingQueue<Connection>(poolsize); while (cnnPool.size() < poolsize) { cnnPool.add(DriverManager.getConnection(url)); } pool = cnnPool; } catch (Exception ex) { return false; } return true; } public Connection getDbConnection() { Connection conn = null; int retry = 0; do { try { conn = pool.poll(10000, TimeUnit.MILLISECONDS); if (conn == null || !conn.isValid(0)) { conn = DriverManager.getConnection(url); } } catch (Exception ex) { } ++retry; } while (conn == null && retry < 3); return conn; } public void releaseDbConnection(java.sql.Connection conn) { if (conn != null) { pool.add(conn); } } public void importData(String tableName, String filename) { Statement stmt; String query; Connection conn = getDbConnection(); if (conn == null) { return; } try { stmt = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); query = "LOAD DATA LOCAL INFILE '" + filename + "' REPLACE INTO TABLE " + tableName; stmt.executeUpdate(query); } catch (Exception e) { stmt = null; } finally { releaseDbConnection(conn); } } }
Java
package com.jh.jutil.helper; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.security.MessageDigest; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author */ public class UtilHelper { public static final Charset charset = Charset.forName("UTF-8"); public static final CharsetEncoder encoder = charset.newEncoder(); public static final CharsetDecoder decoder = charset.newDecoder(); private static final Random rand = new Random(); public static String md5(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte byteData[] = md.digest(); //convert the byte to hex format method 1 StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (Exception ex) { return ""; } } public static ByteBuffer strToBB(String msg) { try { return encoder.encode(CharBuffer.wrap(msg)); } catch (Exception e) { } return null; } public static ByteBuffer longToBB(long l) { ByteBuffer buffer = ByteBuffer.allocateDirect(8); buffer.putLong(l); buffer.flip(); return buffer; } public static long bbToL(ByteBuffer buffer) { int old_position = buffer.position(); long l = buffer.getLong(); buffer.position(old_position); return l; } public static String bbToStr(ByteBuffer buffer) { String data = ""; try { int old_position = buffer.position(); data = decoder.decode(buffer).toString(); buffer.position(old_position); } catch (Exception e) { } return data; } public static String toASCII(String text) { if (text == null) { return ""; } text = text.replaceAll(" ", ""); text = text.toLowerCase(); text = text.replaceAll("à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ", "a"); text = text.replaceAll("è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ", "e"); text = text.replaceAll("ì|í|ị|ỉ|ĩ", "i"); text = text.replaceAll("ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ", "o"); text = text.replaceAll("ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ", "u"); text = text.replaceAll("ỳ|ý|ỵ|ỷ|ỹ", "y"); text = text.replaceAll("đ", "d"); text = text.replaceAll("!|@|%|\\^|\\*|\\(|\\)|\\+|\\=|\\<|\\>|\\?|\\/|,|\\.|\\:|\\;|\\'|\\\"|\\&|\\#|\\[|\\]|~|$|_", "-"); text = text.replaceAll("-+-", "-"); text = text.replaceAll("^\\-+|\\-+$", ""); return text; } public static String filterUnicodeToASCII(String str) { String rs = ""; String[] marTViet = new String[]{"à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ", "ì", "í", "ị", "ỉ", "ĩ", "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ", "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ", "ỳ", "ý", "ỵ", "ỷ", "ỹ", "đ", "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ", "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ", "Ì", "Í", "Ị", "Ỉ", "Ĩ", "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ợ", "Ở", "Ỡ", "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ", "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ", "Đ"}; String[] marKoDau = new String[]{"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "y", "y", "y", "y", "y", "d", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "I", "I", "I", "I", "I", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "Y", "Y", "Y", "Y", "Y", "D"}; rs = str; for (int index = 0; index < marTViet.length; ++index) { rs = rs.replace(marTViet[index], marKoDau[index]); } return rs; } public static long getTime(String strDate, String format) { if (format == null) { format = "dd/MM/yyyy HH:mm:ss"; } long result = 0; try { if (strDate != null && !strDate.isEmpty()) { DateFormat formatter; Date date; formatter = new SimpleDateFormat(format); date = (Date) formatter.parse(strDate); result = date.getTime(); } else { result = System.currentTimeMillis(); } } catch (ParseException e) { System.out.println("Exception :" + e); } return result; } public static String getStrDate(long time, String format) { if (format == null || format.isEmpty()) { format = "dd - MM - yyyy"; } DateFormat dateFormat = new SimpleDateFormat(format); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); String result = dateFormat.format(cal.getTime()); return (result != null ? result : ""); } public static boolean validateURL(String url) { // String rex = "((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%@.\\w_]*)#?(?:[\\w]*))?)"; String rex = "^(https?:\\/\\/)" + // protocol "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string "(\\#[-a-z\\d_]*)?$"; // fragment locater // return url.matches(rex); return true; } public static boolean validateEmail(String hex) { String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(hex); return matcher.matches(); } public static boolean validateUsername(String hex) { String USERNAME_PATTERN = "^(?=.{6,24}$)(?![_.])(?![0-9])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$"; Pattern pattern = Pattern.compile(USERNAME_PATTERN); Matcher matcher = pattern.matcher(hex); return matcher.matches(); } public static boolean validateDisplayname(String hex) { hex = filterUnicodeToASCII(hex); String DISPLAYNAME_PATTERN = "^[a-zA-Z0-9 ]{1,50}$"; Pattern pattern = Pattern.compile(DISPLAYNAME_PATTERN); Matcher matcher = pattern.matcher(hex); return matcher.matches(); } public static boolean validatePhone(String phone) { String PHONE_PATTERN = "^\\+?[0-9]{6,24}$"; Pattern pattern = Pattern.compile(PHONE_PATTERN); Matcher matcher = pattern.matcher(phone); return matcher.matches(); } public static List<String> splitStrToList(String str, String regex) { String[] tempArr = str.split(regex); List<String> result = new ArrayList(); if (tempArr != null && tempArr.length > 0) { Collections.addAll(result, tempArr); } return result; } public static String zenCaptcha(int numchar) { String code = ""; for (int i = 0; i < numchar; ++i) { code += String.valueOf(rand.nextInt(9)); } return code; } public static ByteBuffer getByteBufferFromFile(String path) { ByteBuffer buff = null; File fcover = new File(path); if (fcover.exists()) { FileInputStream fileStream; try { fileStream = new FileInputStream(fcover); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] read = new byte[2048]; int i = 0; while ((i = fileStream.read(read)) > 0) { byteArray.write(read, 0, i); } fileStream.close(); buff = ByteBuffer.wrap(byteArray.toByteArray()); } catch (Exception ex) { } } return buff; } public static String strtrim(String str) { String rs = str; int length; do { length = rs.length(); rs = rs.replace(" ", " "); } while (length != rs.length()); return rs; } public static String hashMediaName(String filename) { String rs = ""; int pos = filename.lastIndexOf("."); if (pos > -1) { String name = filename.substring(0, pos); String type = filename.substring(pos + 1, filename.length()); name = strtrim(name); name = filterUnicodeToASCII(name); name = md5(name); name += "_" + System.currentTimeMillis(); rs = name + "." + type; } return rs; } public static String escapeHTML(String html) { if (html != null) { return html.replaceAll("\\<.*?\\>", ""); } return ""; } public static String xssRemove(String content) { if (content == null) { return ""; } return content.replaceAll("(?i)<script.*?>.*?</script.*?>", "") // case 1 .replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "") // case 2 .replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", ""); // case 3 } public static String safeStr(String content) { content = xssRemove(content); content = escapeHTML(content); content = strtrim(content); return content; } }
Java
package com.jh.jutil.worker; import java.util.HashSet; import java.util.Set; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class MonitorPool extends Pool implements Subject { private Set<Observer> obsersvers = new HashSet<>(); @Override public void add(Observer observer) { obsersvers.add(observer); } @Override public void remove(Observer observer) { obsersvers.remove(observer); } }
Java
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class Job implements Runnable{ private String jobName; public String getJobName() { if (jobName == null || jobName.isEmpty()) { return " {JOB} " + this.hashCode() + " "; } return " {JOB} " + jobName + " "; } public void setJobName(String jobName) { this.jobName = jobName; } @Override public String toString() { return getJobName(); } }
Java
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public interface Subject { void add(Observer observer); void remove(Observer observer); void alert(Observer observer,Object value); }
Java
package com.jh.jutil.worker; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class Pool { private static final int _corePoolSize = 10; private static final int _maxPoolSize = 18; private static final long _keepAliveTime = 5000; private final ThreadPoolExecutor _threadPoolExecutor = new ThreadPoolExecutor( _corePoolSize, _maxPoolSize, _keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(5000) ); public void excute(Job job) { _threadPoolExecutor.execute(job); } public Pool setRejectedExecutionHandler(final long timeout) { _threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { Thread.sleep(timeout); executor.execute(r); } catch (Exception ex) { ex.printStackTrace(); } } }); return this; } public void shutdown(long timeOutBySecond) { try { _threadPoolExecutor.shutdown(); _threadPoolExecutor.awaitTermination(timeOutBySecond, TimeUnit.SECONDS); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
Java
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public interface Observer { int update(Object object); int noftify(Object object); }
Java
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class AlertJob extends Job implements Observer { protected Subject subject; public AlertJob(Subject subject) { this.subject = subject; } }
Java
package b_Money; public class Currency { private String name; private Double rate; /** * New Currency * The rate argument of each currency indicates that Currency's "universal" exchange rate. * Imagine that we define the rate of each currency in relation to some universal currency. * This means that the rate of each currency defines its value compared to this universal currency. * * @param name The name of this Currency * @param rate The exchange rate of this Currency */ Currency (String name, Double rate) { this.name = name; this.rate = rate; } /** Convert an amount of this Currency to its value in the general "universal currency" * (As mentioned in the documentation of the Currency constructor) * * @param amount An amount of cash of this currency. * @return The value of amount in the "universal currency" */ public Integer universalValue(Integer amount) { } /** Get the name of this Currency. * @return name of Currency */ public String getName() { } /** Get the rate of this Currency. * * @return rate of this Currency */ public Double getRate() { } /** Set the rate of this currency. * * @param rate New rate for this Currency */ public void setRate(Double rate) { } /** Convert an amount from another Currency to an amount in this Currency * * @param amount Amount of the other Currency * @param othercurrency The other Currency */ public Integer valueInThisCurrency(Integer amount, Currency othercurrency) { } }
Java
package b_Money; public class AccountDoesNotExistException extends Exception { static final long serialVersionUID = 1L; }
Java
package b_Money; import java.util.Hashtable; public class Bank { private Hashtable<String, Account> accountlist = new Hashtable<String, Account>(); private String name; private Currency currency; /** * New Bank * @param name Name of this bank * @param currency Base currency of this bank (If this is a Swedish bank, this might be a currency class representing SEK) */ Bank(String name, Currency currency) { this.name = name; this.currency = currency; } /** * Get the name of this bank * @return Name of this bank */ public String getName() { return name; } /** * Get the Currency of this bank * @return The Currency of this bank */ public Currency getCurrency() { return currency; } /** * Open an account at this bank. * @param accountid The ID of the account * @throws AccountExistsException If the account already exists */ public void openAccount(String accountid) throws AccountExistsException { if (accountlist.containsKey(accountid)) { throw new AccountExistsException(); } else { accountlist.get(accountid); } } /** * Deposit money to an account * @param accountid Account to deposit to * @param money Money to deposit. * @throws AccountDoesNotExistException If the account does not exist */ public void deposit(String accountid, Money money) throws AccountDoesNotExistException { if (accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Withdraw money from an account * @param accountid Account to withdraw from * @param money Money to withdraw * @throws AccountDoesNotExistException If the account does not exist */ public void withdraw(String accountid, Money money) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Get the balance of an account * @param accountid Account to get balance from * @return Balance of the account * @throws AccountDoesNotExistException If the account does not exist */ public Integer getBalance(String accountid) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { return accountlist.get(accountid).getBalance().getAmount(); } } /** * Transfer money between two accounts * @param fromaccount Id of account to deduct from in this Bank * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, Bank tobank, String toaccount, Money amount) throws AccountDoesNotExistException { if (!accountlist.containsKey(fromaccount) || !tobank.accountlist.containsKey(toaccount)) { throw new AccountDoesNotExistException(); } else { accountlist.get(fromaccount).withdraw(amount); tobank.accountlist.get(toaccount).deposit(amount); } } /** * Transfer money between two accounts on the same bank * @param fromaccount Id of account to deduct from * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, String toaccount, Money amount) throws AccountDoesNotExistException { transfer(fromaccount, this, fromaccount, amount); } /** * Add a timed payment * @param accountid Id of account to deduct from in this Bank * @param payid Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String accountid, String payid, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { Account account = accountlist.get(accountid); account.addTimedPayment(payid, interval, next, amount, tobank, toaccount); } /** * Remove a timed payment * @param accountid Id of account to remove timed payment from * @param id Id of timed payment */ public void removeTimedPayment(String accountid, String id) { Account account = accountlist.get(accountid); account.removeTimedPayment(id); } /** * A time unit passes in the system */ public void tick() throws AccountDoesNotExistException { for (Account account : accountlist.values()) { account.tick(); } } }
Java
package b_Money; import java.util.Hashtable; public class Account { private Money content; private Hashtable<String, TimedPayment> timedpayments = new Hashtable<String, TimedPayment>(); Account(String name, Currency currency) { this.content = new Money(0, currency); } /** * Add a timed payment * @param id Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String id, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { TimedPayment tp = new TimedPayment(interval, next, amount, this, tobank, toaccount); timedpayments.put(id, tp); } /** * Remove a timed payment * @param id Id of timed payment to remove */ public void removeTimedPayment(String id) { timedpayments.remove(id); } /** * Check if a timed payment exists * @param id Id of timed payment to check for */ public boolean timedPaymentExists(String id) { return timedpayments.containsKey(id); } /** * A time unit passes in the system */ public void tick() { for (TimedPayment tp : timedpayments.values()) { tp.tick(); tp.tick(); } } /** * Deposit money to the account * @param money Money to deposit. */ public void deposit(Money money) { content = content.add(money); } /** * Withdraw money from the account * @param money Money to withdraw. */ public void withdraw(Money money) { content = content.sub(money); } /** * Get balance of account * @return Amount of Money currently on account */ public Money getBalance() { return content; } /* Everything below belongs to the private inner class, TimedPayment */ private class TimedPayment { private int interval, next; private Account fromaccount; private Money amount; private Bank tobank; private String toaccount; TimedPayment(Integer interval, Integer next, Money amount, Account fromaccount, Bank tobank, String toaccount) { this.interval = interval; this.next = next; this.amount = amount; this.fromaccount = fromaccount; this.tobank = tobank; this.toaccount = toaccount; } /* Return value indicates whether or not a transfer was initiated */ public Boolean tick() { if (next == 0) { next = interval; fromaccount.withdraw(amount); try { tobank.deposit(toaccount, amount); } catch (AccountDoesNotExistException e) { /* Revert transfer. * In reality, this should probably cause a notification somewhere. */ fromaccount.deposit(amount); } return true; } else { next--; return false; } } } }
Java
package b_Money; public class AccountExistsException extends Exception { static final long serialVersionUID = 1L; }
Java
package b_Money; import java.util.*; public class Money implements Comparable { private int amount; private Currency currency; /** * New Money * @param amount The amount of money * @param currency The currency of the money */ Money (Integer amount, Currency currency) { this.amount = amount; this.currency = currency; } /** * Return the amount of money. * @return Amount of money in Double type. */ public Integer getAmount() { return this.amount; } /** * Returns the currency of this Money. * @return Currency object representing the currency of this Money */ public Currency getCurrency() { return this.currency; } /** * Returns the amount of the money in the string form "(amount) (currencyname)", e.g. "10.5 SEK". * Recall that we represent decimal numbers with integers. This means that the "10.5 SEK" mentioned * above is actually represented as the integer 1050 * @return String representing the amount of Money. */ public String toString() { } /** * Gets the universal value of the Money, according the rate of its Currency. * @return The value of the Money in the "universal currency". */ public Integer universalValue() { } /** * Check to see if the value of this money is equal to the value of another Money of some other Currency. * @param other The other Money that is being compared to this Money. * @return A Boolean indicating if the two monies are equal. */ public Boolean equals(Money other) { } /** * Adds a Money to this Money, regardless of the Currency of the other Money. * @param other The Money that is being added to this Money. * @return A new Money with the same Currency as this Money, representing the added value of the two. * (Remember to convert the other Money before adding the amounts) */ public Money add(Money other) { } /** * Subtracts a Money from this Money, regardless of the Currency of the other Money. * @param other The money that is being subtracted from this Money. * @return A new Money with the same Currency as this Money, representing the subtracted value. * (Again, remember converting the value of the other Money to this Currency) */ public Money sub(Money other) { } /** * Check to see if the amount of this Money is zero or not * @return True if the amount of this Money is equal to 0.0, False otherwise */ public Boolean isZero() { } /** * Negate the amount of money, i.e. if the amount is 10.0 SEK the negation returns -10.0 SEK * @return A new instance of the money class initialized with the new negated money amount. */ public Money negate() { } /** * Compare two Monies. * compareTo is required because the class implements the Comparable interface. * (Remember the universalValue method, and that Integers already implement Comparable). * Also, since compareTo must take an Object, you will have to explicitly downcast it to a Money. * @return 0 if the values of the monies are equal. * A negative integer if this Money is less valuable than the other Money. * A positive integer if this Money is more valuiable than the other Money. */ public int compareTo(Object other) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.android.plus; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; /** * Stub until the release of <a href="https://developers.google.com/android/google-play-services/"> * Google Play Services.</a> */ public final class PlusOneButton extends Button { public PlusOneButton(Context context) { super(context); } public PlusOneButton(Context context, AttributeSet attrs) { super(context, attrs); } public PlusOneButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setUrl(String url) { } public void setSize(Size size) { } public enum Size { SMALL, MEDIUM, TALL, STANDARD } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.android.plus; import android.content.Context; /** * Stub until the release of <a href="https://developers.google.com/android/google-play-services/"> * Google Play Services.</a> */ public final class GooglePlus { public static GooglePlus initialize(Context context, String apiKey, String clientId) { return new GooglePlus(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Room; import com.google.android.apps.iosched.io.model.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Handler that parses room JSON data into a list of content provider operations. */ public class RoomsHandler extends JSONHandler { private static final String TAG = makeLogTag(RoomsHandler.class); public RoomsHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); Rooms roomsJson = new Gson().fromJson(json, Rooms.class); int noOfRooms = roomsJson.rooms.length; for (int i = 0; i < noOfRooms; i++) { parseRoom(roomsJson.rooms[i], batch); } return batch; } private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Rooms.CONTENT_URI)); builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id); builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name); builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor); batch.add(builder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class Event { public String room; public String end_date; public String level; public String[] track; public String start_time; public String title; @SerializedName("abstract") public String _abstract; public String start_date; public String attending; public String has_streaming; public String end_time; public String livestream_url; public String[] youtube_url; public String id; public String tags; public String[] speaker_id; public String[] prereq; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class MyScheduleItem { public String date; public String time; public String role; public Location[] locations; public String title; public String session_id; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class SandboxCompany { public String company_name; public String company_description; public String[] exhibitors; public String logo_img; public String product_description; public String product_pod; public String website; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class AnnouncementsResponse extends GenericResponse { public Announcement[] announcements; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class SearchSuggestions { public String[] words; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Tracks { Track[] track; public Track[] getTrack() { return track; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Errors { public Error[] errors; public String code; public String message; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Speaker { public String display_name; public String bio; public String plusone_url; public String thumbnail_url; public String user_id; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class TimeSlot { public String start; public String end; public String title; public String type; public String meta; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class EventSlots { public Day[] day; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Error { public String domain; public String reason; public String message; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Location { public String location; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Room { public String id; public String name; public String floor; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class Track { public String name; public String color; @SerializedName("abstract") public String _abstract; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Announcement { public String date; public String[] tracks; public String title; public String link; public String summary; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class SessionsResult { public Event[] events; public String event_type; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; import com.google.gson.JsonElement; public class GenericResponse { public JsonElement error; // // public void checkResponseForAuthErrorsAndThrow() throws IOException { // if (error != null && error.isJsonObject()) { // JsonObject errorObject = error.getAsJsonObject(); // int errorCode = errorObject.get("code").getAsInt(); // String errorMessage = errorObject.get("message").getAsString(); // if (400 <= errorCode && errorCode < 500) { // // The API currently only returns 400 unfortunately. // throw ... // } // } // } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; import com.google.gson.annotations.SerializedName; public class SpeakersResponse extends GenericResponse { @SerializedName("devsite_speakers") public Speaker[] speakers; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Day { public String date; public TimeSlot[] slot; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class Rooms { public Room[] rooms; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class ErrorResponse { public Errors error; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class MyScheduleResponse extends GenericResponse { public MyScheduleItem[] schedule_list; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class EditMyScheduleResponse { public String message; public boolean success; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io.model; public class SessionsResponse extends GenericResponse { public SessionsResult[] result; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.MyScheduleItem; import com.google.android.apps.iosched.io.model.MyScheduleResponse; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Handler that parses "my schedule" JSON data into a list of content provider operations. */ public class MyScheduleHandler extends JSONHandler { private static final String TAG = makeLogTag(MyScheduleHandler.class); public MyScheduleHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); MyScheduleResponse response = new Gson().fromJson(json, MyScheduleResponse.class); if (response.error == null) { LOGI(TAG, "Updating user's schedule"); if (response.schedule_list != null) { // Un-star all sessions first batch.add(ContentProviderOperation .newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .withValue(Sessions.SESSION_STARRED, 0) .build()); // Star only those sessions in the "my schedule" response for (MyScheduleItem item : response.schedule_list) { batch.add(ContentProviderOperation .newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildSessionUri(item.session_id))) .withValue(Sessions.SESSION_STARRED, 1) .build()); } } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.SearchSuggestions; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; /** * Handler that parses search suggestions JSON data into a list of content provider operations. */ public class SearchSuggestHandler extends JSONHandler { public SearchSuggestHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class); if (suggestions.words != null) { // Clear out suggestions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .build()); // Rebuild suggestions for (String word : suggestions.words) { batch.add(ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.SearchSuggest.CONTENT_URI)) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word) .build()); } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import java.io.IOException; /** * General {@link IOException} that indicates a problem occurred while parsing or applying a {@link * JSONHandler}. */ public class HandlerException extends IOException { public HandlerException() { super(); } public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } public static class UnauthorizedException extends HandlerException { public UnauthorizedException() { } public UnauthorizedException(String message) { super(message); } public UnauthorizedException(String message, Throwable cause) { super(message, cause); } } public static class NoDevsiteProfileException extends HandlerException { public NoDevsiteProfileException() { } public NoDevsiteProfileException(String message) { super(message); } public NoDevsiteProfileException(String message, Throwable cause) { super(message, cause); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.model.Event; import com.google.android.apps.iosched.io.model.SessionsResponse; import com.google.android.apps.iosched.io.model.SessionsResult; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.text.format.Time; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; /** * Handler that parses session JSON data into a list of content provider operations. */ public class SessionsHandler extends JSONHandler { private static final String TAG = makeLogTag(SessionsHandler.class); private static final String BASE_SESSION_URL = "https://developers.google.com/events/io/sessions/"; private static final String EVENT_TYPE_KEYNOTE = "keynote"; private static final String EVENT_TYPE_CODELAB = "codelab"; private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1; private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2; private static final Time sTime = new Time(); private static final Pattern sRemoveSpeakerIdPrefixPattern = Pattern.compile(".*//"); private boolean mLocal; private boolean mThrowIfNoAuthToken; public SessionsHandler(Context context, boolean local, boolean throwIfNoAuthToken) { super(context); mLocal = local; mThrowIfNoAuthToken = throwIfNoAuthToken; } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SessionsResponse response = new Gson().fromJson(json, SessionsResponse.class); int numEvents = 0; if (response.result != null) { numEvents = response.result[0].events.length; } if (numEvents > 0) { LOGI(TAG, "Updating sessions data"); // by default retain locally starred if local sync boolean retainLocallyStarredSessions = mLocal; if (response.error != null && response.error.isJsonPrimitive()) { String errorMessageLower = response.error.getAsString().toLowerCase(); if (!mLocal && (errorMessageLower.contains("no profile") || errorMessageLower.contains("no auth token"))) { // There was some authentication issue; retain locally starred sessions. retainLocallyStarredSessions = true; LOGW(TAG, "The user has no developers.google.com profile or this call is " + "not authenticated. Retaining locally starred sessions."); } if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) { throw new HandlerException.UnauthorizedException("No auth token but we tried " + "authenticating. Need to invalidate the auth token."); } } Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { // Collect the list of current starred sessions Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created block IDs Set<String> blockIds = new HashSet<String>(); for (SessionsResult result : response.result) { for (Event event : result.events) { int flags = 0; if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(event.id) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } String sessionId = event.id; if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title String sessionTitle = event.title; if (EVENT_TYPE_CODELAB.equals(result.event_type)) { sessionTitle = mContext.getString( R.string.codelab_title_template, sessionTitle); } // Whether or not it's in the schedule boolean inSchedule = "Y".equals(event.attending); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) { // Keynotes are always in your schedule. inSchedule = true; } // Re-order session tracks so that Code Lab is last if (event.track != null) { Arrays.sort(event.track, sTracksComparator); } // Hashtags String hashtags = ""; if (event.track != null) { StringBuilder hashtagsBuilder = new StringBuilder(); for (String trackName : event.track) { if (trackName.trim().startsWith("Code Lab")) { trackName = "Code Labs"; } if (trackName.contains("Keynote")) { continue; } hashtagsBuilder.append(" #"); hashtagsBuilder.append( ScheduleContract.Tracks.generateTrackId(trackName)); } hashtags = hashtagsBuilder.toString().trim(); } // Pre-reqs String prereqs = ""; if (event.prereq != null && event.prereq.length > 0) { StringBuilder sb = new StringBuilder(); for (String prereq : event.prereq) { sb.append(prereq); sb.append(" "); } prereqs = sb.toString(); if (prereqs.startsWith("<br>")) { prereqs = prereqs.substring(4); } } String youtubeUrl = null; if (event.youtube_url != null && event.youtube_url.length > 0) { youtubeUrl = event.youtube_url[0]; } // Insert session info final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, result.event_type) .withValue(Sessions.SESSION_LEVEL, event.level) .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, event._abstract) .withValue(Sessions.SESSION_TAGS, event.tags) .withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId)) .withValue(Sessions.SESSION_LIVESTREAM_URL, event.livestream_url) .withValue(Sessions.SESSION_REQUIREMENTS, prereqs) .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_HASHTAGS, hashtags) .withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, "") .withValue(Sessions.SESSION_NOTES_URL, "") .withValue(Sessions.ROOM_ID, sanitizeId(event.room)); long sessionStartTime = parseTime(event.start_date, event.start_time); long sessionEndTime = parseTime(event.end_date, event.end_time); String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId)) { String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) { blockType = ParserUtils.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(result.event_type)) { blockType = ParserUtils.BLOCK_TYPE_CODE_LAB; blockTitle = mContext .getString(R.string.schedule_block_title_code_labs); } else { blockType = ParserUtils.BLOCK_TYPE_SESSION; blockTitle = mContext.getString(R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } builder.withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); if (event.speaker_id != null) { for (String speakerId : event.speaker_id) { speakerId = sRemoveSpeakerIdPrefixPattern.matcher(speakerId).replaceAll( ""); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build()); } } // Replace all session tracks final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); if (event.track != null) { for (String trackName : event.track) { if (trackName.contains("Code Lab")) { trackName = "Code Labs"; } String trackId = ScheduleContract.Tracks.generateTrackId(trackName); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } } } } return batch; } private Comparator<String> sTracksComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { // TODO: improve performance of this comparator return (s1.contains("Code Lab") ? "z" : s1).compareTo( (s2.contains("Code Lab") ? "z" : s2)); } }; private String makeSessionUrl(String sessionId) { if (TextUtils.isEmpty(sessionId)) { return null; } return BASE_SESSION_URL + sessionId; } private static long parseTime(String date, String time) { //change to this format : 2011-05-10T07:00:00.000-07:00 int index = time.indexOf(":"); if (index == 1) { time = "0" + time; } final String composed = String.format("%sT%s:00.000-07:00", date, time); //return sTimeFormat.parse(composed).getTime(); sTime.parse3339(composed); return sTime.toMillis(false); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Speaker; import com.google.android.apps.iosched.io.model.SpeakersResponse; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Handler that parses speaker JSON data into a list of content provider operations. */ public class SpeakersHandler extends JSONHandler { private static final String TAG = makeLogTag(SpeakersHandler.class); public SpeakersHandler(Context context, boolean local) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SpeakersResponse response = new Gson().fromJson(json, SpeakersResponse.class); int numEvents = 0; if (response.speakers != null) { numEvents = response.speakers.length; } if (numEvents > 0) { LOGI(TAG, "Updating speakers data"); // Clear out existing speakers batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Speakers.CONTENT_URI)) .build()); for (Speaker speaker : response.speakers) { String speakerId = speaker.user_id; // Insert speaker info batch.add(ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Speakers.SPEAKER_ID, speakerId) .withValue(Speakers.SPEAKER_NAME, speaker.display_name) .withValue(Speakers.SPEAKER_ABSTRACT, speaker.bio) .withValue(Speakers.SPEAKER_IMAGE_URL, speaker.thumbnail_url) .withValue(Speakers.SPEAKER_URL, speaker.plusone_url) .build()); } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; /** * An abstract object that is in charge of parsing JSON data with a given, known structure, into * a list of content provider operations (inserts, updates, etc.) representing the data. */ public abstract class JSONHandler { protected static Context mContext; protected JSONHandler(Context context) { mContext = context; } public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException; /** * Loads the JSON text resource with the given ID and returns the JSON content. */ public static String loadResourceJson(Context context, int resource) throws IOException { InputStream is = context.getResources().openRawResource(resource); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.model.SandboxCompany; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import android.text.TextUtils; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Handler that parses developer sandbox JSON data into a list of content provider operations. */ public class SandboxHandler extends JSONHandler { private static final String TAG = makeLogTag(SandboxHandler.class); private static final String BASE_LOGO_URL = "http://commondatastorage.googleapis.com/io2012/sandbox%20logos/"; public SandboxHandler(Context context, boolean local) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); SandboxCompany[] companies = new Gson().fromJson(json, SandboxCompany[].class); if (companies.length > 0) { LOGI(TAG, "Updating developer sandbox data"); // Clear out existing sandbox companies batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Vendors.CONTENT_URI)) .build()); StringBuilder companyDescription = new StringBuilder(); String exhibitorsPrefix = mContext.getString(R.string.vendor_exhibitors_prefix); for (SandboxCompany company : companies) { // Insert sandbox company info String website = company.website; if (!TextUtils.isEmpty(website) && !website.startsWith("http")) { website = "http://" + website; } companyDescription.setLength(0); if (company.exhibitors != null && company.exhibitors.length > 0) { companyDescription.append(exhibitorsPrefix); companyDescription.append(" "); for (int i = 0; i < company.exhibitors.length; i++) { companyDescription.append(company.exhibitors[i]); if (i >= company.exhibitors.length - 1) { break; } companyDescription.append(", "); } companyDescription.append("\n\n"); } if (!TextUtils.isEmpty(company.company_description)) { companyDescription.append(company.company_description); companyDescription.append("\n\n"); } if (!TextUtils.isEmpty(company.product_description)) { companyDescription.append(company.product_description); } // Clean up logo URL String logoUrl = null; if (!TextUtils.isEmpty(company.logo_img)) { logoUrl = company.logo_img.replaceAll(" ", "%20"); if (!logoUrl.startsWith("http")) { logoUrl = BASE_LOGO_URL + logoUrl; } } batch.add(ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Vendors.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Vendors.VENDOR_ID, Vendors.generateVendorId(company.company_name)) .withValue(Vendors.VENDOR_NAME, company.company_name) .withValue(Vendors.VENDOR_DESC, companyDescription.toString()) .withValue(Vendors.VENDOR_PRODUCT_DESC, null) // merged into company desc .withValue(Vendors.VENDOR_LOGO_URL, logoUrl) .withValue(Vendors.VENDOR_URL, website) .withValue(Vendors.TRACK_ID, ScheduleContract.Tracks.generateTrackId(company.product_pod)) .build()); } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import android.content.ContentProviderOperation; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; import com.google.android.apps.iosched.io.model.Announcement; import com.google.android.apps.iosched.io.model.AnnouncementsResponse; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; /** * Handler that parses announcements JSON data into a list of content provider operations. */ public class AnnouncementsHandler extends JSONHandler { private static final String TAG = makeLogTag(AnnouncementsHandler.class); public AnnouncementsHandler(Context context, boolean local) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); AnnouncementsResponse response = new Gson().fromJson(json, AnnouncementsResponse.class); int numAnnouncements = 0; if (response.announcements != null) { numAnnouncements = response.announcements.length; } if (numAnnouncements > 0) { LOGI(TAG, "Updating announcements data"); // Clear out existing announcements batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Announcements.CONTENT_URI)) .build()); for (Announcement announcement : response.announcements) { // Save tracks as a json array final String tracks = (announcement.tracks != null && announcement.tracks.length > 0) ? new Gson().toJson(announcement.tracks) : null; // Insert announcement info batch.add(ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) // TODO: better announcements ID heuristic .withValue(Announcements.ANNOUNCEMENT_ID, (announcement.date + announcement.title).hashCode()) .withValue(Announcements.ANNOUNCEMENT_DATE, announcement.date) .withValue(Announcements.ANNOUNCEMENT_TITLE, announcement.title) .withValue(Announcements.ANNOUNCEMENT_SUMMARY, announcement.summary) .withValue(Announcements.ANNOUNCEMENT_URL, announcement.link) .withValue(Announcements.ANNOUNCEMENT_TRACKS, tracks) .build()); } } return batch; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Day; import com.google.android.apps.iosched.io.model.EventSlots; import com.google.android.apps.iosched.io.model.TimeSlot; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class BlocksHandler extends JSONHandler { private static final String TAG = makeLogTag(BlocksHandler.class); public BlocksHandler(Context context) { super(context); } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); try { Gson gson = new Gson(); EventSlots eventSlots = gson.fromJson(json, EventSlots.class); int numDays = eventSlots.day.length; //2011-05-10T07:00:00.000-07:00 for (int i = 0; i < numDays; i++) { Day day = eventSlots.day[i]; String date = day.date; TimeSlot[] timeSlots = day.slot; for (TimeSlot timeSlot : timeSlots) { parseSlot(date, timeSlot, batch); } } } catch (Throwable e) { LOGE(TAG, e.toString()); } return batch; } private static void parseSlot(String date, TimeSlot slot, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI)); //LOGD(TAG, "Inside parseSlot:" + date + ", " + slot); String start = slot.start; String end = slot.end; String type = "N_D"; if (slot.type != null) { type = slot.type; } String title = "N_D"; if (slot.title != null) { title = slot.title; } String startTime = date + "T" + start + ":00.000-07:00"; String endTime = date + "T" + end + ":00.000-07:00"; LOGV(TAG, "startTime:" + startTime); long startTimeL = ParserUtils.parseTime(startTime); long endTimeL = ParserUtils.parseTime(endTime); final String blockId = Blocks.generateBlockId(startTimeL, endTimeL); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "title:" + title); LOGV(TAG, "start:" + startTimeL); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTimeL); builder.withValue(Blocks.BLOCK_END, endTimeL); builder.withValue(Blocks.BLOCK_TYPE, type); builder.withValue(Blocks.BLOCK_META, slot.meta); batch.add(builder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.model.Track; import com.google.android.apps.iosched.io.model.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.Lists; import com.google.gson.Gson; import android.content.ContentProviderOperation; import android.content.Context; import android.graphics.Color; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; /** * Handler that parses track JSON data into a list of content provider operations. */ public class TracksHandler extends JSONHandler { private static final String TAG = makeLogTag(TracksHandler.class); public TracksHandler(Context context) { super(context); } @Override public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); batch.add(ContentProviderOperation.newDelete( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Tracks.CONTENT_URI)).build()); Tracks tracksJson = new Gson().fromJson(json, Tracks.class); int noOfTracks = tracksJson.getTrack().length; for (int i = 0; i < noOfTracks; i++) { parseTrack(tracksJson.getTrack()[i], batch); } return batch; } private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) { ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( ScheduleContract.addCallerIsSyncAdapterParameter( ScheduleContract.Tracks.CONTENT_URI)); builder.withValue(ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.generateTrackId(track.name)); builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name); builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color)); builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract); batch.add(builder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns; import android.app.SearchManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper for managing {@link SQLiteDatabase} that stores data for * {@link ScheduleProvider}. */ public class ScheduleDatabase extends SQLiteOpenHelper { private static final String TAG = makeLogTag(ScheduleDatabase.class); private static final String DATABASE_NAME = "schedule.db"; // NOTE: carefully update onUpgrade() when bumping database versions to make // sure user data is saved. private static final int VER_LAUNCH = 25; private static final int VER_SESSION_TYPE = 26; private static final int DATABASE_VERSION = VER_SESSION_TYPE; interface Tables { String BLOCKS = "blocks"; String TRACKS = "tracks"; String ROOMS = "rooms"; String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String SESSIONS_SPEAKERS = "sessions_speakers"; String SESSIONS_TRACKS = "sessions_tracks"; String VENDORS = "vendors"; String ANNOUNCEMENTS = "announcements"; String SESSIONS_SEARCH = "sessions_search"; String SEARCH_SUGGEST = "search_suggest"; String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_JOIN_ROOMS = "sessions " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_JOIN_TRACKS = "vendors " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers " + "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id"; String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers " + "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks " + "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id"; String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks " + "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search " + "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions " + "LEFT OUTER JOIN sessions_tracks ON " + "sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id"; String BLOCKS_JOIN_SESSIONS = "blocks " + "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id"; } private interface Triggers { String SESSIONS_SEARCH_INSERT = "sessions_search_insert"; String SESSIONS_SEARCH_DELETE = "sessions_search_delete"; String SESSIONS_SEARCH_UPDATE = "sessions_search_update"; // Deletes from session_tracks when corresponding sessions are deleted. String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete"; } public interface SessionsSpeakers { String SESSION_ID = "session_id"; String SPEAKER_ID = "speaker_id"; } public interface SessionsTracks { String SESSION_ID = "session_id"; String TRACK_ID = "track_id"; } interface SessionsSearchColumns { String SESSION_ID = "session_id"; String BODY = "body"; } /** Fully-qualified field names. */ private interface Qualified { String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "." + SessionsSearchColumns.SESSION_ID; String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID + "," + SessionsSearchColumns.BODY + ")"; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; } /** {@code REFERENCES} clauses. */ private interface References { String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")"; String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")"; String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")"; String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")"; String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")"; String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")"; } private interface Subquery { /** * Subquery used to build the {@link SessionsSearchColumns#BODY} string * used for indexing {@link Sessions} content. */ String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE + "||'; '||new." + Sessions.SESSION_ABSTRACT + "||'; '||" + "coalesce(new." + Sessions.SESSION_TAGS + ", '')" + ")"; } public ScheduleDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.BLOCKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + BlocksColumns.BLOCK_ID + " TEXT NOT NULL," + BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL," + BlocksColumns.BLOCK_START + " INTEGER NOT NULL," + BlocksColumns.BLOCK_END + " INTEGER NOT NULL," + BlocksColumns.BLOCK_TYPE + " TEXT," + BlocksColumns.BLOCK_META + " TEXT," + "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TracksColumns.TRACK_ID + " TEXT NOT NULL," + TracksColumns.TRACK_NAME + " TEXT," + TracksColumns.TRACK_COLOR + " INTEGER," + TracksColumns.TRACK_ABSTRACT + " TEXT," + "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ROOMS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + RoomsColumns.ROOM_ID + " TEXT NOT NULL," + RoomsColumns.ROOM_NAME + " TEXT," + RoomsColumns.ROOM_FLOOR + " TEXT," + "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SessionsColumns.SESSION_ID + " TEXT NOT NULL," + Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + "," + SessionsColumns.SESSION_TYPE + " TEXT," + SessionsColumns.SESSION_LEVEL + " TEXT," + SessionsColumns.SESSION_TITLE + " TEXT," + SessionsColumns.SESSION_ABSTRACT + " TEXT," + SessionsColumns.SESSION_REQUIREMENTS + " TEXT," + SessionsColumns.SESSION_TAGS + " TEXT," + SessionsColumns.SESSION_HASHTAGS + " TEXT," + SessionsColumns.SESSION_URL + " TEXT," + SessionsColumns.SESSION_YOUTUBE_URL + " TEXT," + SessionsColumns.SESSION_PDF_URL + " TEXT," + SessionsColumns.SESSION_NOTES_URL + " TEXT," + SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0," + SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER," + SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT," + "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL," + SpeakersColumns.SPEAKER_NAME + " TEXT," + SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT," + SpeakersColumns.SPEAKER_COMPANY + " TEXT," + SpeakersColumns.SPEAKER_ABSTRACT + " TEXT," + SpeakersColumns.SPEAKER_URL + " TEXT," + "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + "," + "UNIQUE (" + SessionsSpeakers.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID + ")"); db.execSQL("CREATE TABLE " + Tables.VENDORS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + VendorsColumns.VENDOR_ID + " TEXT NOT NULL," + Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + "," + VendorsColumns.VENDOR_NAME + " TEXT," + VendorsColumns.VENDOR_LOCATION + " TEXT," + VendorsColumns.VENDOR_DESC + " TEXT," + VendorsColumns.VENDOR_URL + " TEXT," + VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT," + VendorsColumns.VENDOR_LOGO_URL + " TEXT," + VendorsColumns.VENDOR_STARRED + " INTEGER," + "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL," + AnnouncementsColumns.ANNOUNCEMENT_SUMMARY + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_TRACKS + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT," + AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)"); createSessionsSearch(db); createSessionsDeleteTriggers(db); db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)"); } /** * Create triggers that automatically build {@link Tables#SESSIONS_SEARCH} * as values are changed in {@link Tables#SESSIONS}. */ private static void createSessionsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSearchColumns.BODY + " TEXT NOT NULL," + SessionsSearchColumns.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " " + " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " " + " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE + " AFTER UPDATE ON " + Tables.SESSIONS + " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = " + Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id" + "; END;"); } private void createSessionsDeleteTriggers(SQLiteDatabase db) { db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " " + " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { case VER_LAUNCH: // VER_SESSION_TYPE added column for session feedback URL. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_TYPE + " TEXT"); version = VER_SESSION_TYPE; } LOGD(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { LOGW(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_UPDATE); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH); db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST); onCreate(db); } } public static void deleteDatabase(Context context) { context.deleteDatabase(DATABASE_NAME); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various * {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = makeLogTag(ScheduleProvider.class); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int BLOCKS_ID_SESSIONS_STARRED = 104; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_WITH_TRACK = 402; private static final int SESSIONS_SEARCH = 403; private static final int SESSIONS_AT = 404; private static final int SESSIONS_ID = 405; private static final int SESSIONS_ID_SPEAKERS = 406; private static final int SESSIONS_ID_TRACKS = 407; private static final int SESSIONS_ID_WITH_TRACK = 408; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int ANNOUNCEMENTS = 700; private static final int ANNOUNCEMENTS_ID = 701; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "announcements", ANNOUNCEMENTS); matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { mOpenHelper = new ScheduleDatabase(getContext()); return true; } private void deleteDatabase() { // TODO: wait for content provider operations to finish, then tear down mOpenHelper.close(); Context context = getContext(); ScheduleDatabase.deleteDatabase(context); mOpenHelper = new ScheduleDatabase(getContext()); } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case BLOCKS_ID_SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_WITH_TRACK: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SESSIONS_ID_WITH_TRACK: return Sessions.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; case ANNOUNCEMENTS: return Announcements.CONTENT_TYPE; case ANNOUNCEMENTS_ID: return Announcements.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case ANNOUNCEMENTS: { db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return Announcements.buildAnnouncementUri(values .getAsString(Announcements.ANNOUNCEMENT_ID)); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).update(db, values); boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri); getContext().getContentResolver().notifyChange(uri, null, syncToNetwork); return retVal; } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { LOGV(TAG, "delete(uri=" + uri + ")"); if (uri == ScheduleContract.BASE_CONTENT_URI) { // Handle whole database deletes (e.g. when signing out) deleteDatabase(); getContext().getContentResolver().notifyChange(uri, null, false); return 1; } final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).delete(db); getContext().getContentResolver().notifyChange(uri, null, !ScheduleContract.hasCallerIsSyncAdapterParameter(uri)); return retVal; } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case ANNOUNCEMENTS: { return builder.table(Tables.ANNOUNCEMENTS); } case ANNOUNCEMENTS_ID: { final String announcementId = Announcements.getAnnouncementId(uri); return builder.table(Tables.ANNOUNCEMENTS) .where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder .table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID) .map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE) .map(Blocks.STARRED_SESSION_HASHTAGS, Subquery.BLOCK_STARRED_SESSION_HASHTAGS) .map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL) .map(Blocks.STARRED_SESSION_LIVESTREAM_URL, Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL) .map(Blocks.STARRED_SESSION_ROOM_NAME, Subquery.BLOCK_STARRED_SESSION_ROOM_NAME) .map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS_STARRED: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId) .where(Qualified.SESSIONS_STARRED + "=1"); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.SESSION_STARRED + "=1"); } case SESSIONS_WITH_TRACK: { return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_NAME, Tables.TRACKS) .mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS); } case SESSIONS_ID_WITH_TRACK: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_NAME, Tables.TRACKS) .mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_STARRED + "=1"); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case ANNOUNCEMENTS: { return builder.table(Tables.ANNOUNCEMENTS); } case ANNOUNCEMENTS_ID: { final String announcementId = Announcements.getAnnouncementId(uri); return builder.table(Tables.ANNOUNCEMENTS) .where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)"; String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT " + Qualified.SESSIONS_LIVESTREAM_URL + " FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM " + Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM " + Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 " + "ORDER BY " + Qualified.SESSIONS_TITLE + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED; String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE; String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS; String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL; String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL; String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME; String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.util.ParserUtils; import android.app.SearchManager; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.text.TextUtils; import android.text.format.DateUtils; import java.util.List; /** * Contract class for interacting with {@link ScheduleProvider}. Unless * otherwise noted, all time-based fields are milliseconds since epoch and can * be compared against {@link System#currentTimeMillis()}. * <p> * The backing {@link android.content.ContentProvider} assumes that {@link Uri} * are generated using stronger {@link String} identifiers, instead of * {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during * sync. */ public class ScheduleContract { /** * Special value for {@link SyncColumns#UPDATED} indicating that an entry * has never been updated, or doesn't exist yet. */ public static final long UPDATED_NEVER = -2; /** * Special value for {@link SyncColumns#UPDATED} indicating that the last * update time is unknown, usually when inserted from a local file source. */ public static final long UPDATED_UNKNOWN = -1; public interface SyncColumns { /** Last time this entry was updated or synchronized. */ String UPDATED = "updated"; } interface BlocksColumns { /** Unique string identifying this block of time. */ String BLOCK_ID = "block_id"; /** Title describing this block of time. */ String BLOCK_TITLE = "block_title"; /** Time when this block starts. */ String BLOCK_START = "block_start"; /** Time when this block ends. */ String BLOCK_END = "block_end"; /** Type describing this block. */ String BLOCK_TYPE = "block_type"; /** Extra string metadata for the block. */ String BLOCK_META = "block_meta"; } interface TracksColumns { /** Unique string identifying this track. */ String TRACK_ID = "track_id"; /** Name describing this track. */ String TRACK_NAME = "track_name"; /** Color used to identify this track, in {@link Color#argb} format. */ String TRACK_COLOR = "track_color"; /** Body of text explaining this track in detail. */ String TRACK_ABSTRACT = "track_abstract"; } interface RoomsColumns { /** Unique string identifying this room. */ String ROOM_ID = "room_id"; /** Name describing this room. */ String ROOM_NAME = "room_name"; /** Building floor this room exists on. */ String ROOM_FLOOR = "room_floor"; } interface SessionsColumns { /** Unique string identifying this session. */ String SESSION_ID = "session_id"; /** The type of session (session, keynote, codelab, etc). */ String SESSION_TYPE = "session_type"; /** Difficulty level of the session. */ String SESSION_LEVEL = "session_level"; /** Title describing this track. */ String SESSION_TITLE = "session_title"; /** Body of text explaining this session in detail. */ String SESSION_ABSTRACT = "session_abstract"; /** Requirements that attendees should meet. */ String SESSION_REQUIREMENTS = "session_requirements"; /** Keywords/tags for this session. */ String SESSION_TAGS = "session_keywords"; /** Hashtag for this session. */ String SESSION_HASHTAGS = "session_hashtag"; /** Full URL to session online. */ String SESSION_URL = "session_url"; /** Full URL to YouTube. */ String SESSION_YOUTUBE_URL = "session_youtube_url"; /** Full URL to PDF. */ String SESSION_PDF_URL = "session_pdf_url"; /** Full URL to official session notes. */ String SESSION_NOTES_URL = "session_notes_url"; /** User-specific flag indicating starred status. */ String SESSION_STARRED = "session_starred"; /** Key for session Calendar event. (Used in ICS or above) */ String SESSION_CAL_EVENT_ID = "session_cal_event_id"; /** The YouTube live stream URL. */ String SESSION_LIVESTREAM_URL = "session_livestream_url"; } interface SpeakersColumns { /** Unique string identifying this speaker. */ String SPEAKER_ID = "speaker_id"; /** Name of this speaker. */ String SPEAKER_NAME = "speaker_name"; /** Profile photo of this speaker. */ String SPEAKER_IMAGE_URL = "speaker_image_url"; /** Company this speaker works for. */ String SPEAKER_COMPANY = "speaker_company"; /** Body of text describing this speaker in detail. */ String SPEAKER_ABSTRACT = "speaker_abstract"; /** Full URL to the speaker's profile. */ String SPEAKER_URL = "speaker_url"; } interface VendorsColumns { /** Unique string identifying this vendor. */ String VENDOR_ID = "vendor_id"; /** Name of this vendor. */ String VENDOR_NAME = "vendor_name"; /** Location or city this vendor is based in. */ String VENDOR_LOCATION = "vendor_location"; /** Body of text describing this vendor. */ String VENDOR_DESC = "vendor_desc"; /** Link to vendor online. */ String VENDOR_URL = "vendor_url"; /** Body of text describing the product of this vendor. */ String VENDOR_PRODUCT_DESC = "vendor_product_desc"; /** Link to vendor logo. */ String VENDOR_LOGO_URL = "vendor_logo_url"; /** User-specific flag indicating starred status. */ String VENDOR_STARRED = "vendor_starred"; } interface AnnouncementsColumns { /** Unique string identifying this announcment. */ String ANNOUNCEMENT_ID = "announcement_id"; /** Title of the announcement. */ String ANNOUNCEMENT_TITLE = "announcement_title"; /** Summary of the announcement. */ String ANNOUNCEMENT_SUMMARY = "announcement_summary"; /** Track announcement belongs to. */ String ANNOUNCEMENT_TRACKS = "announcement_tracks"; /** Full URL for the announcement. */ String ANNOUNCEMENT_URL = "announcement_url"; /** Date of the announcement. */ String ANNOUNCEMENT_DATE = "announcement_date"; } public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_BLOCKS = "blocks"; private static final String PATH_AT = "at"; private static final String PATH_BETWEEN = "between"; private static final String PATH_TRACKS = "tracks"; private static final String PATH_ROOMS = "rooms"; private static final String PATH_SESSIONS = "sessions"; private static final String PATH_WITH_TRACK = "with_track"; private static final String PATH_STARRED = "starred"; private static final String PATH_SPEAKERS = "speakers"; private static final String PATH_VENDORS = "vendors"; private static final String PATH_ANNOUNCEMENTS = "announcements"; private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH_SUGGEST = "search_suggest_query"; /** * Blocks are generic timeslots that {@link Sessions} and other related * events fall into. */ public static class Blocks implements BlocksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.block"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.block"; /** Count of {@link Sessions} inside given block. */ public static final String SESSIONS_COUNT = "sessions_count"; /** * Flag indicating the number of sessions inside this block that have * {@link Sessions#SESSION_STARRED} set. */ public static final String NUM_STARRED_SESSIONS = "num_starred_sessions"; /** * The {@link Sessions#SESSION_ID} of the first starred session in this * block. */ public static final String STARRED_SESSION_ID = "starred_session_id"; /** * The {@link Sessions#SESSION_TITLE} of the first starred session in * this block. */ public static final String STARRED_SESSION_TITLE = "starred_session_title"; /** * The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred * session in this block. */ public static final String STARRED_SESSION_LIVESTREAM_URL = "starred_session_livestream_url"; /** * The {@link Rooms#ROOM_NAME} of the first starred session in this * block. */ public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name"; /** * The {@link Rooms#ROOM_ID} of the first starred session in this block. */ public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id"; /** * The {@link Sessions#SESSION_HASHTAGS} of the first starred session in * this block. */ public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags"; /** * The {@link Sessions#SESSION_URL} of the first starred session in this * block. */ public static final String STARRED_SESSION_URL = "starred_session_url"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, " + BlocksColumns.BLOCK_END + " ASC"; public static final String EMPTY_SESSIONS_SELECTION = "(" + BLOCK_TYPE + " = '" + ParserUtils.BLOCK_TYPE_SESSION + "' OR " + BLOCK_TYPE + " = '" + ParserUtils.BLOCK_TYPE_CODE_LAB + "') AND " + SESSIONS_COUNT + " = 0"; /** Build {@link Uri} for requested {@link #BLOCK_ID}. */ public static Uri buildBlockUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references starred {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildStarredSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS) .appendPath(PATH_STARRED).build(); } /** * Build {@link Uri} that references any {@link Blocks} that occur * between the requested time boundaries. */ public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) { return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath( String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build(); } /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */ public static String getBlockId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #BLOCK_ID} that will always match the requested * {@link Blocks} details. */ public static String generateBlockId(long startTime, long endTime) { startTime /= DateUtils.SECOND_IN_MILLIS; endTime /= DateUtils.SECOND_IN_MILLIS; return ParserUtils.sanitizeId(startTime + "-" + endTime); } } /** * Tracks are overall categories for {@link Sessions} and {@link Vendors}, * such as "Android" or "Enterprise." */ public static class Tracks implements TracksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.track"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.track"; /** "All tracks" ID. */ public static final String ALL_TRACK_ID = "all"; public static final String CODELABS_TRACK_ID = generateTrackId("Code Labs"); public static final String TECH_TALK_TRACK_ID = generateTrackId("Tech Talk"); /** Count of {@link Sessions} inside given track. */ public static final String SESSIONS_COUNT = "sessions_count"; /** Count of {@link Vendors} inside given track. */ public static final String VENDORS_COUNT = "vendors_count"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC"; /** Build {@link Uri} for requested {@link #TRACK_ID}. */ public static Uri buildTrackUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #TRACK_ID}. */ public static Uri buildSessionsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Vendors} associated with * the requested {@link #TRACK_ID}. */ public static Uri buildVendorsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build(); } /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */ public static String getTrackId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #TRACK_ID} that will always match the requested * {@link Tracks} details. */ public static String generateTrackId(String name) { return ParserUtils.sanitizeId(name); } } /** * Rooms are physical locations at the conference venue. */ public static class Rooms implements RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.room"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.room"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, " + RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ROOM_ID}. */ public static Uri buildRoomUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #ROOM_ID}. */ public static Uri buildSessionsDirUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */ public static String getRoomId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Each session is a block of time that has a {@link Tracks}, a * {@link Rooms}, and zero or more {@link Speakers}. */ public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session"; public static final String BLOCK_ID = "block_id"; public static final String ROOM_ID = "room_id"; public static final String SEARCH_SNIPPET = "search_snippet"; // TODO: shortcut primary track to offer sub-sorting here /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC," + SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC"; public static final String LIVESTREAM_SELECTION = SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''"; // Used to fetch sessions for a particular time public static final String AT_TIME_SELECTION = BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?"; // Builds selectionArgs for {@link AT_TIME_SELECTION} public static String[] buildAtTimeSelectionArgs(long time) { final String timeString = String.valueOf(time); return new String[] { timeString, timeString }; } // Used to fetch upcoming sessions public static final String UPCOMING_SELECTION = BLOCK_START + " = (select min(" + BLOCK_START + ") from " + ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION + " and " + BLOCK_START + " >" + " ?)"; // Builds selectionArgs for {@link UPCOMING_SELECTION} public static String[] buildUpcomingSelectionArgs(long minTime) { return new String[] { String.valueOf(minTime) }; } /** Build {@link Uri} for requested {@link #SESSION_ID}. */ public static Uri buildSessionUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** * Build {@link Uri} that references any {@link Speakers} associated * with the requested {@link #SESSION_ID}. */ public static Uri buildSpeakersDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build(); } /** * Build {@link Uri} that includes track detail with list of sessions. */ public static Uri buildWithTracksUri() { return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build(); } /** * Build {@link Uri} that includes track detail for a specific session. */ public static Uri buildWithTracksUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId) .appendPath(PATH_WITH_TRACK).build(); } /** * Build {@link Uri} that references any {@link Tracks} associated with * the requested {@link #SESSION_ID}. */ public static Uri buildTracksDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build(); } public static Uri buildSessionsAtDirUri(long time) { return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time)) .build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } } /** * Speakers are individual people that lead {@link Sessions}. */ public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.speaker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.speaker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */ public static Uri buildSpeakerUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #SPEAKER_ID}. */ public static Uri buildSessionsDirUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */ public static String getSpeakerId(Uri uri) { return uri.getPathSegments().get(1); } } /** * Each vendor is a company appearing at the conference that may be * associated with a specific {@link Tracks}. */ public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.vendor"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.vendor"; /** {@link Tracks#TRACK_ID} that this vendor belongs to. */ public static final String TRACK_ID = "track_id"; public static final String SEARCH_SNIPPET = "search_snippet"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #VENDOR_ID}. */ public static Uri buildVendorUri(String vendorId) { return CONTENT_URI.buildUpon().appendPath(vendorId).build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */ public static String getVendorId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #VENDOR_ID} that will always match the requested * {@link Vendors} details. */ public static String generateVendorId(String companyName) { return ParserUtils.sanitizeId(companyName); } } /** * Announcements of breaking news */ public static class Announcements implements AnnouncementsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.announcement"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.announcement"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */ public static Uri buildAnnouncementUri(String announcementId) { return CONTENT_URI.buildUpon().appendPath(announcementId).build(); } /** * Build {@link Uri} that references any {@link Announcements} * associated with the requested {@link #ANNOUNCEMENT_ID}. */ public static Uri buildAnnouncementsDirUri(String announcementId) { return CONTENT_URI.buildUpon().appendPath(announcementId) .appendPath(PATH_ANNOUNCEMENTS).build(); } /** * Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}. */ public static String getAnnouncementId(Uri uri) { return uri.getPathSegments().get(1); } } public static class SearchSuggest { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build(); public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1 + " COLLATE NOCASE ASC"; } public static Uri addCallerIsSyncAdapterParameter(Uri uri) { return uri.buildUpon().appendQueryParameter( ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); } public static boolean hasCallerIsSyncAdapterParameter(Uri uri) { return TextUtils.equals("true", uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER)); } private ScheduleContract() { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.calendar; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.app.IntentService; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.RemoteException; import android.provider.CalendarContract; import android.text.TextUtils; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background {@link android.app.Service} that adds or removes session Calendar events through * the {@link CalendarContract} API available in Android 4.0 or above. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class SessionCalendarService extends IntentService { private static final String TAG = makeLogTag(SessionCalendarService.class); public static final String ACTION_ADD_SESSION_CALENDAR = "com.google.android.apps.iosched.action.ADD_SESSION_CALENDAR"; public static final String ACTION_REMOVE_SESSION_CALENDAR = "com.google.android.apps.iosched.action.REMOVE_SESSION_CALENDAR"; public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR = "com.google.android.apps.iosched.action.UPDATE_ALL_SESSIONS_CALENDAR"; public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED = "com.google.android.apps.iosched.action.UPDATE_CALENDAR_COMPLETED"; public static final String ACTION_CLEAR_ALL_SESSIONS_CALENDAR = "com.google.android.apps.iosched.action.CLEAR_ALL_SESSIONS_CALENDAR"; public static final String EXTRA_ACCOUNT_NAME = "com.google.android.apps.iosched.extra.ACCOUNT_NAME"; public static final String EXTRA_SESSION_BLOCK_START = "com.google.android.apps.iosched.extra.SESSION_BLOCK_START"; public static final String EXTRA_SESSION_BLOCK_END = "com.google.android.apps.iosched.extra.SESSION_BLOCK_END"; public static final String EXTRA_SESSION_TITLE = "com.google.android.apps.iosched.extra.SESSION_TITLE"; public static final String EXTRA_SESSION_ROOM = "com.google.android.apps.iosched.extra.SESSION_ROOM"; private static final long INVALID_CALENDAR_ID = -1; // TODO: localize private static final String CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION = "%added by Google I/O 2012%"; public SessionCalendarService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { final String action = intent.getAction(); final ContentResolver resolver = getContentResolver(); boolean isAddEvent = false; if (ACTION_ADD_SESSION_CALENDAR.equals(action)) { isAddEvent = true; } else if (ACTION_REMOVE_SESSION_CALENDAR.equals(action)) { isAddEvent = false; } else if (ACTION_UPDATE_ALL_SESSIONS_CALENDAR.equals(action)) { try { getContentResolver().applyBatch(CalendarContract.AUTHORITY, processAllSessionsCalendar(resolver, getCalendarId(intent))); sendBroadcast(new Intent( SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED)); } catch (RemoteException e) { LOGE(TAG, "Error adding all sessions to Google Calendar", e); } catch (OperationApplicationException e) { LOGE(TAG, "Error adding all sessions to Google Calendar", e); } } else if (ACTION_CLEAR_ALL_SESSIONS_CALENDAR.equals(action)) { try { getContentResolver().applyBatch(CalendarContract.AUTHORITY, processClearAllSessions(resolver, getCalendarId(intent))); } catch (RemoteException e) { LOGE(TAG, "Error clearing all sessions from Google Calendar", e); } catch (OperationApplicationException e) { LOGE(TAG, "Error clearing all sessions from Google Calendar", e); } } else { return; } final Uri uri = intent.getData(); final Bundle extras = intent.getExtras(); if (uri == null || extras == null) { return; } try { resolver.applyBatch(CalendarContract.AUTHORITY, processSessionCalendar(resolver, getCalendarId(intent), isAddEvent, uri, extras.getLong(EXTRA_SESSION_BLOCK_START), extras.getLong(EXTRA_SESSION_BLOCK_END), extras.getString(EXTRA_SESSION_TITLE), extras.getString(EXTRA_SESSION_ROOM))); } catch (RemoteException e) { LOGE(TAG, "Error adding session to Google Calendar", e); } catch (OperationApplicationException e) { LOGE(TAG, "Error adding session to Google Calendar", e); } } /** * Gets the currently-logged in user's Google Calendar, or the Google Calendar for the user * specified in the given intent's {@link #EXTRA_ACCOUNT_NAME}. */ private long getCalendarId(Intent intent) { final String accountName; if (intent != null && intent.hasExtra(EXTRA_ACCOUNT_NAME)) { accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME); } else { accountName = AccountUtils.getChosenAccountName(this); } if (TextUtils.isEmpty(accountName)) { return INVALID_CALENDAR_ID; } // TODO: The calendar ID should be stored in shared preferences upon choosing an account. Cursor calendarsCursor = getContentResolver().query( CalendarContract.Calendars.CONTENT_URI, new String[]{"_id"}, // TODO: Handle case where the calendar is not displayed or not sync'd "account_name = ownerAccount and account_name = ?", new String[]{accountName}, null); long calendarId = INVALID_CALENDAR_ID; if (calendarsCursor != null && calendarsCursor.moveToFirst()) { calendarId = calendarsCursor.getLong(0); calendarsCursor.close(); } return calendarId; } private String makeCalendarEventTitle(String sessionTitle) { return sessionTitle + getResources().getString(R.string.session_calendar_suffix); } /** * Processes all sessions in the * {@link com.google.android.apps.iosched.provider.ScheduleProvider}, adding or removing * calendar events to/from the specified Google Calendar depending on whether a session is * in the user's schedule or not. */ private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver, final long calendarId) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { return batch; } // Retrieves all sessions. For each session, add to Calendar if starred and attempt to // remove from Calendar if unstarred. Cursor cursor = resolver.query( ScheduleContract.Sessions.CONTENT_URI, SessionsQuery.PROJECTION, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { Uri uri = ScheduleContract.Sessions.buildSessionUri( Long.valueOf(cursor.getLong(0)).toString()); boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_STARRED) == 1); if (isAddEvent) { batch.addAll(processSessionCalendar(resolver, calendarId, isAddEvent, uri, cursor.getLong(SessionsQuery.BLOCK_START), cursor.getLong(SessionsQuery.BLOCK_END), cursor.getString(SessionsQuery.SESSION_TITLE), cursor.getString(SessionsQuery.ROOM_NAME))); } } cursor.close(); } return batch; } /** * Adds or removes a single session to/from the specified Google Calendar. */ private ArrayList<ContentProviderOperation> processSessionCalendar( final ContentResolver resolver, final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { return batch; } final String calendarEventTitle = makeCalendarEventTitle(sessionTitle); Cursor cursor; ContentValues values = new ContentValues(); // Add Calendar event. if (isAddEvent) { if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) { LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters."); return batch; } // Check if the calendar event exists first. If it does, we don't want to add a // duplicate one. cursor = resolver.query( CalendarContract.Events.CONTENT_URI, // URI new String[] {CalendarContract.Events._ID}, // Projection CalendarContract.Events.CALENDAR_ID + "=? and " // Selection + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART + ">=? and " + CalendarContract.Events.DTEND + "<=?", new String[]{ // Selection args Long.valueOf(calendarId).toString(), calendarEventTitle, Long.toString(UIUtils.CONFERENCE_START_MILLIS), Long.toString(UIUtils.CONFERENCE_END_MILLIS) }, null); long newEventId = -1; if (cursor != null && cursor.moveToFirst()) { // Calendar event already exists for this session. newEventId = cursor.getLong(0); cursor.close(); } else { // Calendar event doesn't exist, create it. // NOTE: we can't use batch processing here because we need the result of // the insert. values.clear(); values.put(CalendarContract.Events.DTSTART, sessionBlockStart); values.put(CalendarContract.Events.DTEND, sessionBlockEnd); values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom); values.put(CalendarContract.Events.TITLE, calendarEventTitle); values.put(CalendarContract.Events.CALENDAR_ID, calendarId); values.put(CalendarContract.Events.EVENT_TIMEZONE, UIUtils.CONFERENCE_TIME_ZONE.getID()); Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values); String eventId = eventUri.getLastPathSegment(); if (eventId == null) { return batch; // Should be empty at this point } newEventId = Long.valueOf(eventId); // Since we're adding session reminder to system notification, we're not creating // Calendar event reminders. If we were to create Calendar event reminders, this // is how we would do it. //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId)); //values.put(CalendarContract.Reminders.MINUTES, 10); //values.put(CalendarContract.Reminders.METHOD, // CalendarContract.Reminders.METHOD_ALERT); // Or default? //cr.insert(CalendarContract.Reminders.CONTENT_URI, values); //values.clear(); } // Update the session in our own provider with the newly created calendar event ID. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId); resolver.update(sessionUri, values, null, null); } else { // Remove Calendar event, if exists. // Get the event calendar id. cursor = resolver.query(sessionUri, new String[] {ScheduleContract.Sessions.SESSION_CAL_EVENT_ID}, null, null, null); long calendarEventId = -1; if (cursor != null && cursor.moveToFirst()) { calendarEventId = cursor.getLong(0); cursor.close(); } // Try to remove the Calendar Event based on key. If successful, move on; // otherwise, remove the event based on Event title. int affectedRows = 0; if (calendarEventId != -1) { affectedRows = resolver.delete( CalendarContract.Events.CONTENT_URI, CalendarContract.Events._ID + "=?", new String[]{Long.valueOf(calendarEventId).toString()}); } if (affectedRows == 0) { resolver.delete(CalendarContract.Events.CONTENT_URI, String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), new String[]{Long.valueOf(calendarId).toString(), calendarEventTitle, Long.valueOf(sessionBlockStart).toString(), Long.valueOf(sessionBlockEnd).toString()}); } // Remove the session and calendar event association. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null); resolver.update(sessionUri, values, null, null); } return batch; } /** * Removes all calendar entries associated with Google I/O 2012. */ private ArrayList<ContentProviderOperation> processClearAllSessions( ContentResolver resolver, long calendarId) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user. Stop here. if (calendarId == INVALID_CALENDAR_ID) { return batch; } // Delete all calendar entries matching the given title within the given time period batch.add(ContentProviderOperation .newDelete(CalendarContract.Events.CONTENT_URI) .withSelection( CalendarContract.Events.CALENDAR_ID + " = ? and " + CalendarContract.Events.TITLE + " LIKE ? and " + CalendarContract.Events.DTSTART + ">= ? and " + CalendarContract.Events.DTEND + "<= ?", new String[]{ Long.toString(calendarId), CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION, Long.toString(UIUtils.CONFERENCE_START_MILLIS), Long.toString(UIUtils.CONFERENCE_END_MILLIS) }) .build()); return batch; } private interface SessionsQuery { String[] PROJECTION = { ScheduleContract.Sessions._ID, ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.ROOM_NAME, ScheduleContract.Sessions.SESSION_STARRED, }; int _ID = 0; int BLOCK_START = 1; int BLOCK_END = 2; int SESSION_TITLE = 3; int ROOM_NAME = 4; int SESSION_STARRED = 5; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.calendar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred * session blocks. */ public class SessionAlarmReceiver extends BroadcastReceiver { public static final String TAG = makeLogTag(SessionAlarmReceiver.class); @Override public void onReceive(Context context, Intent intent) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS, null, context, SessionAlarmService.class); context.startService(scheduleIntent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.calendar; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.support.v4.app.NotificationCompat; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background service to handle scheduling of starred session notification via * {@link android.app.AlarmManager}. */ public class SessionAlarmService extends IntentService { private static final String TAG = makeLogTag(SessionAlarmService.class); public static final String ACTION_NOTIFY_SESSION = "com.google.android.apps.iosched.action.NOTIFY_SESSION"; public static final String ACTION_SCHEDULE_STARRED_BLOCK = "com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK"; public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS = "com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS"; public static final String EXTRA_SESSION_START = "com.google.android.apps.iosched.extra.SESSION_START"; public static final String EXTRA_SESSION_END = "com.google.android.apps.iosched.extra.SESSION_END"; public static final String EXTRA_SESSION_ALARM_OFFSET = "com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET"; private static final int NOTIFICATION_ID = 100; // pulsate every 1 second, indicating a relatively high degree of urgency private static final int NOTIFICATION_LED_ON_MS = 100; private static final int NOTIFICATION_LED_OFF_MS = 1000; private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan private static final long ONE_MINUTE_MILLIS = 1 * 60 * 1000; private static final long TEN_MINUTES_MILLIS = 10 * ONE_MINUTE_MILLIS; private static final long UNDEFINED_ALARM_OFFSET = -1; public SessionAlarmService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { final String action = intent.getAction(); if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) { scheduleAllStarredBlocks(); return; } final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, -1); if (sessionStart == -1) { return; } final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, -1); if (sessionEnd == -1) { return; } final long sessionAlarmOffset = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, UNDEFINED_ALARM_OFFSET); if (ACTION_NOTIFY_SESSION.equals(action)) { notifySession(sessionStart, sessionEnd, sessionAlarmOffset); } else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) { scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset); } } private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(NOTIFICATION_ID); final long currentTime = System.currentTimeMillis(); // If the session is already started, do not schedule system notification. if (currentTime > sessionStart) { return; } // By default, sets alarm to go off at 10 minutes before session start time. If alarm // offset is provided, alarm is set to go off by that much time from now. long alarmTime; if (alarmOffset == UNDEFINED_ALARM_OFFSET) { alarmTime = sessionStart - TEN_MINUTES_MILLIS; } else { alarmTime = currentTime + alarmOffset; } final Intent alarmIntent = new Intent( ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class); // Setting data to ensure intent's uniqueness for different session start times. alarmIntent.setData( new Uri.Builder() .authority(ScheduleContract.CONTENT_AUTHORITY) .path(String.valueOf(sessionStart)) .build()); alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // Schedule an alarm to be fired to notify user of added sessions are about to begin. am.set(AlarmManager.RTC_WAKEUP, alarmTime, PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT)); } /** * Constructs and triggers system notification for when starred sessions are about to begin. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) { long currentTime = System.currentTimeMillis(); if (sessionStart < currentTime) { return; } // Avoid repeated notifications. if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock( this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) { return; } final ContentResolver resolver = getContentResolver(); final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri( ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd)); Cursor cursor = resolver.query(starredBlockUri, new String[]{ ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Sessions.SESSION_TITLE }, null, null, null); int starredCount = 0; ArrayList<String> starredSessionTitles = new ArrayList<String>(); while (cursor.moveToNext()) { starredSessionTitles.add(cursor.getString(1)); starredCount = cursor.getInt(0); } if (starredCount < 1) { return; } // Generates the pending intent which gets fired when the user touches on the notification. Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri); sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Resources res = getResources(); String contentText; int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000; if (minutesLeft < 1) { minutesLeft = 1; } if (starredCount == 1) { contentText = res.getString(R.string.session_notification_text_1, minutesLeft); } else { contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft, starredCount - 1); } // Construct a notification. Use Jelly Bean (API 16) rich notifications if possible. Notification notification; if (UIUtils.hasJellyBean()) { // Rich notifications Notification.Builder builder = new Notification.Builder(this) .setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights( SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification) .setContentIntent(pi) .setPriority(Notification.PRIORITY_MAX) .setAutoCancel(true); if (minutesLeft > 5) { builder.addAction(R.drawable.ic_alarm_holo_dark, String.format(res.getString(R.string.snooze_x_min), 5), createSnoozeIntent(sessionStart, sessionEnd, 5)); } Notification.InboxStyle richNotification = new Notification.InboxStyle( builder) .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft, starredCount)); // Adds starred sessions starting at this time block to the notification. for (int i = 0; i < starredCount; i++) { richNotification.addLine(starredSessionTitles.get(i)); } notification = richNotification.build(); } else { // Pre-Jelly Bean non-rich notifications notification = new NotificationCompat.Builder(this) .setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights( SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification) .setContentIntent(pi) .getNotification(); } NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, notification); } private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd, final int snoozeMinutes) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, this, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, snoozeMinutes * ONE_MINUTE_MILLIS); return PendingIntent.getService(this, 0, scheduleIntent, PendingIntent.FLAG_CANCEL_CURRENT); } private void scheduleAllStarredBlocks() { final Cursor cursor = getContentResolver().query( ScheduleContract.Sessions.CONTENT_STARRED_URI, new String[] { "distinct " + ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END }, null, null, null); if (cursor == null) { return; } while (cursor.moveToNext()) { final long sessionStart = cursor.getLong(0); final long sessionEnd = cursor.getLong(1); scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; /** * {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing * then against fractional dimensions of the source view. * <p> * This is particularly useful when you want to define a rectangle in terms of * the source dimensions, but when those dimensions might change due to pending * or future layout passes. * <p> * One example is catching touches that occur in the top-right quadrant of * {@code sourceParent}, and relaying them to {@code targetChild}. This could be * done with: <code> * FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f)); * </code> */ public class FractionalTouchDelegate extends TouchDelegate { private View mSource; private View mTarget; private RectF mSourceFraction; private Rect mScrap = new Rect(); /** Cached full dimensions of {@link #mSource}. */ private Rect mSourceFull = new Rect(); /** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */ private Rect mSourcePartial = new Rect(); private boolean mDelegateTargeted; public FractionalTouchDelegate(View source, View target, RectF sourceFraction) { super(new Rect(0, 0, 0, 0), target); mSource = source; mTarget = target; mSourceFraction = sourceFraction; } /** * Helper to create and setup a {@link FractionalTouchDelegate} between the * given {@link View}. * * @param source Larger source {@link View}, usually a parent, that will be * assigned {@link View#setTouchDelegate(TouchDelegate)}. * @param target Smaller target {@link View} which will receive * {@link MotionEvent} that land in requested fractional area. * @param sourceFraction Fractional area projected onto source {@link View} * which determines when {@link MotionEvent} will be passed to * target {@link View}. */ public static void setupDelegate(View source, View target, RectF sourceFraction) { source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction)); } /** * Consider updating {@link #mSourcePartial} when {@link #mSource} * dimensions have changed. */ private void updateSourcePartial() { mSource.getHitRect(mScrap); if (!mScrap.equals(mSourceFull)) { // Copy over and calculate fractional rectangle mSourceFull.set(mScrap); final int width = mSourceFull.width(); final int height = mSourceFull.height(); mSourcePartial.left = (int) (mSourceFraction.left * width); mSourcePartial.top = (int) (mSourceFraction.top * height); mSourcePartial.right = (int) (mSourceFraction.right * width); mSourcePartial.bottom = (int) (mSourceFraction.bottom * height); } } @Override public boolean onTouchEvent(MotionEvent event) { updateSourcePartial(); // The logic below is mostly copied from the parent class, since we // can't update private mBounds variable. // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob; // f=core/java/android/view/TouchDelegate.java;hb=eclair#l98 final Rect sourcePartial = mSourcePartial; final View target = mTarget; int x = (int)event.getX(); int y = (int)event.getY(); boolean sendToDelegate = false; boolean hit = true; boolean handled = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (sourcePartial.contains(x, y)) { mDelegateTargeted = true; sendToDelegate = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: sendToDelegate = mDelegateTargeted; if (sendToDelegate) { if (!sourcePartial.contains(x, y)) { hit = false; } } break; case MotionEvent.ACTION_CANCEL: sendToDelegate = mDelegateTargeted; mDelegateTargeted = false; break; } if (sendToDelegate) { if (hit) { event.setLocation(target.getWidth() / 2, target.getHeight() / 2); } else { event.setLocation(-1, -1); } handled = target.dispatchTouchEvent(event); } return handled; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.appwidget.MyScheduleWidgetProvider; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.sync.ScheduleUpdaterService; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SocialStreamActivity; import com.google.android.apps.iosched.ui.SocialStreamFragment; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.Activity; import android.content.AsyncQueryHandler; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v4.app.ShareCompat; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper class for dealing with common actions to take on a session. */ public final class SessionsHelper { private static final String TAG = makeLogTag(SessionsHelper.class); private final Activity mActivity; public SessionsHelper(Activity activity) { mActivity = activity; } public void startMapActivity(String roomId) { Intent intent = new Intent(mActivity.getApplicationContext(), UIUtils.getMapActivityClass(mActivity)); intent.putExtra(MapFragment.EXTRA_ROOM, roomId); mActivity.startActivity(intent); } public Intent createShareIntent(int messageTemplateResId, String title, String hashtags, String url) { ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(mActivity) .setType("text/plain") .setText(mActivity.getString(messageTemplateResId, title, UIUtils.getSessionHashtagsString(hashtags), url)); return builder.getIntent(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void tryConfigureShareMenuItem(MenuItem menuItem, int messageTemplateResId, final String title, String hashtags, String url) { // TODO: uncomment pending ShareActionProvider fixes for split AB // if (UIUtils.hasICS()) { // ActionProvider itemProvider = menuItem.getActionProvider(); // ShareActionProvider provider; // if (!(itemProvider instanceof ShareActionProvider)) { // provider = new ShareActionProvider(mActivity); // } else { // provider = (ShareActionProvider) itemProvider; // } // provider.setShareIntent(createShareIntent(messageTemplateResId, title, hashtags, url)); // provider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() { // @Override // public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) { // EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L); // LOGD("Tracker", "Shared: " + title); // return false; // } // }); // // menuItem.setActionProvider(provider); // } } public void shareSession(Context context, int messageTemplateResId, String title, String hashtags, String url) { EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L); LOGD("Tracker", "Shared: " + title); context.startActivity(Intent.createChooser( createShareIntent(messageTemplateResId, title, hashtags, url), context.getString(R.string.title_share))); } public void setSessionStarred(Uri sessionUri, boolean starred, String title) { LOGD(TAG, "setSessionStarred uri=" + sessionUri + " starred=" + starred + " title=" + title); sessionUri = ScheduleContract.addCallerIsSyncAdapterParameter(sessionUri); final ContentValues values = new ContentValues(); values.put(ScheduleContract.Sessions.SESSION_STARRED, starred); AsyncQueryHandler handler = new AsyncQueryHandler(mActivity.getContentResolver()) { }; handler.startUpdate(-1, null, sessionUri, values, null, null); EasyTracker.getTracker().trackEvent( "Session", starred ? "Starred" : "Unstarred", title, 0L); // Because change listener is set to null during initialization, these // won't fire on pageview. final Intent refreshIntent = new Intent(mActivity, MyScheduleWidgetProvider.class); refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION); mActivity.sendBroadcast(refreshIntent); // Sync to the cloud. final Intent updateServerIntent = new Intent(mActivity, ScheduleUpdaterService.class); updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_SESSION_ID, ScheduleContract.Sessions.getSessionId(sessionUri)); updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_IN_SCHEDULE, starred); mActivity.startService(updateServerIntent); } public void startSocialStream(String hashtags) { Intent intent = new Intent(mActivity, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, hashtags); mActivity.startActivity(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.ArrayList; import java.util.Collections; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public class Lists { /** * Creates an empty {@code ArrayList} instance. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } /** * Creates a resizable {@code ArrayList} instance containing the given * elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of * {@code Base}, not of {@code Base} itself. To get around this, you must * use: * * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} * * @param elements the elements that the list should contain, in order * @return a newly-created {@code ArrayList} containing those elements */ public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.Html; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebView; import android.widget.TextView; /** * A set of helper methods for showing contextual help information in the app. */ public class HelpUtils { public static boolean hasSeenTutorial(final Context context, String id) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean("seen_tutorial_" + id, false); } private static void setSeenTutorial(final Context context, final String id) { //noinspection unchecked new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean("seen_tutorial_" + id, true).commit(); return null; } }.execute(); } public static void maybeShowAddToScheduleTutorial(FragmentActivity activity) { if (hasSeenTutorial(activity, "add_to_schedule")) { return; } // DialogFragment.show() will take care of adding the fragment // in a transaction. We also want to remove any currently showing // dialog, so make our own transaction and take care of that here. FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_add_to_schedule"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new AddToScheduleTutorialDialog().show(ft, "dialog_add_to_schedule"); setSeenTutorial(activity, "add_to_schedule"); } public static class AddToScheduleTutorialDialog extends DialogFragment implements Html.ImageGetter { public AddToScheduleTutorialDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView tutorialBodyView = (TextView) layoutInflater.inflate( R.layout.dialog_tutorial_message, null); tutorialBodyView.setText( Html.fromHtml(getString(R.string.help_add_to_schedule), this, null)); tutorialBodyView.setContentDescription( Html.fromHtml(getString(R.string.help_add_to_schedule_alt))); return new AlertDialog.Builder(getActivity()) .setView(tutorialBodyView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } @Override public Drawable getDrawable(String url) { if ("add_to_schedule".equals(url)) { Resources res = getActivity().getResources(); Drawable d = res.getDrawable(R.drawable.help_add_to_schedule); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } return null; } } public static void showAbout(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_about"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new AboutDialog().show(ft, "dialog_about"); } public static class AboutDialog extends DialogFragment { private static final String VERSION_UNAVAILABLE = "N/A"; public AboutDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Get app version PackageManager pm = getActivity().getPackageManager(); String packageName = getActivity().getPackageName(); String versionName; try { PackageInfo info = pm.getPackageInfo(packageName, 0); versionName = info.versionName; } catch (PackageManager.NameNotFoundException e) { versionName = VERSION_UNAVAILABLE; } // Build the about body view and append the link to see OSS licenses SpannableStringBuilder aboutBody = new SpannableStringBuilder(); aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName))); SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses)); licensesLink.setSpan(new ClickableSpan() { @Override public void onClick(View view) { HelpUtils.showOpenSourceLicenses(getActivity()); } }, 0, licensesLink.length(), 0); aboutBody.append("\n\n"); aboutBody.append(licensesLink); SpannableString eulaLink = new SpannableString(getString(R.string.about_eula)); eulaLink.setSpan(new ClickableSpan() { @Override public void onClick(View view) { HelpUtils.showEula(getActivity()); } }, 0, eulaLink.length(), 0); aboutBody.append("\n\n"); aboutBody.append(eulaLink); LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null); aboutBodyView.setText(aboutBody); aboutBodyView.setMovementMethod(new LinkMovementMethod()); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_about) .setView(aboutBodyView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } } public static void showOpenSourceLicenses(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_licenses"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new OpenSourceLicensesDialog().show(ft, "dialog_licenses"); } public static class OpenSourceLicensesDialog extends DialogFragment { public OpenSourceLicensesDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { WebView webView = new WebView(getActivity()); webView.loadUrl("file:///android_asset/licenses.html"); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.about_licenses) .setView(webView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } } public static void showEula(FragmentActivity activity) { FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog_eula"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); new EulaDialog().show(ft, "dialog_eula"); } public static class EulaDialog extends DialogFragment { public EulaDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal); TextView eulaTextView = new TextView(getActivity()); eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text))); eulaTextView.setMovementMethod(LinkMovementMethod.getInstance()); eulaTextView.setPadding(padding, padding, padding, padding); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.about_eula) .setView(eulaTextView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } ) .create(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications: * -Imported from AOSP frameworks/base/core/java/com/android/internal/content * -Changed package name */ package com.google.android.apps.iosched.util; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Map; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper for building selection clauses for {@link SQLiteDatabase}. Each * appended clause is combined using {@code AND}. This class is <em>not</em> * thread safe. */ public class SelectionBuilder { private static final String TAG = makeLogTag(SelectionBuilder.class); private String mTable = null; private Map<String, String> mProjectionMap = Maps.newHashMap(); private StringBuilder mSelection = new StringBuilder(); private ArrayList<String> mSelectionArgs = Lists.newArrayList(); /** * Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { mTable = null; mSelection.setLength(0); mSelectionArgs.clear(); return this; } /** * Append the given selection clause to the internal state. Each clause is * surrounded with parenthesis and combined using {@code AND}. */ public SelectionBuilder where(String selection, String... selectionArgs) { if (TextUtils.isEmpty(selection)) { if (selectionArgs != null && selectionArgs.length > 0) { throw new IllegalArgumentException( "Valid selection required when including arguments="); } // Shortcut when clause is empty return this; } if (mSelection.length() > 0) { mSelection.append(" AND "); } mSelection.append("(").append(selection).append(")"); if (selectionArgs != null) { Collections.addAll(mSelectionArgs, selectionArgs); } return this; } public SelectionBuilder table(String table) { mTable = table; return this; } private void assertTable() { if (mTable == null) { throw new IllegalStateException("Table not specified"); } } public SelectionBuilder mapToTable(String column, String table) { mProjectionMap.put(column, table + "." + column); return this; } public SelectionBuilder map(String fromColumn, String toClause) { mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); return this; } /** * Return selection string for current internal state. * * @see #getSelectionArgs() */ public String getSelection() { return mSelection.toString(); } /** * Return selection arguments for current internal state. * * @see #getSelection() */ public String[] getSelectionArgs() { return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); } private void mapColumns(String[] columns) { for (int i = 0; i < columns.length; i++) { final String target = mProjectionMap.get(columns[i]); if (target != null) { columns[i] = target; } } } @Override public String toString() { return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { return query(db, columns, null, null, orderBy, null); } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having, String orderBy, String limit) { assertTable(); if (columns != null) mapColumns(columns); LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy, limit); } /** * Execute update using the current internal state as {@code WHERE} clause. */ public int update(SQLiteDatabase db, ContentValues values) { assertTable(); LOGV(TAG, "update() " + this); return db.update(mTable, values, getSelection(), getSelectionArgs()); } /** * Execute delete using the current internal state as {@code WHERE} clause. */ public int delete(SQLiteDatabase db) { assertTable(); LOGV(TAG, "delete() " + this); return db.delete(mTable, getSelection(), getSelectionArgs()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Array; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** ****************************************************************************** * Taken from the JB source code, can be found in: * libcore/luni/src/main/java/libcore/io/DiskLruCache.java * or direct link: * https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java ****************************************************************************** * * A cache that uses a bounded amount of space on a filesystem. Each cache * entry has a string key and a fixed number of values. Values are byte * sequences, accessible as streams or files. Each value must be between {@code * 0} and {@code Integer.MAX_VALUE} bytes in length. * * <p>The cache stores its data in a directory on the filesystem. This * directory must be exclusive to the cache; the cache may delete or overwrite * files from its directory. It is an error for multiple processes to use the * same cache directory at the same time. * * <p>This cache limits the number of bytes that it will store on the * filesystem. When the number of stored bytes exceeds the limit, the cache will * remove entries in the background until the limit is satisfied. The limit is * not strict: the cache may temporarily exceed it while waiting for files to be * deleted. The limit does not include filesystem overhead or the cache * journal so space-sensitive applications should set a conservative limit. * * <p>Clients call {@link #edit} to create or update the values of an entry. An * entry may have only one editor at one time; if a value is not available to be * edited then {@link #edit} will return null. * <ul> * <li>When an entry is being <strong>created</strong> it is necessary to * supply a full set of values; the empty value should be used as a * placeholder if necessary. * <li>When an entry is being <strong>edited</strong>, it is not necessary * to supply data for every value; values default to their previous * value. * </ul> * Every {@link #edit} call must be matched by a call to {@link Editor#commit} * or {@link Editor#abort}. Committing is atomic: a read observes the full set * of values as they were before or after the commit, but never a mix of values. * * <p>Clients call {@link #get} to read a snapshot of an entry. The read will * observe the value at the time that {@link #get} was called. Updates and * removals after the call do not impact ongoing reads. * * <p>This class is tolerant of some I/O errors. If files are missing from the * filesystem, the corresponding entries will be dropped from the cache. If * an error occurs while writing a cache value, the edit will fail silently. * Callers should handle other problems by catching {@code IOException} and * responding appropriately. */ public final class DiskLruCache implements Closeable { static final String JOURNAL_FILE = "journal"; static final String JOURNAL_FILE_TMP = "journal.tmp"; static final String MAGIC = "libcore.io.DiskLruCache"; static final String VERSION_1 = "1"; static final long ANY_SEQUENCE_NUMBER = -1; private static final String CLEAN = "CLEAN"; private static final String DIRTY = "DIRTY"; private static final String REMOVE = "REMOVE"; private static final String READ = "READ"; private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final int IO_BUFFER_SIZE = 8 * 1024; /* * This cache uses a journal file named "journal". A typical journal file * looks like this: * libcore.io.DiskLruCache * 1 * 100 * 2 * * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 * DIRTY 335c4c6028171cfddfbaae1a9c313c52 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 * REMOVE 335c4c6028171cfddfbaae1a9c313c52 * DIRTY 1ab96a171faeeee38496d8b330771a7a * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 * READ 335c4c6028171cfddfbaae1a9c313c52 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 * * The first five lines of the journal form its header. They are the * constant string "libcore.io.DiskLruCache", the disk cache's version, * the application's version, the value count, and a blank line. * * Each of the subsequent lines in the file is a record of the state of a * cache entry. Each line contains space-separated values: a state, a key, * and optional state-specific values. * o DIRTY lines track that an entry is actively being created or updated. * Every successful DIRTY action should be followed by a CLEAN or REMOVE * action. DIRTY lines without a matching CLEAN or REMOVE indicate that * temporary files may need to be deleted. * o CLEAN lines track a cache entry that has been successfully published * and may be read. A publish line is followed by the lengths of each of * its values. * o READ lines track accesses for LRU. * o REMOVE lines track entries that have been deleted. * * The journal file is appended to as cache operations occur. The journal may * occasionally be compacted by dropping redundant lines. A temporary file named * "journal.tmp" will be used during compaction; that file should be deleted if * it exists when the cache is opened. */ private final File directory; private final File journalFile; private final File journalFileTmp; private final int appVersion; private final long maxSize; private final int valueCount; private long size = 0; private Writer journalWriter; private final LinkedHashMap<String, Entry> lruEntries = new LinkedHashMap<String, Entry>(0, 0.75f, true); private int redundantOpCount; /** * To differentiate between old and current snapshots, each entry is given * a sequence number each time an edit is committed. A snapshot is stale if * its sequence number is not equal to its entry's sequence number. */ private long nextSequenceNumber = 0; /* From java.util.Arrays */ @SuppressWarnings("unchecked") private static <T> T[] copyOfRange(T[] original, int start, int end) { final int originalLength = original.length; // For exception priority compatibility. if (start > end) { throw new IllegalArgumentException(); } if (start < 0 || start > originalLength) { throw new ArrayIndexOutOfBoundsException(); } final int resultLength = end - start; final int copyLength = Math.min(resultLength, originalLength - start); final T[] result = (T[]) Array .newInstance(original.getClass().getComponentType(), resultLength); System.arraycopy(original, start, result, 0, copyLength); return result; } /** * Returns the remainder of 'reader' as a string, closing it when done. */ public static String readFully(Reader reader) throws IOException { try { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; int count; while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } return writer.toString(); } finally { reader.close(); } } /** * Returns the ASCII characters up to but not including the next "\r\n", or * "\n". * * @throws java.io.EOFException if the stream is exhausted before the next newline * character. */ public static String readAsciiLine(InputStream in) throws IOException { // TODO: support UTF-8 here instead StringBuilder result = new StringBuilder(80); while (true) { int c = in.read(); if (c == -1) { throw new EOFException(); } else if (c == '\n') { break; } result.append((char) c); } int length = result.length(); if (length > 0 && result.charAt(length - 1) == '\r') { result.setLength(length - 1); } return result.toString(); } /** * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null. */ public static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } /** * Recursively delete everything in {@code dir}. */ // TODO: this should specify paths as Strings rather than as Files public static void deleteContents(File dir) throws IOException { File[] files = dir.listFiles(); if (files == null) { throw new IllegalArgumentException("not a directory: " + dir); } for (File file : files) { if (file.isDirectory()) { deleteContents(file); } if (!file.delete()) { throw new IOException("failed to delete file: " + file); } } } /** This cache uses a single background thread to evict entries. */ private final ExecutorService executorService = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); private final Callable<Void> cleanupCallable = new Callable<Void>() { @Override public Void call() throws Exception { synchronized (DiskLruCache.this) { if (journalWriter == null) { return null; // closed } trimToSize(); if (journalRebuildRequired()) { rebuildJournal(); redundantOpCount = 0; } } return null; } }; private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) { this.directory = directory; this.appVersion = appVersion; this.journalFile = new File(directory, JOURNAL_FILE); this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP); this.valueCount = valueCount; this.maxSize = maxSize; } /** * Opens the cache in {@code directory}, creating a cache if none exists * there. * * @param directory a writable directory * @param appVersion * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store * @throws IOException if reading or writing the cache directory fails */ public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize) throws IOException { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } if (valueCount <= 0) { throw new IllegalArgumentException("valueCount <= 0"); } // prefer to pick up where we left off DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); if (cache.journalFile.exists()) { try { cache.readJournal(); cache.processJournal(); cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true), IO_BUFFER_SIZE); return cache; } catch (IOException journalIsCorrupt) { // System.logW("DiskLruCache " + directory + " is corrupt: " // + journalIsCorrupt.getMessage() + ", removing"); cache.delete(); } } // create a new empty cache directory.mkdirs(); cache = new DiskLruCache(directory, appVersion, valueCount, maxSize); cache.rebuildJournal(); return cache; } private void readJournal() throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE); try { String magic = readAsciiLine(in); String version = readAsciiLine(in); String appVersionString = readAsciiLine(in); String valueCountString = readAsciiLine(in); String blank = readAsciiLine(in); if (!MAGIC.equals(magic) || !VERSION_1.equals(version) || !Integer.toString(appVersion).equals(appVersionString) || !Integer.toString(valueCount).equals(valueCountString) || !"".equals(blank)) { throw new IOException("unexpected journal header: [" + magic + ", " + version + ", " + valueCountString + ", " + blank + "]"); } while (true) { try { readJournalLine(readAsciiLine(in)); } catch (EOFException endOfJournal) { break; } } } finally { closeQuietly(in); } } private void readJournalLine(String line) throws IOException { String[] parts = line.split(" "); if (parts.length < 2) { throw new IOException("unexpected journal line: " + line); } String key = parts[1]; if (parts[0].equals(REMOVE) && parts.length == 2) { lruEntries.remove(key); return; } Entry entry = lruEntries.get(key); if (entry == null) { entry = new Entry(key); lruEntries.put(key, entry); } if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) { entry.readable = true; entry.currentEditor = null; entry.setLengths(copyOfRange(parts, 2, parts.length)); } else if (parts[0].equals(DIRTY) && parts.length == 2) { entry.currentEditor = new Editor(entry); } else if (parts[0].equals(READ) && parts.length == 2) { // this work was already done by calling lruEntries.get() } else { throw new IOException("unexpected journal line: " + line); } } /** * Computes the initial size and collects garbage as a part of opening the * cache. Dirty entries are assumed to be inconsistent and will be deleted. */ private void processJournal() throws IOException { deleteIfExists(journalFileTmp); for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) { Entry entry = i.next(); if (entry.currentEditor == null) { for (int t = 0; t < valueCount; t++) { size += entry.lengths[t]; } } else { entry.currentEditor = null; for (int t = 0; t < valueCount; t++) { deleteIfExists(entry.getCleanFile(t)); deleteIfExists(entry.getDirtyFile(t)); } i.remove(); } } } /** * Creates a new journal that omits redundant information. This replaces the * current journal if it exists. */ private synchronized void rebuildJournal() throws IOException { if (journalWriter != null) { journalWriter.close(); } Writer writer = new BufferedWriter(new FileWriter(journalFileTmp), IO_BUFFER_SIZE); writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); writer.write("\n"); writer.write(Integer.toString(appVersion)); writer.write("\n"); writer.write(Integer.toString(valueCount)); writer.write("\n"); writer.write("\n"); for (Entry entry : lruEntries.values()) { if (entry.currentEditor != null) { writer.write(DIRTY + ' ' + entry.key + '\n'); } else { writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); } } writer.close(); journalFileTmp.renameTo(journalFile); journalWriter = new BufferedWriter(new FileWriter(journalFile, true), IO_BUFFER_SIZE); } private static void deleteIfExists(File file) throws IOException { // try { // Libcore.os.remove(file.getPath()); // } catch (ErrnoException errnoException) { // if (errnoException.errno != OsConstants.ENOENT) { // throw errnoException.rethrowAsIOException(); // } // } if (file.exists() && !file.delete()) { throw new IOException(); } } /** * Returns a snapshot of the entry named {@code key}, or null if it doesn't * exist is not currently readable. If a value is returned, it is moved to * the head of the LRU queue. */ public synchronized Snapshot get(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null) { return null; } if (!entry.readable) { return null; } /* * Open all streams eagerly to guarantee that we see a single published * snapshot. If we opened streams lazily then the streams could come * from different edits. */ InputStream[] ins = new InputStream[valueCount]; try { for (int i = 0; i < valueCount; i++) { ins[i] = new FileInputStream(entry.getCleanFile(i)); } } catch (FileNotFoundException e) { // a file must have been deleted manually! return null; } redundantOpCount++; journalWriter.append(READ + ' ' + key + '\n'); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return new Snapshot(key, entry.sequenceNumber, ins); } /** * Returns an editor for the entry named {@code key}, or null if another * edit is in progress. */ public Editor edit(String key) throws IOException { return edit(key, ANY_SEQUENCE_NUMBER); } private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null || entry.sequenceNumber != expectedSequenceNumber)) { return null; // snapshot is stale } if (entry == null) { entry = new Entry(key); lruEntries.put(key, entry); } else if (entry.currentEditor != null) { return null; // another edit is in progress } Editor editor = new Editor(entry); entry.currentEditor = editor; // flush the journal before creating files to prevent file leaks journalWriter.write(DIRTY + ' ' + key + '\n'); journalWriter.flush(); return editor; } /** * Returns the directory where this cache stores its data. */ public File getDirectory() { return directory; } /** * Returns the maximum number of bytes that this cache should use to store * its data. */ public long maxSize() { return maxSize; } /** * Returns the number of bytes currently being used to store the values in * this cache. This may be greater than the max size if a background * deletion is pending. */ public synchronized long size() { return size; } private synchronized void completeEdit(Editor editor, boolean success) throws IOException { Entry entry = editor.entry; if (entry.currentEditor != editor) { throw new IllegalStateException(); } // if this edit is creating the entry for the first time, every index must have a value if (success && !entry.readable) { for (int i = 0; i < valueCount; i++) { if (!entry.getDirtyFile(i).exists()) { editor.abort(); throw new IllegalStateException("edit didn't create file " + i); } } } for (int i = 0; i < valueCount; i++) { File dirty = entry.getDirtyFile(i); if (success) { if (dirty.exists()) { File clean = entry.getCleanFile(i); dirty.renameTo(clean); long oldLength = entry.lengths[i]; long newLength = clean.length(); entry.lengths[i] = newLength; size = size - oldLength + newLength; } } else { deleteIfExists(dirty); } } redundantOpCount++; entry.currentEditor = null; if (entry.readable | success) { entry.readable = true; journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); if (success) { entry.sequenceNumber = nextSequenceNumber++; } } else { lruEntries.remove(entry.key); journalWriter.write(REMOVE + ' ' + entry.key + '\n'); } if (size > maxSize || journalRebuildRequired()) { executorService.submit(cleanupCallable); } } /** * We only rebuild the journal when it will halve the size of the journal * and eliminate at least 2000 ops. */ private boolean journalRebuildRequired() { final int REDUNDANT_OP_COMPACT_THRESHOLD = 2000; return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD && redundantOpCount >= lruEntries.size(); } /** * Drops the entry for {@code key} if it exists and can be removed. Entries * actively being edited cannot be removed. * * @return true if an entry was removed. */ public synchronized boolean remove(String key) throws IOException { checkNotClosed(); validateKey(key); Entry entry = lruEntries.get(key); if (entry == null || entry.currentEditor != null) { return false; } for (int i = 0; i < valueCount; i++) { File file = entry.getCleanFile(i); if (!file.delete()) { throw new IOException("failed to delete " + file); } size -= entry.lengths[i]; entry.lengths[i] = 0; } redundantOpCount++; journalWriter.append(REMOVE + ' ' + key + '\n'); lruEntries.remove(key); if (journalRebuildRequired()) { executorService.submit(cleanupCallable); } return true; } /** * Returns true if this cache has been closed. */ public boolean isClosed() { return journalWriter == null; } private void checkNotClosed() { if (journalWriter == null) { throw new IllegalStateException("cache is closed"); } } /** * Force buffered operations to the filesystem. */ public synchronized void flush() throws IOException { checkNotClosed(); trimToSize(); journalWriter.flush(); } /** * Closes this cache. Stored values will remain on the filesystem. */ public synchronized void close() throws IOException { if (journalWriter == null) { return; // already closed } for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } } trimToSize(); journalWriter.close(); journalWriter = null; } private void trimToSize() throws IOException { while (size > maxSize) { // Map.Entry<String, Entry> toEvict = lruEntries.eldest(); final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next(); remove(toEvict.getKey()); } } /** * Closes the cache and deletes all of its stored values. This will delete * all files in the cache directory including files that weren't created by * the cache. */ public void delete() throws IOException { close(); deleteContents(directory); } private void validateKey(String key) { if (key.contains(" ") || key.contains("\n") || key.contains("\r")) { throw new IllegalArgumentException( "keys must not contain spaces or newlines: \"" + key + "\""); } } private static String inputStreamToString(InputStream in) throws IOException { return readFully(new InputStreamReader(in, UTF_8)); } /** * A snapshot of the values for an entry. */ public final class Snapshot implements Closeable { private final String key; private final long sequenceNumber; private final InputStream[] ins; private Snapshot(String key, long sequenceNumber, InputStream[] ins) { this.key = key; this.sequenceNumber = sequenceNumber; this.ins = ins; } /** * Returns an editor for this snapshot's entry, or null if either the * entry has changed since this snapshot was created or if another edit * is in progress. */ public Editor edit() throws IOException { return DiskLruCache.this.edit(key, sequenceNumber); } /** * Returns the unbuffered stream with the value for {@code index}. */ public InputStream getInputStream(int index) { return ins[index]; } /** * Returns the string value for {@code index}. */ public String getString(int index) throws IOException { return inputStreamToString(getInputStream(index)); } @Override public void close() { for (InputStream in : ins) { closeQuietly(in); } } } /** * Edits the values for an entry. */ public final class Editor { private final Entry entry; private boolean hasErrors; private Editor(Entry entry) { this.entry = entry; } /** * Returns an unbuffered input stream to read the last committed value, * or null if no value has been committed. */ public InputStream newInputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { return null; } return new FileInputStream(entry.getCleanFile(index)); } } /** * Returns the last committed value as a string, or null if no value * has been committed. */ public String getString(int index) throws IOException { InputStream in = newInputStream(index); return in != null ? inputStreamToString(in) : null; } /** * Returns a new unbuffered output stream to write the value at * {@code index}. If the underlying output stream encounters errors * when writing to the filesystem, this edit will be aborted when * {@link #commit} is called. The returned output stream does not throw * IOExceptions. */ public OutputStream newOutputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index))); } } /** * Sets the value at {@code index} to {@code value}. */ public void set(int index, String value) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(newOutputStream(index), UTF_8); writer.write(value); } finally { closeQuietly(writer); } } /** * Commits this edit so it is visible to readers. This releases the * edit lock so another edit may be started on the same key. */ public void commit() throws IOException { if (hasErrors) { completeEdit(this, false); remove(entry.key); // the previous entry is stale } else { completeEdit(this, true); } } /** * Aborts this edit. This releases the edit lock so another edit may be * started on the same key. */ public void abort() throws IOException { completeEdit(this, false); } private class FaultHidingOutputStream extends FilterOutputStream { private FaultHidingOutputStream(OutputStream out) { super(out); } @Override public void write(int oneByte) { try { out.write(oneByte); } catch (IOException e) { hasErrors = true; } } @Override public void write(byte[] buffer, int offset, int length) { try { out.write(buffer, offset, length); } catch (IOException e) { hasErrors = true; } } @Override public void close() { try { out.close(); } catch (IOException e) { hasErrors = true; } } @Override public void flush() { try { out.flush(); } catch (IOException e) { hasErrors = true; } } } } private final class Entry { private final String key; /** Lengths of this entry's files. */ private final long[] lengths; /** True if this entry has ever been published */ private boolean readable; /** The ongoing edit or null if this entry is not being edited. */ private Editor currentEditor; /** The sequence number of the most recently committed edit to this entry. */ private long sequenceNumber; private Entry(String key) { this.key = key; this.lengths = new long[valueCount]; } public String getLengths() throws IOException { StringBuilder result = new StringBuilder(); for (long size : lengths) { result.append(' ').append(size); } return result.toString(); } /** * Set lengths using decimal numbers like "10123". */ private void setLengths(String[] strings) throws IOException { if (strings.length != valueCount) { throw invalidLengths(strings); } try { for (int i = 0; i < strings.length; i++) { lengths[i] = Long.parseLong(strings[i]); } } catch (NumberFormatException e) { throw invalidLengths(strings); } } private IOException invalidLengths(String[] strings) throws IOException { throw new IOException("unexpected journal line: " + Arrays.toString(strings)); } public File getCleanFile(int i) { return new File(directory, key + "." + i); } public File getDirtyFile(int i) { return new File(directory, key + "." + i + ".tmp"); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.BuildConfig; import android.util.Log; /** * Helper methods that make logging more consistent throughout the app. */ public class LogUtils { private static final String LOG_PREFIX = "iosched_"; private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); private static final int MAX_LOG_TAG_LENGTH = 23; public static String makeLogTag(String str) { if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); } return LOG_PREFIX + str; } /** * WARNING: Don't use this when obfuscating class names with Proguard! */ public static String makeLogTag(Class cls) { return makeLogTag(cls.getSimpleName()); } public static void LOGD(final String tag, String message) { if (Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, message); } } public static void LOGD(final String tag, String message, Throwable cause) { if (Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, message, cause); } } public static void LOGV(final String tag, String message) { //noinspection PointlessBooleanExpression,ConstantConditions if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) { Log.v(tag, message); } } public static void LOGV(final String tag, String message, Throwable cause) { //noinspection PointlessBooleanExpression,ConstantConditions if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) { Log.v(tag, message, cause); } } public static void LOGI(final String tag, String message) { Log.i(tag, message); } public static void LOGI(final String tag, String message, Throwable cause) { Log.i(tag, message, cause); } public static void LOGW(final String tag, String message) { Log.w(tag, message); } public static void LOGW(final String tag, String message, Throwable cause) { Log.w(tag, message, cause); } public static void LOGE(final String tag, String message) { Log.e(tag, message); } public static void LOGE(final String tag, String message, Throwable cause) { Log.e(tag, message, cause); } private LogUtils() { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.HashMap; /** * Provides static methods for creating mutable {@code Maps} instances easily. */ public class Maps { /** * Creates a {@code HashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.ui.phone.MapActivity; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import com.google.android.apps.iosched.ui.phone.TrackDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity; import android.annotation.TargetApi; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.Calendar; import java.util.Formatter; import java.util.Locale; import java.util.TimeZone; /** * An assortment of UI helpers. */ public class UIUtils { /** * Time zone to use when formatting all session times. To always use the * phone local time, use {@link TimeZone#getDefault()}. */ public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles"); public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime( "2012-06-27T09:30:00.000-07:00"); public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime( "2012-06-29T18:00:00.000-07:00"); public static final String CONFERENCE_HASHTAG = "#io12"; private static final int SECOND_MILLIS = 1000; private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DAY_MILLIS = 24 * HOUR_MILLIS; /** Flags used with {@link DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; /** {@link StringBuilder} used for formatting time block. */ private static StringBuilder sBuilder = new StringBuilder(50); /** {@link Formatter} used for formatting time block. */ private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault()); private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); private static CharSequence sEmptyRoomText; private static CharSequence sCodeLabRoomText; private static CharSequence sNowPlayingText; private static CharSequence sLivestreamNowText; private static CharSequence sLivestreamAvailableText; public static final String GOOGLE_PLUS_PACKAGE_NAME = "com.google.android.apps.plus"; /** * Format and return the given {@link Blocks} and {@link Rooms} values using * {@link #CONFERENCE_TIME_ZONE}. */ public static String formatSessionSubtitle(String sessionTitle, long blockStart, long blockEnd, String roomName, Context context) { if (sEmptyRoomText == null || sCodeLabRoomText == null) { sEmptyRoomText = context.getText(R.string.unknown_room); sCodeLabRoomText = context.getText(R.string.codelab_room); } if (roomName == null) { // TODO: remove the WAR for API not returning rooms for code labs return context.getString(R.string.session_subtitle, formatBlockTimeString(blockStart, blockEnd, context), sessionTitle.contains("Code Lab") ? sCodeLabRoomText : sEmptyRoomText); } return context.getString(R.string.session_subtitle, formatBlockTimeString(blockStart, blockEnd, context), roomName); } /** * Format and return the given {@link Blocks} values using * {@link #CONFERENCE_TIME_ZONE}. */ public static String formatBlockTimeString(long blockStart, long blockEnd, Context context) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); // NOTE: There is an efficient version of formatDateRange in Eclair and // beyond that allows you to recycle a StringBuilder. return DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS); } public static boolean isSameDay(long time1, long time2) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTimeInMillis(time1); cal2.setTimeInMillis(time2); return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); } public static String getTimeAgo(long time, Context ctx) { if (time < 1000000000000L) { // if timestamp given in seconds, convert to millis time *= 1000; } long now = getCurrentTime(ctx); if (time > now || time <= 0) { return null; } // TODO: localize final long diff = now - time; if (diff < MINUTE_MILLIS) { return "just now"; } else if (diff < 2 * MINUTE_MILLIS) { return "a minute ago"; } else if (diff < 50 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + " minutes ago"; } else if (diff < 90 * MINUTE_MILLIS) { return "an hour ago"; } else if (diff < 24 * HOUR_MILLIS) { return diff / HOUR_MILLIS + " hours ago"; } else if (diff < 48 * HOUR_MILLIS) { return "yesterday"; } else { return diff / DAY_MILLIS + " days ago"; } } /** * Populate the given {@link TextView} with the requested text, formatting * through {@link Html#fromHtml(String)} when applicable. Also sets * {@link TextView#setMovementMethod} so inline links are handled. */ public static void setTextMaybeHtml(TextView view, String text) { if (TextUtils.isEmpty(text)) { view.setText(""); return; } if (text.contains("<") && text.contains(">")) { view.setText(Html.fromHtml(text)); view.setMovementMethod(LinkMovementMethod.getInstance()); } else { view.setText(text); } } public static void updateTimeAndLivestreamBlockUI(final Context context, long blockStart, long blockEnd, boolean hasLivestream, View backgroundView, TextView titleView, TextView subtitleView, CharSequence subtitle) { long currentTimeMillis = getCurrentTime(context); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS); boolean present = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd); final Resources res = context.getResources(); if (backgroundView != null) { backgroundView.setBackgroundColor(past ? res.getColor(R.color.past_background_color) : 0); } if (titleView != null) { titleView.setTypeface(Typeface.SANS_SERIF, past ? Typeface.NORMAL : Typeface.BOLD); } if (subtitleView != null) { boolean empty = true; SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle if (subtitle != null) { sb.append(subtitle); empty = false; } if (present) { if (sNowPlayingText == null) { sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge)); } if (!empty) { sb.append(" "); } sb.append(sNowPlayingText); if (hasLivestream) { if (sLivestreamNowText == null) { sLivestreamNowText = Html.fromHtml("&nbsp;&nbsp;" + context.getString(R.string.live_now_badge)); } sb.append(sLivestreamNowText); } } else if (hasLivestream) { if (sLivestreamAvailableText == null) { sLivestreamAvailableText = Html.fromHtml( context.getString(R.string.live_available_badge)); } if (!empty) { sb.append(" "); } sb.append(sLivestreamAvailableText); } subtitleView.setText(sb); } } /** * Given a snippet string with matching segments surrounded by curly * braces, turn those areas into bold spans, removing the curly braces. */ public static Spannable buildStyledSnippet(String snippet) { final SpannableStringBuilder builder = new SpannableStringBuilder(snippet); // Walk through string, inserting bold snippet spans int startIndex = -1, endIndex = -1, delta = 0; while ((startIndex = snippet.indexOf('{', endIndex)) != -1) { endIndex = snippet.indexOf('}', startIndex); // Remove braces from both sides builder.delete(startIndex - delta, startIndex - delta + 1); builder.delete(endIndex - delta - 1, endIndex - delta); // Insert bold style builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); delta += 2; } return builder; } public static void preferPackageForIntent(Context context, Intent intent, String packageName) { PackageManager pm = context.getPackageManager(); for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) { if (resolveInfo.activityInfo.packageName.equals(packageName)) { intent.setPackage(packageName); break; } } } public static ImageFetcher getImageFetcher(final FragmentActivity activity) { // The ImageFetcher takes care of loading remote images into our ImageView ImageFetcher fetcher = new ImageFetcher(activity); fetcher.addImageCache(activity); return fetcher; } public static String getSessionHashtagsString(String hashtags) { if (!TextUtils.isEmpty(hashtags)) { if (!hashtags.startsWith("#")) { hashtags = "#" + hashtags; } if (hashtags.contains(CONFERENCE_HASHTAG)) { return hashtags; } return CONFERENCE_HASHTAG + " " + hashtags; } else { return CONFERENCE_HASHTAG; } } private static final int BRIGHTNESS_THRESHOLD = 130; /** * Calculate whether a color is light or dark, based on a commonly known * brightness formula. * * @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness} */ public static boolean isColorDark(int color) { return ((30 * Color.red(color) + 59 * Color.green(color) + 11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD; } // Shows whether a notification was fired for a particular session time block. In the // event that notification has not been fired yet, return false and set the bit. public static boolean isNotificationFiredForBlock(Context context, String blockId) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); final String key = String.format("notification_fired_%s", blockId); boolean fired = sp.getBoolean(key, false); sp.edit().putBoolean(key, true).commit(); return fired; } private static final long sAppLoadTime = System.currentTimeMillis(); public static long getCurrentTime(final Context context) { if (BuildConfig.DEBUG) { return context.getSharedPreferences("mock_data", Context.MODE_PRIVATE) .getLong("mock_current_time", System.currentTimeMillis()) + System.currentTimeMillis() - sAppLoadTime; } else { return System.currentTimeMillis(); } } public static void safeOpenLink(Context context, Intent linkIntent) { try { context.startActivity(linkIntent); } catch (ActivityNotFoundException e) { Toast.makeText(context, "Couldn't open link", Toast.LENGTH_SHORT) .show(); } } // TODO: use <meta-data> element instead private static final Class[] sPhoneActivities = new Class[]{ MapActivity.class, SessionDetailActivity.class, SessionsActivity.class, TrackDetailActivity.class, VendorDetailActivity.class, }; // TODO: use <meta-data> element instead private static final Class[] sTabletActivities = new Class[]{ MapMultiPaneActivity.class, SessionsVendorsMultiPaneActivity.class, }; public static void enableDisableActivities(final Context context) { boolean isHoneycombTablet = isHoneycombTablet(context); PackageManager pm = context.getPackageManager(); // Enable/disable phone activities for (Class a : sPhoneActivities) { pm.setComponentEnabledSetting(new ComponentName(context, a), isHoneycombTablet ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED : PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); } // Enable/disable tablet activities for (Class a : sTabletActivities) { pm.setComponentEnabledSetting(new ComponentName(context, a), isHoneycombTablet ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } public static Class getMapActivityClass(Context context) { if (UIUtils.isHoneycombTablet(context)) { return MapMultiPaneActivity.class; } return MapActivity.class; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void setActivatedCompat(View view, boolean activated) { if (hasHoneycomb()) { view.setActivated(activated); } } public static boolean isGoogleTV(Context context) { return context.getPackageManager().hasSystemFeature("com.google.android.tv"); } public static boolean hasFroyo() { // Can use static final constants like FROYO, declared in later versions // of the OS since they are inlined at compile time. This is guaranteed behavior. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; } public static boolean hasGingerbread() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; } public static boolean hasHoneycomb() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean hasHoneycombMR1() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; } public static boolean hasICS() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; } public static boolean hasJellyBean() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static boolean isHoneycombTablet(Context context) { return hasHoneycomb() && isTablet(context); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A subclass of {@link ImageWorker} that fetches images from a URL. */ public class ImageFetcher extends ImageWorker { private static final String TAG = makeLogTag(ImageFetcher.class); public static final int IO_BUFFER_SIZE_BYTES = 4 * 1024; // 4KB // Default fetcher params private static final int MAX_THUMBNAIL_BYTES = 70 * 1024; // 70KB private static final int HTTP_CACHE_SIZE = 5 * 1024 * 1024; // 5MB private static final String HTTP_CACHE_DIR = "http"; private static final int DEFAULT_IMAGE_HEIGHT = 1024; private static final int DEFAULT_IMAGE_WIDTH = 1024; protected int mImageWidth; protected int mImageHeight; private DiskLruCache mHttpDiskCache; private File mHttpCacheDir; private boolean mHttpDiskCacheStarting = true; private final Object mHttpDiskCacheLock = new Object(); private static final int DISK_CACHE_INDEX = 0; /** * Create an ImageFetcher specifying max image loading width/height. */ public ImageFetcher(Context context, int imageWidth, int imageHeight) { super(context); init(context, imageWidth, imageHeight); } /** * Create an ImageFetcher using defaults. */ public ImageFetcher(Context context) { super(context); init(context, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT); } private void init(Context context, int imageWidth, int imageHeight) { mImageWidth = imageWidth; mImageHeight = imageHeight; mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR); if (!mHttpCacheDir.exists()) { mHttpCacheDir.mkdirs(); } } public void loadThumbnailImage(String key, ImageView imageView, Bitmap loadingBitmap) { loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, loadingBitmap); } public void loadThumbnailImage(String key, ImageView imageView, int resId) { loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, resId); } public void loadThumbnailImage(String key, ImageView imageView) { loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, mLoadingBitmap); } public void loadImage(String key, ImageView imageView, Bitmap loadingBitmap) { loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, loadingBitmap); } public void loadImage(String key, ImageView imageView, int resId) { loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, resId); } public void loadImage(String key, ImageView imageView) { loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, mLoadingBitmap); } /** * Set the target image width and height. */ public void setImageSize(int width, int height) { mImageWidth = width; mImageHeight = height; } /** * Set the target image size (width and height will be the same). */ public void setImageSize(int size) { setImageSize(size, size); } /** * The main process method, which will be called by the ImageWorker in the AsyncTask background * thread. * * @param key The key to load the bitmap, in this case, a regular http URL * @return The downloaded and resized bitmap */ private Bitmap processBitmap(String key, int type) { LOGD(TAG, "processBitmap - " + key); if (type == ImageData.IMAGE_TYPE_NORMAL) { return processNormalBitmap(key); // Process a regular, full sized bitmap } else if (type == ImageData.IMAGE_TYPE_THUMBNAIL) { return processThumbnailBitmap(key); // Process a smaller, thumbnail bitmap } return null; } @Override protected Bitmap processBitmap(Object key) { final ImageData imageData = (ImageData) key; return processBitmap(imageData.mKey, imageData.mType); } /** * Download and resize a normal sized remote bitmap from a HTTP URL using a HTTP cache. * @param urlString The URL of the image to download * @return The scaled bitmap */ private Bitmap processNormalBitmap(String urlString) { final String key = ImageCache.hashKeyForDisk(urlString); FileDescriptor fileDescriptor = null; FileInputStream fileInputStream = null; DiskLruCache.Snapshot snapshot; synchronized (mHttpDiskCacheLock) { // Wait for disk cache to initialize while (mHttpDiskCacheStarting) { try { mHttpDiskCacheLock.wait(); } catch (InterruptedException e) {} } if (mHttpDiskCache != null) { try { snapshot = mHttpDiskCache.get(key); if (snapshot == null) { LOGD(TAG, "processBitmap, not found in http cache, downloading..."); DiskLruCache.Editor editor = mHttpDiskCache.edit(key); if (editor != null) { if (downloadUrlToStream(urlString, editor.newOutputStream(DISK_CACHE_INDEX))) { editor.commit(); } else { editor.abort(); } } snapshot = mHttpDiskCache.get(key); } if (snapshot != null) { fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX); fileDescriptor = fileInputStream.getFD(); } } catch (IOException e) { LOGE(TAG, "processBitmap - " + e); } catch (IllegalStateException e) { LOGE(TAG, "processBitmap - " + e); } finally { if (fileDescriptor == null && fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) {} } } } } Bitmap bitmap = null; if (fileDescriptor != null) { bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight); } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) {} } return bitmap; } /** * Download a thumbnail sized remote bitmap from a HTTP URL. No HTTP caching is done (the * {@link ImageCache} that this eventually gets passed to will do it's own disk caching. * @param urlString The URL of the image to download * @return The bitmap */ private Bitmap processThumbnailBitmap(String urlString) { final byte[] bitmapBytes = downloadBitmapToMemory(urlString, MAX_THUMBNAIL_BYTES); if (bitmapBytes != null) { // Caution: we don't check the size of the bitmap here, we are relying on the output // of downloadBitmapToMemory to not exceed our memory limits and load a huge bitmap // into memory. return BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length); } return null; } /** * Download a bitmap from a URL, write it to a disk and return the File pointer. This * implementation uses a simple disk cache. * * @param urlString The URL to fetch * @param maxBytes The maximum number of bytes to read before returning null to protect against * OutOfMemory exceptions. * @return A File pointing to the fetched bitmap */ public static byte[] downloadBitmapToMemory(String urlString, int maxBytes) { LOGD(TAG, "downloadBitmapToMemory - downloading - " + urlString); disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; ByteArrayOutputStream out = null; InputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES); out = new ByteArrayOutputStream(IO_BUFFER_SIZE_BYTES); final byte[] buffer = new byte[128]; int total = 0; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { total += bytesRead; if (total > maxBytes) { return null; } out.write(buffer, 0, bytesRead); } return out.toByteArray(); } catch (final IOException e) { LOGE(TAG, "Error in downloadBitmapToMemory - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (final IOException e) {} } return null; } /** * Download a bitmap from a URL and write the content to an output stream. * * @param urlString The URL to fetch * @param outputStream The outputStream to write to * @return true if successful, false otherwise */ public boolean downloadUrlToStream(String urlString, OutputStream outputStream) { disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES); out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE_BYTES); int b; while ((b = in.read()) != -1) { out.write(b); } return true; } catch (final IOException e) { LOGE(TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) {} } return false; } /** * Download a bitmap from a URL, write it to a disk and return the File pointer. This * implementation uses a simple disk cache. * * @param urlString The URL to fetch * @param cacheDir The directory to store the downloaded file * @return A File pointing to the fetched bitmap */ public static File downloadBitmapToFile(String urlString, File cacheDir) { LOGD(TAG, "downloadBitmap - downloading - " + urlString); disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final File tempFile = File.createTempFile("bitmap", null, cacheDir); final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES); out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES); int b; while ((b = in.read()) != -1) { out.write(b); } return tempFile; } catch (final IOException e) { LOGE(TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (final IOException e) {} } return null; } /** * Decode and sample down a bitmap from a file to the requested width and * height. * * @param filename The full path of the file to decode * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @return A bitmap sampled down from the original with the same aspect * ratio and dimensions that are equal to or greater than the * requested width and height */ public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filename, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filename, options); } /** * Decode and sample down a bitmap from a file input stream to the requested width and height. * * @param fileDescriptor The file descriptor to read from * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @return A bitmap sampled down from the original with the same aspect ratio and dimensions * that are equal to or greater than the requested width and height */ public static Bitmap decodeSampledBitmapFromDescriptor( FileDescriptor fileDescriptor, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); } /** * Calculate an inSampleSize for use in a * {@link android.graphics.BitmapFactory.Options} object when decoding * bitmaps using the decode* methods from {@link BitmapFactory}. This * implementation calculates the closest inSampleSize that will result in * the final decoded bitmap having a width and height equal to or larger * than the requested width and height. This implementation does not ensure * a power of 2 is returned for inSampleSize which can be faster when * decoding but results in a larger bitmap which isn't as useful for caching * purposes. * * @param options An options object with out* params already populated (run * through a decode* method with inJustDecodeBounds==true * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @return The value to be used for inSampleSize */ public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; // This offers some additional logic in case the image has a strange // aspect ratio. For example, a panorama may have a much larger // width than height. In these cases the total pixels might still // end up being too large to fit comfortably in memory, so we should // be more aggressive with sample down the image (=larger // inSampleSize). final float totalPixels = width * height; // Anything more than 2x the requested pixels we'll sample down // further. final float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { inSampleSize++; } } return inSampleSize; } /** * Workaround for bug pre-Froyo, see here for more info: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html */ public static void disableConnectionReuseIfNecessary() { // HTTP connection reuse which was buggy pre-froyo if (hasHttpConnectionBug()) { System.setProperty("http.keepAlive", "false"); } } /** * Check if OS version has a http URLConnection bug. See here for more * information: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html * * @return true if this OS version is affected, false otherwise */ public static boolean hasHttpConnectionBug() { return !UIUtils.hasFroyo(); } @Override protected void initDiskCacheInternal() { super.initDiskCacheInternal(); initHttpDiskCache(); } private void initHttpDiskCache() { if (!mHttpCacheDir.exists()) { mHttpCacheDir.mkdirs(); } synchronized (mHttpDiskCacheLock) { if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) { try { mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE); LOGD(TAG, "HTTP cache initialized"); } catch (IOException e) { mHttpDiskCache = null; } } mHttpDiskCacheStarting = false; mHttpDiskCacheLock.notifyAll(); } } @Override protected void clearCacheInternal() { super.clearCacheInternal(); synchronized (mHttpDiskCacheLock) { if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) { try { mHttpDiskCache.delete(); LOGD(TAG, "HTTP cache cleared"); } catch (IOException e) { LOGE(TAG, "clearCacheInternal - " + e); } mHttpDiskCache = null; mHttpDiskCacheStarting = true; initHttpDiskCache(); } } } @Override protected void flushCacheInternal() { super.flushCacheInternal(); synchronized (mHttpDiskCacheLock) { if (mHttpDiskCache != null) { try { mHttpDiskCache.flush(); LOGD(TAG, "HTTP cache flushed"); } catch (IOException e) { LOGE(TAG, "flush - " + e); } } } } @Override protected void closeCacheInternal() { super.closeCacheInternal(); synchronized (mHttpDiskCacheLock) { if (mHttpDiskCache != null) { try { if (!mHttpDiskCache.isClosed()) { mHttpDiskCache.close(); mHttpDiskCache = null; LOGD(TAG, "HTTP cache closed"); } } catch (IOException e) { LOGE(TAG, "closeCacheInternal - " + e); } } } } private static class ImageData { public static final int IMAGE_TYPE_THUMBNAIL = 0; public static final int IMAGE_TYPE_NORMAL = 1; public String mKey; public int mType; public ImageData(String key, int type) { mKey = key; mType = type; } @Override public String toString() { return mKey; } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.calendar.SessionCalendarService; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.AccountActivity; import com.google.android.gcm.GCMRegistrar; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.widget.Toast; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An assortment of authentication and login helper utilities. */ public class AccountUtils { private static final String TAG = makeLogTag(AccountUtils.class); private static final String PREF_CHOSEN_ACCOUNT = "chosen_account"; private static final String PREF_AUTH_TOKEN = "auth_token"; // The auth scope required for the app. In our case we use the "conference API" // (not currently open source) which requires the developerssite (and readonly variant) scope. private static final String AUTH_TOKEN_TYPE = "oauth2:" + "https://www.googleapis.com/auth/developerssite " + "https://www.googleapis.com/auth/developerssite.readonly "; public static boolean isAuthenticated(final Context context) { return !TextUtils.isEmpty(getChosenAccountName(context)); } public static String getChosenAccountName(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(PREF_CHOSEN_ACCOUNT, null); } private static void setChosenAccountName(final Context context, final String accountName) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_CHOSEN_ACCOUNT, accountName).commit(); } public static String getAuthToken(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString(PREF_AUTH_TOKEN, null); } private static void setAuthToken(final Context context, final String authToken) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString(PREF_AUTH_TOKEN, authToken).commit(); } public static void invalidateAuthToken(final Context context) { AccountManager am = AccountManager.get(context); am.invalidateAuthToken(GoogleAccountManager.ACCOUNT_TYPE, getAuthToken(context)); setAuthToken(context, null); } public static interface AuthenticateCallback { public boolean shouldCancelAuthentication(); public void onAuthTokenAvailable(String authToken); } public static void tryAuthenticate(Activity activity, AuthenticateCallback callback, int activityRequestCode, Account account) { //noinspection deprecation AccountManager.get(activity).getAuthToken( account, AUTH_TOKEN_TYPE, false, getAccountManagerCallback(callback, account, activity, activity, activityRequestCode), null); } public static void tryAuthenticateWithErrorNotification(Context context, AuthenticateCallback callback, Account account) { //noinspection deprecation AccountManager.get(context).getAuthToken( account, AUTH_TOKEN_TYPE, true, getAccountManagerCallback(callback, account, context, null, 0), null); } private static AccountManagerCallback<Bundle> getAccountManagerCallback( final AuthenticateCallback callback, final Account account, final Context context, final Activity activity, final int activityRequestCode) { return new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { if (callback != null && callback.shouldCancelAuthentication()) { return; } try { Bundle bundle = future.getResult(); if (activity != null && bundle.containsKey(AccountManager.KEY_INTENT)) { Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT); intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivityForResult(intent, activityRequestCode); } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) { final String token = bundle.getString(AccountManager.KEY_AUTHTOKEN); setAuthToken(context, token); setChosenAccountName(context, account.name); if (callback != null) { callback.onAuthTokenAvailable(token); } } } catch (Exception e) { LOGE(TAG, "Authentication error", e); } } }; } public static void signOut(final Context context) { // Clear out all Google I/O-created sessions from Calendar if (UIUtils.hasICS()) { LOGI(TAG, "Clearing all sessions from Google Calendar using SessionCalendarService."); Toast.makeText(context, R.string.toast_deleting_sessions_from_calendar, Toast.LENGTH_LONG).show(); context.startService( new Intent(SessionCalendarService.ACTION_CLEAR_ALL_SESSIONS_CALENDAR) .setClass(context, SessionCalendarService.class) .putExtra(SessionCalendarService.EXTRA_ACCOUNT_NAME, getChosenAccountName(context))); } invalidateAuthToken(context); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().clear().commit(); context.getContentResolver().delete(ScheduleContract.BASE_CONTENT_URI, null, null); GCMRegistrar.unregister(context); } public static void startAuthenticationFlow(final Context context, final Intent finishIntent) { Intent loginFlowIntent = new Intent(context, AccountActivity.class); loginFlowIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); loginFlowIntent.putExtra(AccountActivity.EXTRA_FINISH_INTENT, finishIntent); context.startActivity(loginFlowIntent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.provider.ScheduleContract; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Build; import android.os.Parcelable; import android.preference.PreferenceManager; /** * Android Beam helper methods. */ public class BeamUtils { private static final byte[] DEFAULT_BEAM_MIME = "application/vnd.google.iosched.default".getBytes(); private static final String PREF_BEAM_STATE = "beam_state"; private static final int BEAM_STATE_UNLOCKED = 0x1481; private static final int BEAM_STATE_LOCKED = 0x0; /** * Sets this activity's Android Beam message to one representing the given session. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void setBeamSessionUri(Activity activity, Uri sessionUri) { if (UIUtils.hasICS()) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter == null) { // No NFC :-( return; } nfcAdapter.setNdefPushMessage(new NdefMessage( new NdefRecord[]{ new NdefRecord(NdefRecord.TNF_MIME_MEDIA, ScheduleContract.Sessions.CONTENT_ITEM_TYPE.getBytes(), new byte[0], sessionUri.toString().getBytes()) }), activity); } } /** * Sets this activity's Android Beam message to the default. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void setDefaultBeamUri(Activity activity) { if (UIUtils.hasICS()) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter == null) { // No NFC :-( return; } nfcAdapter.setNdefPushMessage(new NdefMessage( new NdefRecord[]{ new NdefRecord(NdefRecord.TNF_MIME_MEDIA, DEFAULT_BEAM_MIME, new byte[0], new byte[0]) }), activity); } } public static boolean isBeamUnlocked(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return (prefs.getInt(PREF_BEAM_STATE, BEAM_STATE_LOCKED) == BEAM_STATE_UNLOCKED); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void setBeamUnlocked(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putInt(PREF_BEAM_STATE, BEAM_STATE_UNLOCKED).commit(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static boolean wasLaunchedThroughBeamFirstTime(Context context, Intent intent) { return intent != null && UIUtils.hasICS() && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) && !isBeamUnlocked(context); } /** * Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is * an NFC intent that the app recognizes. If it is, then parse the NFC message and set the * activity's intent (using {@link Activity#setIntent(android.content.Intent)}) to something * the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent). */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void tryUpdateIntentFromBeam(Activity activity) { if (UIUtils.hasICS()) { Intent originalIntent = activity.getIntent(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) { Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; // Record 0 contains the MIME type, record 1 is the AAR, if present. // In iosched, AARs are not present. NdefRecord mimeRecord = msg.getRecords()[0]; if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals( new String(mimeRecord.getType()))) { // Re-set the activity's intent to one that represents session details. Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(new String(mimeRecord.getPayload()))); activity.setIntent(sessionDetailIntent); } } } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void setBeamCompleteCallback(Activity activity, NfcAdapter.OnNdefPushCompleteCallback callback) { if (UIUtils.hasICS()) { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity); if (adapter == null) { return; } adapter.setOnNdefPushCompleteCallback(callback, activity); } } public static void launchBeamSession(Context context) { context.startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri("gooio2012/125/"))); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.BuildConfig; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.AsyncTask; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.widget.ImageView; import java.lang.ref.WeakReference; import java.util.Hashtable; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This class wraps up completing some arbitrary long running work when loading a bitmap to an * ImageView. It handles things like using a memory and disk cache, running the work in a background * thread and setting a placeholder image. */ public abstract class ImageWorker { private static final String TAG = makeLogTag(ImageWorker.class); private static final int FADE_IN_TIME = 200; protected ImageCache mImageCache; protected ImageCache.ImageCacheParams mImageCacheParams; protected Bitmap mLoadingBitmap; protected boolean mFadeInBitmap = true; private boolean mExitTasksEarly = false; protected boolean mPauseWork = false; private final Object mPauseWorkLock = new Object(); private final Hashtable<Integer, Bitmap> loadingBitmaps = new Hashtable<Integer, Bitmap>(2); protected Resources mResources; private static final int MESSAGE_CLEAR = 0; private static final int MESSAGE_INIT_DISK_CACHE = 1; private static final int MESSAGE_FLUSH = 2; private static final int MESSAGE_CLOSE = 3; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; // Dual thread executor for main AsyncTask public static final Executor DUAL_THREAD_EXECUTOR = Executors.newFixedThreadPool(2, sThreadFactory); protected ImageWorker(Context context) { mResources = context.getResources(); } /** * Load an image specified by the data parameter into an ImageView (override * {@link ImageWorker#processBitmap(Object)} to define the processing * logic). A memory and disk cache will be used if an {@link ImageCache} has * been set using {@link ImageWorker#addImageCache}. If the * image is found in the memory cache, it is set immediately, otherwise an * {@link AsyncTask} will be created to asynchronously load the bitmap. * * @param data The URL of the image to download. * @param imageView The ImageView to bind the downloaded image to. */ protected void loadImage(Object data, ImageView imageView) { loadImage(data, imageView, mLoadingBitmap); } /** * Load an image specified by the data parameter into an ImageView (override * {@link ImageWorker#processBitmap(Object)} to define the processing * logic). A memory and disk cache will be used if an {@link ImageCache} has * been set using {@link ImageWorker#addImageCache}. If the * image is found in the memory cache, it is set immediately, otherwise an * {@link AsyncTask} will be created to asynchronously load the bitmap. * * @param data The URL of the image to download. * @param imageView The ImageView to bind the downloaded image to. * @param resId Resource of placeholder bitmap while the image loads. */ protected void loadImage(Object data, ImageView imageView, int resId) { if (!loadingBitmaps.containsKey(resId)) { // Store loading bitmap in a hash table to prevent continual decoding loadingBitmaps.put(resId, BitmapFactory.decodeResource(mResources, resId)); } loadImage(data, imageView, loadingBitmaps.get(resId)); } /** * Load an image specified by the data parameter into an ImageView (override * {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and disk * cache will be used if an {@link ImageCache} has been set using * {@link ImageWorker#addImageCache}. If the image is found in the memory cache, it * is set immediately, otherwise an {@link AsyncTask} will be created to asynchronously load the * bitmap. * * @param data The URL of the image to download. * @param imageView The ImageView to bind the downloaded image to. */ public void loadImage(Object data, ImageView imageView, Bitmap loadingBitmap) { if (data == null) { return; } Bitmap bitmap = null; if (mImageCache != null) { bitmap = mImageCache.getBitmapFromMemCache(String.valueOf(data)); } if (bitmap != null) { // Bitmap found in memory cache imageView.setImageBitmap(bitmap); } else if (cancelPotentialWork(data, imageView)) { final BitmapWorkerTask task = new BitmapWorkerTask(imageView); final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, loadingBitmap, task); imageView.setImageDrawable(asyncDrawable); if (UIUtils.hasHoneycomb()) { // On HC+ we execute on a dual thread executor. There really isn't much extra // benefit to having a really large pool of threads. Having more than one will // likely benefit network bottlenecks though. task.executeOnExecutor(DUAL_THREAD_EXECUTOR, data); } else { // Otherwise pre-HC the default is a thread pool executor (not ideal, serial // execution or a smaller number of threads would be better). task.execute(data); } } } /** * Set placeholder bitmap that shows when the the background thread is running. * * @param bitmap */ public void setLoadingImage(Bitmap bitmap) { mLoadingBitmap = bitmap; } /** * Set placeholder bitmap that shows when the the background thread is running. * * @param resId */ public void setLoadingImage(int resId) { mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId); } /** * Adds an {@link ImageCache} to this worker in the background (to prevent disk access on UI * thread). * @param fragmentManager The FragmentManager to initialize and add the cache * @param cacheParams The cache parameters to use */ public void addImageCache(FragmentManager fragmentManager, ImageCache.ImageCacheParams cacheParams) { mImageCacheParams = cacheParams; setImageCache(ImageCache.findOrCreateCache(fragmentManager, mImageCacheParams)); new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE); } /** * Adds an {@link ImageCache} to this worker in the background (to prevent disk access on UI * thread) using default cache parameters. * @param fragmentActivity The FragmentActivity to initialize and add the cache */ public void addImageCache(FragmentActivity fragmentActivity) { addImageCache(fragmentActivity.getSupportFragmentManager(), new ImageCache.ImageCacheParams(fragmentActivity)); } /** * Sets the {@link ImageCache} object to use with this ImageWorker. Usually you will not need * to call this directly, instead use {@link ImageWorker#addImageCache} which will create and * add the {@link ImageCache} object in a background thread (to ensure no disk access on the * main/UI thread). * * @param imageCache */ public void setImageCache(ImageCache imageCache) { mImageCache = imageCache; } /** * If set to true, the image will fade-in once it has been loaded by the background thread. */ public void setImageFadeIn(boolean fadeIn) { mFadeInBitmap = fadeIn; } /** * Setting this to true will signal the working tasks to exit processing at the next chance. * This helps finish up pending work when the activity is no longer in the foreground and * completing the tasks is no longer useful. * @param exitTasksEarly */ public void setExitTasksEarly(boolean exitTasksEarly) { mExitTasksEarly = exitTasksEarly; setPauseWork(false); } /** * Subclasses should override this to define any processing or work that must happen to produce * the final bitmap. This will be executed in a background thread and be long running. For * example, you could resize a large bitmap here, or pull down an image from the network. * * @param data The data to identify which image to process, as provided by * {@link ImageWorker#loadImage(Object, ImageView)} * @return The processed bitmap */ protected abstract Bitmap processBitmap(Object data); /** * Cancels any pending work attached to the provided ImageView. * @param imageView */ public static void cancelWork(ImageView imageView) { final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { bitmapWorkerTask.cancel(true); if (BuildConfig.DEBUG) { LOGD(TAG, "cancelWork - cancelled work for " + bitmapWorkerTask.data); } } } /** * Returns true if the current work has been canceled or if there was no work in * progress on this image view. * Returns false if the work in progress deals with the same data. The work is not * stopped in that case. */ public static boolean cancelPotentialWork(Object data, ImageView imageView) { final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { final Object bitmapData = bitmapWorkerTask.data; if (bitmapData == null || !bitmapData.equals(data)) { bitmapWorkerTask.cancel(true); LOGD(TAG, "cancelPotentialWork - cancelled work for " + data); } else { // The same work is already in progress. return false; } } return true; } /** * @param imageView Any imageView * @return Retrieve the currently active work task (if any) associated with this imageView. * null if there is no such task. */ private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getBitmapWorkerTask(); } } return null; } /** * The actual AsyncTask that will asynchronously process the image. */ private class BitmapWorkerTask extends AsyncTask<Object, Void, Bitmap> { private Object data; private final WeakReference<ImageView> imageViewReference; public BitmapWorkerTask(ImageView imageView) { imageViewReference = new WeakReference<ImageView>(imageView); } /** * Background processing. */ @Override protected Bitmap doInBackground(Object... params) { LOGD(TAG, "doInBackground - starting work"); data = params[0]; final String dataString = String.valueOf(data); Bitmap bitmap = null; // Wait here if work is paused and the task is not cancelled synchronized (mPauseWorkLock) { while (mPauseWork && !isCancelled()) { try { mPauseWorkLock.wait(); } catch (InterruptedException e) {} } } // If the image cache is available and this task has not been cancelled by another // thread and the ImageView that was originally bound to this task is still bound back // to this task and our "exit early" flag is not set then try and fetch the bitmap from // the cache if (mImageCache != null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { bitmap = mImageCache.getBitmapFromDiskCache(dataString); } // If the bitmap was not found in the cache and this task has not been cancelled by // another thread and the ImageView that was originally bound to this task is still // bound back to this task and our "exit early" flag is not set, then call the main // process method (as implemented by a subclass) if (bitmap == null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) { bitmap = processBitmap(params[0]); } // If the bitmap was processed and the image cache is available, then add the processed // bitmap to the cache for future use. Note we don't check if the task was cancelled // here, if it was, and the thread is still running, we may as well add the processed // bitmap to our cache as it might be used again in the future if (bitmap != null && mImageCache != null) { mImageCache.addBitmapToCache(dataString, bitmap); } LOGD(TAG, "doInBackground - finished work"); return bitmap; } /** * Once the image is processed, associates it to the imageView */ @Override protected void onPostExecute(Bitmap bitmap) { // if cancel was called on this task or the "exit early" flag is set then we're done if (isCancelled() || mExitTasksEarly) { bitmap = null; } final ImageView imageView = getAttachedImageView(); if (bitmap != null && imageView != null) { LOGD(TAG, "onPostExecute - setting bitmap"); setImageBitmap(imageView, bitmap); } } @Override protected void onCancelled() { super.onCancelled(); synchronized (mPauseWorkLock) { mPauseWorkLock.notifyAll(); } } /** * Returns the ImageView associated with this task as long as the ImageView's task still * points to this task as well. Returns null otherwise. */ private ImageView getAttachedImageView() { final ImageView imageView = imageViewReference.get(); final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (this == bitmapWorkerTask) { return imageView; } return null; } } /** * A custom Drawable that will be attached to the imageView while the work is in progress. * Contains a reference to the actual worker task, so that it can be stopped if a new binding is * required, and makes sure that only the last started worker process can bind its result, * independently of the finish order. */ private static class AsyncDrawable extends BitmapDrawable { private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference; public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) { super(res, bitmap); bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(bitmapWorkerTask); } public BitmapWorkerTask getBitmapWorkerTask() { return bitmapWorkerTaskReference.get(); } } /** * Called when the processing is complete and the final bitmap should be set on the ImageView. * * @param imageView * @param bitmap */ private void setImageBitmap(ImageView imageView, Bitmap bitmap) { if (mFadeInBitmap) { // Use TransitionDrawable to fade in final TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(android.R.color.transparent), new BitmapDrawable(mResources, bitmap) }); //noinspection deprecation imageView.setBackgroundDrawable(imageView.getDrawable()); imageView.setImageDrawable(td); td.startTransition(FADE_IN_TIME); } else { imageView.setImageBitmap(bitmap); } } /** * Pause any ongoing background work. This can be used as a temporary * measure to improve performance. For example background work could * be paused when a ListView or GridView is being scrolled using a * {@link android.widget.AbsListView.OnScrollListener} to keep * scrolling smooth. * <p> * If work is paused, be sure setPauseWork(false) is called again * before your fragment or activity is destroyed (for example during * {@link android.app.Activity#onPause()}), or there is a risk the * background thread will never finish. */ public void setPauseWork(boolean pauseWork) { synchronized (mPauseWorkLock) { mPauseWork = pauseWork; if (!mPauseWork) { mPauseWorkLock.notifyAll(); } } } protected class CacheAsyncTask extends AsyncTask<Object, Void, Void> { @Override protected Void doInBackground(Object... params) { switch ((Integer)params[0]) { case MESSAGE_CLEAR: clearCacheInternal(); break; case MESSAGE_INIT_DISK_CACHE: initDiskCacheInternal(); break; case MESSAGE_FLUSH: flushCacheInternal(); break; case MESSAGE_CLOSE: closeCacheInternal(); break; } return null; } } protected void initDiskCacheInternal() { if (mImageCache != null) { mImageCache.initDiskCache(); } } protected void clearCacheInternal() { if (mImageCache != null) { mImageCache.clearCache(); } } protected void flushCacheInternal() { if (mImageCache != null) { mImageCache.flush(); } } protected void closeCacheInternal() { if (mImageCache != null) { mImageCache.close(); mImageCache = null; } } public void clearCache() { new CacheAsyncTask().execute(MESSAGE_CLEAR); } public void flushCache() { new CacheAsyncTask().execute(MESSAGE_FLUSH); } public void closeCache() { new CacheAsyncTask().execute(MESSAGE_CLOSE); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.lang.reflect.InvocationTargetException; /** * A set of helper methods for best-effort method calls via reflection. */ public class ReflectionUtils { public static Object tryInvoke(Object target, String methodName, Object... args) { Class<?>[] argTypes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } return tryInvoke(target, methodName, argTypes, args); } public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes, Object... args) { try { return target.getClass().getMethod(methodName, argTypes).invoke(target, args); } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } return null; } public static <E> E callWithDefault(Object target, String methodName, E defaultValue) { try { //noinspection unchecked return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target); } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException ignored) { } catch (InvocationTargetException ignored) { } return defaultValue; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.ContentProvider; import android.net.Uri; import android.text.format.Time; import java.util.regex.Pattern; /** * Various utility methods used by {@link com.google.android.apps.iosched.io.JSONHandler}. */ public class ParserUtils { public static final String BLOCK_TYPE_SESSION = "session"; public static final String BLOCK_TYPE_CODE_LAB = "codelab"; public static final String BLOCK_TYPE_KEYNOTE = "keynote"; /** Used to sanitize a string to be {@link Uri} safe. */ private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]"); private static final Time sTime = new Time(); /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input) { if (input == null) { return null; } return sSanitizePattern.matcher(input.toLowerCase()).replaceAll(""); } /** * Parse the given string as a RFC 3339 timestamp, returning the value as * milliseconds since the epoch. */ public static long parseTime(String time) { sTime.parse3339(time); return sTime.toMillis(false); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.annotation.TargetApi; import android.app.ActivityManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.util.LruCache; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This class holds our bitmap caches (memory and disk). */ public class ImageCache { private static final String TAG = makeLogTag(ImageCache.class); // Default memory cache size as a percent of device memory class private static final float DEFAULT_MEM_CACHE_PERCENT = 0.15f; // Default disk cache size private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB // Default disk cache directory name private static final String DEFAULT_DISK_CACHE_DIR = "images"; // Compression settings when writing images to disk cache private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG; private static final int DEFAULT_COMPRESS_QUALITY = 75; private static final int DISK_CACHE_INDEX = 0; // Constants to easily toggle various caches private static final boolean DEFAULT_MEM_CACHE_ENABLED = true; private static final boolean DEFAULT_DISK_CACHE_ENABLED = true; private static final boolean DEFAULT_CLEAR_DISK_CACHE_ON_START = false; private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false; private DiskLruCache mDiskLruCache; private LruCache<String, Bitmap> mMemoryCache; private ImageCacheParams mCacheParams; private final Object mDiskCacheLock = new Object(); private boolean mDiskCacheStarting = true; /** * Creating a new ImageCache object using the specified parameters. * * @param cacheParams The cache parameters to use to initialize the cache */ public ImageCache(ImageCacheParams cacheParams) { init(cacheParams); } /** * Creating a new ImageCache object using the default parameters. * * @param context The context to use */ public ImageCache(Context context) { init(new ImageCacheParams(context)); } /** * Find and return an existing ImageCache stored in a {@link RetainFragment}, if not found a new * one is created using the supplied params and saved to a {@link RetainFragment}. * * @param fragmentManager The fragment manager to use when dealing with the retained fragment. * @param cacheParams The cache parameters to use if creating the ImageCache * @return An existing retained ImageCache object or a new one if one did not exist */ public static ImageCache findOrCreateCache( FragmentManager fragmentManager, ImageCacheParams cacheParams) { // Search for, or create an instance of the non-UI RetainFragment final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager); // See if we already have an ImageCache stored in RetainFragment ImageCache imageCache = (ImageCache) mRetainFragment.getObject(); // No existing ImageCache, create one and store it in RetainFragment if (imageCache == null) { imageCache = new ImageCache(cacheParams); mRetainFragment.setObject(imageCache); } return imageCache; } /** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache */ private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; // Set up memory cache if (mCacheParams.memoryCacheEnabled) { LOGD(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")"); mMemoryCache = new LruCache<String, Bitmap>(mCacheParams.memCacheSize) { /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, Bitmap bitmap) { final int bitmapSize = getBitmapSize(bitmap) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } // By default the disk cache is not initialized here as it should be initialized // on a separate thread due to disk access. if (cacheParams.initDiskCacheOnCreate) { // Set up disk cache initDiskCache(); } } /** * Initializes the disk cache. Note that this includes disk access so this should not be * executed on the main/UI thread. By default an ImageCache does not initialize the disk * cache when it is created, instead you should call initDiskCache() to initialize it on a * background thread. */ public void initDiskCache() { // Set up disk cache synchronized (mDiskCacheLock) { if (mDiskLruCache == null || mDiskLruCache.isClosed()) { File diskCacheDir = mCacheParams.diskCacheDir; if (mCacheParams.diskCacheEnabled && diskCacheDir != null) { if (!diskCacheDir.exists()) { diskCacheDir.mkdirs(); } if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) { try { mDiskLruCache = DiskLruCache.open( diskCacheDir, 1, 1, mCacheParams.diskCacheSize); LOGD(TAG, "Disk cache initialized"); } catch (final IOException e) { mCacheParams.diskCacheDir = null; LOGE(TAG, "initDiskCache - " + e); } } } } mDiskCacheStarting = false; mDiskCacheLock.notifyAll(); } } /** * Adds a bitmap to both memory and disk cache. * @param data Unique identifier for the bitmap to store * @param bitmap The bitmap to store */ public void addBitmapToCache(String data, Bitmap bitmap) { if (data == null || bitmap == null) { return; } // Add to memory cache if (mMemoryCache != null && mMemoryCache.get(data) == null) { mMemoryCache.put(data, bitmap); } synchronized (mDiskCacheLock) { // Add to disk cache if (mDiskLruCache != null) { final String key = hashKeyForDisk(data); OutputStream out = null; try { DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); if (snapshot == null) { final DiskLruCache.Editor editor = mDiskLruCache.edit(key); if (editor != null) { out = editor.newOutputStream(DISK_CACHE_INDEX); bitmap.compress( mCacheParams.compressFormat, mCacheParams.compressQuality, out); editor.commit(); out.close(); } } else { snapshot.getInputStream(DISK_CACHE_INDEX).close(); } } catch (final IOException e) { LOGE(TAG, "addBitmapToCache - " + e); } catch (Exception e) { LOGE(TAG, "addBitmapToCache - " + e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) {} } } } } /** * Get from memory cache. * * @param data Unique identifier for which item to get * @return The bitmap if found in cache, null otherwise */ public Bitmap getBitmapFromMemCache(String data) { if (mMemoryCache != null) { final Bitmap memBitmap = mMemoryCache.get(data); if (memBitmap != null) { LOGD(TAG, "Memory cache hit"); return memBitmap; } } return null; } /** * Get from disk cache. * * @param data Unique identifier for which item to get * @return The bitmap if found in cache, null otherwise */ public Bitmap getBitmapFromDiskCache(String data) { final String key = hashKeyForDisk(data); synchronized (mDiskCacheLock) { while (mDiskCacheStarting) { try { mDiskCacheLock.wait(); } catch (InterruptedException e) {} } if (mDiskLruCache != null) { InputStream inputStream = null; try { final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); if (snapshot != null) { LOGD(TAG, "Disk cache hit"); inputStream = snapshot.getInputStream(DISK_CACHE_INDEX); if (inputStream != null) { final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } } catch (final IOException e) { LOGE(TAG, "getBitmapFromDiskCache - " + e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) {} } } return null; } } /** * Clears both the memory and disk cache associated with this ImageCache object. Note that * this includes disk access so this should not be executed on the main/UI thread. */ public void clearCache() { if (mMemoryCache != null) { mMemoryCache.evictAll(); LOGD(TAG, "Memory cache cleared"); } synchronized (mDiskCacheLock) { mDiskCacheStarting = true; if (mDiskLruCache != null && !mDiskLruCache.isClosed()) { try { mDiskLruCache.delete(); LOGD(TAG, "Disk cache cleared"); } catch (IOException e) { LOGE(TAG, "clearCache - " + e); } mDiskLruCache = null; initDiskCache(); } } } /** * Flushes the disk cache associated with this ImageCache object. Note that this includes * disk access so this should not be executed on the main/UI thread. */ public void flush() { synchronized (mDiskCacheLock) { if (mDiskLruCache != null) { try { mDiskLruCache.flush(); LOGD(TAG, "Disk cache flushed"); } catch (IOException e) { LOGE(TAG, "flush - " + e); } } } } /** * Closes the disk cache associated with this ImageCache object. Note that this includes * disk access so this should not be executed on the main/UI thread. */ public void close() { synchronized (mDiskCacheLock) { if (mDiskLruCache != null) { try { if (!mDiskLruCache.isClosed()) { mDiskLruCache.close(); mDiskLruCache = null; LOGD(TAG, "Disk cache closed"); } } catch (IOException e) { LOGE(TAG, "close - " + e); } } } } /** * A holder class that contains cache parameters. */ public static class ImageCacheParams { public int memCacheSize; public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE; public File diskCacheDir; public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT; public int compressQuality = DEFAULT_COMPRESS_QUALITY; public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED; public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED; public boolean clearDiskCacheOnStart = DEFAULT_CLEAR_DISK_CACHE_ON_START; public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE; public ImageCacheParams(Context context) { init(getDiskCacheDir(context, DEFAULT_DISK_CACHE_DIR)); } public ImageCacheParams(Context context, String uniqueName) { init(getDiskCacheDir(context, uniqueName)); } public ImageCacheParams(File diskCacheDir) { init(diskCacheDir); } private void init(File diskCacheDir) { setMemCacheSizePercent(DEFAULT_MEM_CACHE_PERCENT); this.diskCacheDir = diskCacheDir; } /** * Sets the memory cache size based on a percentage of the max available VM memory. * Eg. setting percent to 0.2 would set the memory cache to one fifth of the avilable * memory. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8. * memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed * to construct a LruCache which takes an int in its constructor. * * This value should be chosen carefully based on a number of factors * Refer to the corresponding Android Training class for more discussion: * http://developer.android.com/training/displaying-bitmaps/ * * @param percent Percent of memory class to use to size memory cache */ public void setMemCacheSizePercent(float percent) { if (percent < 0.05f || percent > 0.8f) { throw new IllegalArgumentException("setMemCacheSizePercent - percent must be " + "between 0.05 and 0.8 (inclusive)"); } memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024); } private static int getMemoryClass(Context context) { return ((ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE)).getMemoryClass(); } } /** * Get a usable cache directory (external if available, internal otherwise). * * @param context The context to use * @param uniqueName A unique directory name to append to the cache dir * @return The cache dir */ public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() : context.getCacheDir().getPath(); return new File(cachePath + File.separator + uniqueName); } /** * A hashing method that changes a string (like a URL) into a hash suitable for using as a * disk filename. */ public static String hashKeyForDisk(String key) { String cacheKey; try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(key.getBytes()); cacheKey = bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { cacheKey = String.valueOf(key.hashCode()); } return cacheKey; } private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } /** * Get the size in bytes of a bitmap. * @param bitmap * @return size in bytes */ @TargetApi(12) public static int getBitmapSize(Bitmap bitmap) { if (UIUtils.hasHoneycombMR1()) { return bitmap.getByteCount(); } // Pre HC-MR1 return bitmap.getRowBytes() * bitmap.getHeight(); } /** * Check if external storage is built-in or removable. * * @return True if external storage is removable (like an SD card), false * otherwise. */ @TargetApi(9) public static boolean isExternalStorageRemovable() { if (UIUtils.hasGingerbread()) { return Environment.isExternalStorageRemovable(); } return true; } /** * Get the external app cache directory. * * @param context The context to use * @return The external cache dir */ @TargetApi(8) public static File getExternalCacheDir(Context context) { if (UIUtils.hasFroyo()) { return context.getExternalCacheDir(); } // Before Froyo we need to construct the external cache dir ourselves final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/"; return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir); } /** * Check how much usable space is available at a given path. * * @param path The path to check * @return The space available in bytes */ @TargetApi(9) public static long getUsableSpace(File path) { if (UIUtils.hasGingerbread()) { return path.getUsableSpace(); } final StatFs stats = new StatFs(path.getPath()); return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks(); } /** * Locate an existing instance of this Fragment or if not found, create and * add it using FragmentManager. * * @param fm The FragmentManager manager to use. * @return The existing instance of the Fragment or the new instance if just * created. */ public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) { // Check to see if we have retained the worker fragment. RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(TAG); // If not retained (or first time running), we need to create and add it. if (mRetainFragment == null) { mRetainFragment = new RetainFragment(); fm.beginTransaction().add(mRetainFragment, TAG).commitAllowingStateLoss(); } return mRetainFragment; } /** * A simple non-UI Fragment that stores a single Object and is retained over configuration * changes. It will be used to retain the ImageCache object. */ public static class RetainFragment extends Fragment { private Object mObject; /** * Empty constructor as per the Fragment documentation */ public RetainFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Make sure this Fragment is retained over a configuration change setRetainInstance(true); } /** * Store a single object in this Fragment. * * @param object The object to store */ public void setObject(Object object) { mObject = object; } /** * Get the stored object. * * @return The stored object */ public Object getObject() { return mObject; } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util.actionmodecompat; import android.annotation.TargetApi; import android.os.Build; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.AbsListView; import android.widget.ListView; /** * An implementation of {@link ActionMode} that proxies to the native * {@link android.view.ActionMode} implementation (shows the contextual action bar). */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) class ActionModeHoneycomb extends ActionMode { android.view.ActionMode mNativeActionMode; ActionModeHoneycomb() { } static ActionModeHoneycomb startInternal(final FragmentActivity activity, final Callback callback) { final ActionModeHoneycomb actionMode = new ActionModeHoneycomb(); activity.startActionMode(new android.view.ActionMode.Callback() { @Override public boolean onCreateActionMode(android.view.ActionMode nativeActionMode, Menu menu) { actionMode.mNativeActionMode = nativeActionMode; return callback.onCreateActionMode(actionMode, menu); } @Override public boolean onPrepareActionMode(android.view.ActionMode nativeActionMode, Menu menu) { return callback.onPrepareActionMode(actionMode, menu); } @Override public boolean onActionItemClicked(android.view.ActionMode nativeActionMode, MenuItem menuItem) { return callback.onActionItemClicked(actionMode, menuItem); } @Override public void onDestroyActionMode(android.view.ActionMode nativeActionMode) { callback.onDestroyActionMode(actionMode); } }); return actionMode; } /**{@inheritDoc}*/ @Override public void setTitle(CharSequence title) { mNativeActionMode.setTitle(title); } /**{@inheritDoc}*/ @Override public void setTitle(int resId) { mNativeActionMode.setTitle(resId); } /**{@inheritDoc}*/ @Override public void invalidate() { mNativeActionMode.invalidate(); } /**{@inheritDoc}*/ @Override public void finish() { mNativeActionMode.finish(); } /**{@inheritDoc}*/ @Override public CharSequence getTitle() { return mNativeActionMode.getTitle(); } /**{@inheritDoc}*/ @Override public MenuInflater getMenuInflater() { return mNativeActionMode.getMenuInflater(); } public static void beginMultiChoiceMode(ListView listView, FragmentActivity activity, final MultiChoiceModeListener listener) { listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() { ActionModeHoneycomb mWrappedActionMode; @Override public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int position, long id, boolean checked) { listener.onItemCheckedStateChanged(mWrappedActionMode, position, id, checked); } @Override public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) { if (mWrappedActionMode == null) { mWrappedActionMode = new ActionModeHoneycomb(); mWrappedActionMode.mNativeActionMode = actionMode; } return listener.onCreateActionMode(mWrappedActionMode, menu); } @Override public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) { if (mWrappedActionMode == null) { mWrappedActionMode = new ActionModeHoneycomb(); mWrappedActionMode.mNativeActionMode = actionMode; } return listener.onPrepareActionMode(mWrappedActionMode, menu); } @Override public boolean onActionItemClicked(android.view.ActionMode actionMode, MenuItem menuItem) { return listener.onActionItemClicked(mWrappedActionMode, menuItem); } @Override public void onDestroyActionMode(android.view.ActionMode actionMode) { listener.onDestroyActionMode(mWrappedActionMode); } }); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util.actionmodecompat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import java.util.ArrayList; /** * A <em>really</em> dumb implementation of the {@link android.view.Menu} interface, that's only * useful for our actionbar-compat purposes. See * <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for a more complete * implementation. */ public class SimpleMenu implements Menu { private Context mContext; private Resources mResources; private ArrayList<SimpleMenuItem> mItems; public SimpleMenu(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<SimpleMenuItem>(); } public Context getContext() { return mContext; } public Resources getResources() { return mResources; } public MenuItem add(CharSequence title) { return addInternal(0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, mResources.getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(itemId, order, title); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(itemId, order, mResources.getString(titleRes)); } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int itemId, int order, CharSequence title) { final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title); mItems.add(findInsertIndex(mItems, order), item); return item; } private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) { for (int i = items.size() - 1; i >= 0; i--) { MenuItem item = items.get(i); if (item.getOrder() <= order) { return i + 1; } } return 0; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public void removeItem(int itemId) { removeItemAtInt(findItemIndex(itemId)); } private void removeItemAtInt(int index) { if ((index < 0) || (index >= mItems.size())) { return; } mItems.remove(index); } public void clear() { mItems.clear(); } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return item; } } return null; } public int size() { return mItems.size(); } public MenuItem getItem(int index) { return mItems.get(index); } // Unsupported operations. public SubMenu addSubMenu(CharSequence charSequence) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public int addIntentOptions(int i, int i1, int i2, ComponentName componentName, Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void removeGroup(int i) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupCheckable(int i, boolean b, boolean b1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupVisible(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupEnabled(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean hasVisibleItems() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void close() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performShortcut(int i, KeyEvent keyEvent, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performIdentifierAction(int i, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setQwertyMode(boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util.actionmodecompat; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * A pre-Honeycomb, simple implementation of {@link ActionMode} that simply shows a context menu * for the action mode. */ class ActionModeBase extends ActionMode implements DialogInterface.OnClickListener { private FragmentActivity mActivity; private Callback mCallback; private MenuInflater mMenuInflater; private ContextMenuDialog mDialog; private CharSequence mTitle; private SimpleMenu mMenu; private ArrayAdapter<MenuItem> mMenuItemArrayAdapter; ActionModeBase(FragmentActivity activity, Callback callback) { mActivity = activity; mCallback = callback; } static ActionModeBase startInternal(final FragmentActivity activity, Callback callback) { final ActionModeBase actionMode = new ActionModeBase(activity, callback); actionMode.startInternal(); return actionMode; } void startInternal() { mMenu = new SimpleMenu(mActivity); mCallback.onCreateActionMode(this, mMenu); mCallback.onPrepareActionMode(this, mMenu); mMenuItemArrayAdapter = new ArrayAdapter<MenuItem>(mActivity, android.R.layout.simple_list_item_1, android.R.id.text1); invalidate(); // DialogFragment.show() will take care of adding the fragment // in a transaction. We also want to remove any currently showing // dialog, so make our own transaction and take care of that here. FragmentManager fm = mActivity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("action_mode_context_menu"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); mDialog = new ContextMenuDialog(); mDialog.mActionModeBase = this; mDialog.show(ft, "action_mode_context_menu"); } /**{@inheritDoc}*/ @Override public void setTitle(CharSequence title) { mTitle = title; } /**{@inheritDoc}*/ @Override public void setTitle(int resId) { mTitle = mActivity.getResources().getString(resId); } /**{@inheritDoc}*/ @Override public void invalidate() { mMenuItemArrayAdapter.clear(); List<MenuItem> items = new ArrayList<MenuItem>(); for (int i = 0; i < mMenu.size(); i++) { MenuItem item = mMenu.getItem(i); if (item.isVisible()) { items.add(item); } } Collections.sort(items, new Comparator<MenuItem>() { @Override public int compare(MenuItem a, MenuItem b) { return a.getOrder() - b.getOrder(); } }); for (MenuItem item : items) { mMenuItemArrayAdapter.add(item); } } /**{@inheritDoc}*/ @Override public void finish() { if (mDialog != null) { mDialog.dismiss(); } mCallback.onDestroyActionMode(this); mDialog = null; mMenu = null; mMenuItemArrayAdapter = null; mTitle = null; } /**{@inheritDoc}*/ @Override public CharSequence getTitle() { return mTitle; } /**{@inheritDoc}*/ @Override public MenuInflater getMenuInflater() { if (mMenuInflater == null) { mMenuInflater = mActivity.getMenuInflater(); } return mMenuInflater; } public static void beginMultiChoiceMode(ListView listView, final FragmentActivity activity, final MultiChoiceModeListener listener) { listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { ActionMode mode = ActionModeBase.start(activity, listener); listener.onItemCheckedStateChanged(mode, position, id, true); return true; } }); } @Override public void onClick(DialogInterface dialogInterface, int position) { mCallback.onActionItemClicked(this, mMenuItemArrayAdapter.getItem(position)); } public static class ContextMenuDialog extends DialogFragment { ActionModeBase mActionModeBase; public ContextMenuDialog() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (mActionModeBase == null) { // TODO: support orientation changes and avoid this awful hack. final Dialog d = new AlertDialog.Builder(getActivity()).create(); new Handler().post(new Runnable() { @Override public void run() { d.dismiss(); } }); return d; } return new AlertDialog.Builder(getActivity()) .setTitle(mActionModeBase.mTitle) .setAdapter(mActionModeBase.mMenuItemArrayAdapter, mActionModeBase) .create(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (mActionModeBase == null) { return; } mActionModeBase.mDialog = null; mActionModeBase.finish(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util.actionmodecompat; /** * A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}. * It acts as the {@link ActionMode.Callback} for the selection mode and also receives {@link * #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user selects and * deselects list items. */ public interface MultiChoiceModeListener extends ActionMode.Callback { /** * Called when an item is checked or unchecked during selection mode. * * @param mode The {@link ActionMode} providing the selection mode * @param position Adapter position of the item that was checked or unchecked * @param id Adapter ID of the item that was checked or unchecked * @param checked <code>true</code> if the item is now checked, <code>false</code> if the * item is now unchecked. */ public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked); }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util.actionmodecompat; import android.annotation.TargetApi; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.ActionProvider; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; /** * A <em>really</em> dumb implementation of the {@link android.view.MenuItem} interface, that's only * useful for our actionbar-compat purposes. See * <code>com.android.internal.view.menu.MenuItemImpl</code> in AOSP for a more complete * implementation. */ public class SimpleMenuItem implements MenuItem { private SimpleMenu mMenu; private final int mId; private final int mOrder; private CharSequence mTitle; private CharSequence mTitleCondensed; private Drawable mIconDrawable; private int mIconResId = 0; private boolean mEnabled = true; public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) { mMenu = menu; mId = id; mOrder = order; mTitle = title; } public int getItemId() { return mId; } public int getOrder() { return mOrder; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int titleRes) { return setTitle(mMenu.getContext().getString(titleRes)); } public CharSequence getTitle() { return mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setIcon(Drawable icon) { mIconResId = 0; mIconDrawable = icon; return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != 0) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setEnabled(boolean enabled) { mEnabled = enabled; return this; } public boolean isEnabled() { return mEnabled; } // No-op operations. We use no-ops to allow inflation from menu XML. public int getGroupId() { // Noop return 0; } public View getActionView() { // Noop return null; } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public MenuItem setActionProvider(ActionProvider actionProvider) { // Noop return this; } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public ActionProvider getActionProvider() { // Noop return null; } public boolean expandActionView() { // Noop return false; } public boolean collapseActionView() { // Noop return false; } public boolean isActionViewExpanded() { // Noop return false; } @Override @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public MenuItem setOnActionExpandListener(OnActionExpandListener onActionExpandListener) { // Noop return this; } public MenuItem setIntent(Intent intent) { // Noop return this; } public Intent getIntent() { // Noop return null; } public MenuItem setShortcut(char c, char c1) { // Noop return this; } public MenuItem setNumericShortcut(char c) { // Noop return this; } public char getNumericShortcut() { // Noop return 0; } public MenuItem setAlphabeticShortcut(char c) { // Noop return this; } public char getAlphabeticShortcut() { // Noop return 0; } public MenuItem setCheckable(boolean b) { // Noop return this; } public boolean isCheckable() { // Noop return false; } public MenuItem setChecked(boolean b) { // Noop return this; } public boolean isChecked() { // Noop return false; } public MenuItem setVisible(boolean b) { // Noop return this; } public boolean isVisible() { // Noop return true; } public boolean hasSubMenu() { // Noop return false; } public SubMenu getSubMenu() { // Noop return null; } public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) { // Noop return this; } public ContextMenu.ContextMenuInfo getMenuInfo() { // Noop return null; } public void setShowAsAction(int i) { // Noop } public MenuItem setShowAsActionFlags(int i) { // Noop return null; } public MenuItem setActionView(View view) { // Noop return this; } public MenuItem setActionView(int i) { // Noop return this; } @Override public String toString() { return mTitle == null ? "" : mTitle.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util.actionmodecompat; import com.google.android.apps.iosched.util.UIUtils; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ListView; /** * A compatibility shim for {@link android.view.ActionMode} that shows context menus * on pre-Honeycomb devices. */ public abstract class ActionMode { private Object mTag; public static ActionMode start(FragmentActivity activity, Callback callback) { if (UIUtils.hasHoneycomb()) { return ActionModeHoneycomb.startInternal(activity, callback); } else { return ActionModeBase.startInternal(activity, callback); } } public static void setMultiChoiceMode(ListView listView, FragmentActivity activity, MultiChoiceModeListener listener) { if (UIUtils.hasHoneycomb()) { ActionModeHoneycomb.beginMultiChoiceMode(listView, activity, listener); } else { ActionModeBase.beginMultiChoiceMode(listView, activity, listener); } } /** * Set a tag object associated with this ActionMode. * * <p>Like the tag available to views, this allows applications to associate arbitrary * data with an ActionMode for later reference. * * @param tag Tag to associate with this ActionMode * * @see #getTag() */ public void setTag(Object tag) { mTag = tag; } /** * Retrieve the tag object associated with this ActionMode. * * <p>Like the tag available to views, this allows applications to associate arbitrary * data with an ActionMode for later reference. * * @return Tag associated with this ActionMode * * @see #setTag(Object) */ public Object getTag() { return mTag; } /** * Set the title of the action mode. This method will have no visible effect if * a custom view has been set. * * @param title Title string to set * * @see #setTitle(int) * @see #setCustomView(View) */ public abstract void setTitle(CharSequence title); /** * Set the title of the action mode. This method will have no visible effect if * a custom view has been set. * * @param resId Resource ID of a string to set as the title * * @see #setTitle(CharSequence) * @see #setCustomView(View) */ public abstract void setTitle(int resId); /** * Invalidate the action mode and refresh menu content. The mode's * {@link ActionMode.Callback} will have its * {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called. * If it returns true the menu will be scanned for updated content and any relevant changes * will be reflected to the user. */ public abstract void invalidate(); /** * Finish and close this action mode. The action mode's {@link ActionMode.Callback} will * have its {@link Callback#onDestroyActionMode(ActionMode)} method called. */ public abstract void finish(); /** * Returns the current title of this action mode. * @return Title text */ public abstract CharSequence getTitle(); /** * Returns a {@link MenuInflater} with the ActionMode's context. */ public abstract MenuInflater getMenuInflater(); /** * Returns whether the UI presenting this action mode can take focus or not. * This is used by internal components within the framework that would otherwise * present an action mode UI that requires focus, such as an EditText as a custom view. * * @return true if the UI used to show this action mode can take focus * @hide Internal use only */ public boolean isUiFocusable() { return true; } /** * Callback interface for action modes. Supplied to * {@link View#startActionMode(Callback)}, a Callback * configures and handles events raised by a user's interaction with an action mode. * * <p>An action mode's lifecycle is as follows: * <ul> * <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial * creation</li> * <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation * and any time the {@link ActionMode} is invalidated</li> * <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a * contextual action button is clicked</li> * <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode * is closed</li> * </ul> */ public interface Callback { /** * Called when action mode is first created. The menu supplied will be used to * generate action buttons for the action mode. * * @param mode ActionMode being created * @param menu Menu used to populate action buttons * @return true if the action mode should be created, false if entering this * mode should be aborted. */ public boolean onCreateActionMode(ActionMode mode, Menu menu); /** * Called to refresh an action mode's action menu whenever it is invalidated. * * @param mode ActionMode being prepared * @param menu Menu used to populate action buttons * @return true if the menu or action mode was updated, false otherwise. */ public boolean onPrepareActionMode(ActionMode mode, Menu menu); /** * Called to report a user click on an action button. * * @param mode The current ActionMode * @param item The item that was clicked * @return true if this callback handled the event, false if the standard MenuItem * invocation should continue. */ public boolean onActionItemClicked(ActionMode mode, MenuItem item); /** * Called when an action mode is about to be exited and destroyed. * * @param mode The current ActionMode being destroyed */ public void onDestroyActionMode(ActionMode mode); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter.Section; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This is the service that provides the factory to be bound to the collection service. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyScheduleWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new WidgetRemoveViewsFactory(this.getApplicationContext()); } /** * This is the factory that will provide data to the collection widget. */ private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory { private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class); private Context mContext; private Cursor mCursor; private SparseIntArray mPMap; private List<SimpleSectionedListAdapter.Section> mSections; private SparseBooleanArray mHeaderPositionMap; public WidgetRemoveViewsFactory(Context context) { mContext = context; } public void onCreate() { // Since we reload the cursor in onDataSetChanged() which gets called immediately after // onCreate(), we do nothing here. } public void onDestroy() { if (mCursor != null) { mCursor.close(); } } public int getCount() { if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) { return 0; } int size = mCursor.getCount() + mSections.size(); if (size < 10) { init(); size = mCursor.getCount() + mSections.size(); } LOGV(TAG, "size returned:" + size); return size; } public RemoteViews getViewAt(int position) { RemoteViews rv; boolean isSectionHeader = mHeaderPositionMap.get(position); int offset = mPMap.get(position); if (isSectionHeader) { rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header); Section section = mSections.get(offset - 1); rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle()); } else { int cursorPosition = position - offset; mCursor.moveToPosition(cursorPosition); rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_block_widget); final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE); final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META); final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START); final Resources res = mContext.getResources(); if (ParserUtils.BLOCK_TYPE_SESSION.equals(type) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) { final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); if (numStarredSessions == 0) { // No sessions starred rv.setTextViewText(R.id.block_title, mContext.getString( R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1_positive)); rv.setTextViewText(R.id.block_subtitle, mContext.getString( R.string.schedule_empty_slot_subtitle)); rv.setViewVisibility(R.id.extra_button, View.GONE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, false); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); String starredSessionRoomName = mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (starredSessionRoomName == null) { // TODO: remove this WAR for API not returning rooms for code labs starredSessionRoomName = mContext.getString( starredSessionTitle.contains("Code Lab") ? R.string.codelab_room : R.string.unknown_room); } rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, starredSessionRoomName); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID, starredSessionId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); final Intent fillInIntent2 = new Intent(); final Bundle extras2 = new Bundle(); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true); extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); fillInIntent2.putExtras(extras2); rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2); } else { // 2 or more sessions starred rv.setTextViewText(R.id.block_title, mContext.getString(R.string.schedule_conflict_title, numStarredSessions)); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, mContext.getString(R.string.schedule_conflict_subtitle)); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); final Intent fillInIntent2 = new Intent(); final Bundle extras2 = new Bundle(); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true); extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true); extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, numStarredSessions); fillInIntent2.putExtras(extras2); rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2); } rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2)); } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room)); rv.setViewVisibility(R.id.extra_button, View.GONE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID, starredSessionId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); } else { rv.setTextViewText(R.id.block_title, blockTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled)); rv.setTextViewText(R.id.block_subtitle, blockMeta); rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled)); rv.setViewVisibility(R.id.extra_button, View.GONE); // TODO: use TaskStackBuilder final Intent fillInIntent = new Intent(); final Bundle extras = new Bundle(); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId); extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType); extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, -1); fillInIntent.putExtras(extras); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent); } rv.setTextViewText(R.id.block_time, DateUtils.formatDateTime(mContext, blockStart, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR)); } return rv; } public RemoteViews getLoadingView() { return null; } public int getViewTypeCount() { return 2; } public long getItemId(int position) { return position; } public boolean hasStableIds() { return true; } public void onDataSetChanged() { init(); } private void init() { if (mCursor != null) { mCursor.close(); } mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, ScheduleContract.Blocks.BLOCK_END + " >= ?", new String[]{ Long.toString(UIUtils.getCurrentTime(mContext)) }, ScheduleContract.Blocks.DEFAULT_SORT); mSections = new ArrayList<SimpleSectionedListAdapter.Section>(); mCursor.moveToFirst(); long previousTime = -1; long time; mPMap = new SparseIntArray(); mHeaderPositionMap = new SparseBooleanArray(); int offset = 0; int globalPosition = 0; while (!mCursor.isAfterLast()) { time = mCursor.getLong(BlocksQuery.BLOCK_START); if (!UIUtils.isSameDay(previousTime, time)) { mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(), DateUtils.formatDateTime(mContext, time, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY))); ++offset; mHeaderPositionMap.put(globalPosition, true); mPMap.put(globalPosition, offset); ++globalPosition; } mHeaderPositionMap.put(globalPosition, false); mPMap.put(globalPosition, offset); ++globalPosition; previousTime = time; mCursor.moveToNext(); } LOGV(TAG, "Leaving init()"); } } public interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int NUM_STARRED_SESSIONS = 7; int STARRED_SESSION_ID = 8; int STARRED_SESSION_TITLE = 9; int STARRED_SESSION_ROOM_NAME = 10; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import android.accounts.Account; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.widget.RemoteViews; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The app widget's AppWidgetProvider. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyScheduleWidgetProvider extends AppWidgetProvider { private static final String TAG = makeLogTag(MyScheduleWidgetProvider.class); public static final String EXTRA_BLOCK_ID = "block_id"; public static final String EXTRA_STARRED_SESSION_ID = "star_session_id"; public static final String EXTRA_BLOCK_TYPE = "block_type"; public static final String EXTRA_STARRED_SESSION = "starred_session"; public static final String EXTRA_NUM_STARRED_SESSIONS = "num_starred_sessions"; public static final String EXTRA_BUTTON = "extra_button"; public static final String CLICK_ACTION = "com.google.android.apps.iosched.appwidget.action.CLICK"; public static final String REFRESH_ACTION = "com.google.android.apps.iosched.appwidget.action.REFRESH"; public static final String EXTRA_PERFORM_SYNC = "com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC"; private static Handler sWorkerQueue; // TODO: this will get destroyed when the app process is killed. need better observer strategy. private static SessionDataProviderObserver sDataObserver; public MyScheduleWidgetProvider() { // Start the worker thread HandlerThread sWorkerThread = new HandlerThread("MyScheduleWidgetProvider-worker"); sWorkerThread.start(); sWorkerQueue = new Handler(sWorkerThread.getLooper()); } @Override public void onEnabled(Context context) { final ContentResolver r = context.getContentResolver(); if (sDataObserver == null) { final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class); sDataObserver = new SessionDataProviderObserver(mgr, cn, sWorkerQueue); r.registerContentObserver(ScheduleContract.Sessions.CONTENT_URI, true, sDataObserver); } } @Override public void onReceive(final Context context, Intent widgetIntent) { final String action = widgetIntent.getAction(); if (REFRESH_ACTION.equals(action)) { final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false); sWorkerQueue.removeMessages(0); sWorkerQueue.post(new Runnable() { @Override public void run() { // Trigger sync String chosenAccountName = AccountUtils.getChosenAccountName(context); if (shouldSync && chosenAccountName != null) { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync( new Account(chosenAccountName, GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, extras); } // Update widget final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, MyScheduleWidgetProvider.class); mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_schedule_list); } }); } else if (CLICK_ACTION.equals(action)) { String blockId = widgetIntent.getStringExtra(EXTRA_BLOCK_ID); int numStarredSessions = widgetIntent.getIntExtra(EXTRA_NUM_STARRED_SESSIONS, 0); String starredSessionId = widgetIntent.getStringExtra(EXTRA_STARRED_SESSION_ID); String blockType = widgetIntent.getStringExtra(EXTRA_BLOCK_TYPE); boolean starredSession = widgetIntent.getBooleanExtra(EXTRA_STARRED_SESSION, false); boolean extraButton = widgetIntent.getBooleanExtra(EXTRA_BUTTON, false); LOGV(TAG, "blockId:" + blockId); LOGV(TAG, "starredSession:" + starredSession); LOGV(TAG, "blockType:" + blockType); LOGV(TAG, "numStarredSessions:" + numStarredSessions); LOGV(TAG, "extraButton:" + extraButton); if (ParserUtils.BLOCK_TYPE_SESSION.equals(blockType) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(blockType)) { Uri sessionsUri; if (numStarredSessions == 0) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri( blockId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else if (numStarredSessions == 1) { if (extraButton) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); LOGV(TAG, "sessionsUri extraButton:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { sessionsUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } else { if (extraButton) { sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); LOGV(TAG, "sessionsUri extraButton:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { sessionsUri = ScheduleContract.Blocks.buildStarredSessionsUri(blockId); LOGV(TAG, "sessionsUri:" + sessionsUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(blockType)) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(starredSessionId); LOGV(TAG, "sessionUri:" + sessionUri); Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.setClass(context, SessionLivestreamActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } super.onReceive(context, widgetIntent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final boolean isAuthenticated = AccountUtils.isAuthenticated(context); for (int appWidgetId : appWidgetIds) { // Specify the service to provide data for the collection widget. Note that we need to // embed the appWidgetId via the data otherwise it will be ignored. final Intent intent = new Intent(context, MyScheduleWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout); compatSetRemoteAdapter(rv, appWidgetId, intent); // Set the empty view to be displayed if the collection is empty. It must be a sibling // view of the collection view. rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty); rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated ? R.string.empty_widget_text : R.string.empty_widget_text_signed_out)); final Intent onClickIntent = new Intent(context, MyScheduleWidgetProvider.class); onClickIntent.setAction(MyScheduleWidgetProvider.CLICK_ACTION); onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME))); final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent); final Intent refreshIntent = new Intent(context, MyScheduleWidgetProvider.class); refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION); refreshIntent.putExtra(MyScheduleWidgetProvider.EXTRA_PERFORM_SYNC, true); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent); final Intent openAppIntent = new Intent(context, HomeActivity.class); final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void compatSetRemoteAdapter(RemoteViews rv, int appWidgetId, Intent intent) { if (UIUtils.hasICS()) { rv.setRemoteAdapter(R.id.widget_schedule_list, intent); } else { //noinspection deprecation rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent); } } private static class SessionDataProviderObserver extends ContentObserver { private AppWidgetManager mAppWidgetManager; private ComponentName mComponentName; SessionDataProviderObserver(AppWidgetManager appWidgetManager, ComponentName componentName, Handler handler) { super(handler); mAppWidgetManager = appWidgetManager; mComponentName = componentName; } @Override public void onChange(boolean selfChange) { // The data has changed, so notify the widget that the collection view needs to be updated. // In response, the factory's onDataSetChanged() will be called which will requery the // cursor for the new data. mAppWidgetManager.notifyAppWidgetViewDataChanged( mAppWidgetManager.getAppWidgetIds(mComponentName), R.id.widget_schedule_list); } } }
Java