code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import java.util.Calendar; import java.util.GregorianCalendar; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.TimedActionUtils; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; import com.rdrrlabs.example.timer1app.ui.EditActionUI; import com.rdrrlabs.example.timer1app.ui.EditProfileUI; /** * A base holder class that keeps tracks of the current cursor * and the common widgets of the two derived holders. */ public abstract class BaseHolder { public static final String TAG = BaseHolder.class.getSimpleName(); /** * The text view that holds the title or description as well * as the "check box". */ private final TextView mDescription; protected final ProfilesUiImpl mActivity; public BaseHolder(ProfilesUiImpl activity, View view) { mActivity = activity; mDescription = view != null ? (TextView) view.findViewById(R.id.description) : null; } protected void setUiData(String description, Drawable state) { if (description != null) mDescription.setText(description); if (state != null) mDescription.setCompoundDrawablesWithIntrinsicBounds( state /*left*/, null /*top*/, null /*right*/, null /*bottom*/); } public abstract void setUiData(); public abstract void onItemSelected(); public abstract void onCreateContextMenu(ContextMenu menu); public abstract void onContextMenuSelected(MenuItem item); // --- profile actions --- private void startEditActivity(Class<?> activity, String extra_id, long extra_value) { Intent intent = new Intent(mActivity.getActivity(), activity); intent.putExtra(extra_id, extra_value); mActivity.getActivity().startActivityForResult(intent, ProfilesUiImpl.DATA_CHANGED); } protected void deleteProfile(Cursor cursor) { ColIndexes colIndexes = mActivity.getColIndexes(); final long row_id = cursor.getLong(colIndexes.mIdColIndex); String title = cursor.getString(colIndexes.mDescColIndex); mActivity.showTempDialog(row_id, title, ProfilesUiImpl.DIALOG_DELETE_PROFILE); } protected void insertNewProfile(Cursor beforeCursor) { long prof_index = 0; if (beforeCursor != null) { ColIndexes colIndexes = mActivity.getColIndexes(); prof_index = beforeCursor.getLong(colIndexes.mProfIdColIndex) >> Columns.PROFILE_SHIFT; } ProfilesDB profDb = mActivity.getProfilesDb(); prof_index = profDb.insertProfile(prof_index, mActivity.getActivity().getString(R.string.insertprofile_new_profile_title), true /*isEnabled*/); startEditActivity(EditProfileUI.class, EditProfileUI.EXTRA_PROFILE_ID, prof_index << Columns.PROFILE_SHIFT); } protected void editProfile(Cursor cursor) { ColIndexes colIndexes = mActivity.getColIndexes(); long prof_id = cursor.getLong(colIndexes.mProfIdColIndex); startEditActivity(EditProfileUI.class, EditProfileUI.EXTRA_PROFILE_ID, prof_id); } // --- timed actions ---- protected void deleteTimedAction(Cursor cursor) { ColIndexes colIndexes = mActivity.getColIndexes(); final long row_id = cursor.getLong(colIndexes.mIdColIndex); String description = cursor.getString(colIndexes.mDescColIndex); mActivity.showTempDialog(row_id, description, ProfilesUiImpl.DIALOG_DELETE_ACTION); } protected void insertNewAction(Cursor beforeCursor) { long prof_index = 0; long action_index = 0; if (beforeCursor != null) { ColIndexes colIndexes = mActivity.getColIndexes(); prof_index = beforeCursor.getLong(colIndexes.mProfIdColIndex); action_index = prof_index & Columns.ACTION_MASK; prof_index = prof_index >> Columns.PROFILE_SHIFT; } Calendar c = new GregorianCalendar(); c.setTimeInMillis(System.currentTimeMillis()); int hourMin = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); int day = TimedActionUtils.calendarDayToActionDay(c); ProfilesDB profDb = mActivity.getProfilesDb(); action_index = profDb.insertTimedAction( prof_index, action_index, hourMin, // hourMin day, // days "", // actions 0 // nextMs ); long action_id = (prof_index << Columns.PROFILE_SHIFT) + action_index; startEditActivity(EditActionUI.class, EditActionUI.EXTRA_ACTION_ID, action_id); } protected void editAction(Cursor cursor) { try { ColIndexes colIndexes = mActivity.getColIndexes(); long action_id = cursor.getLong(colIndexes.mProfIdColIndex); startEditActivity(EditActionUI.class, EditActionUI.EXTRA_ACTION_ID, action_id); } catch (Throwable t) { Log.e(TAG, "editAction", t); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewTreeObserver; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.view.ViewTreeObserver.OnPreDrawListener; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.app.TimerifficApp; import com.rdrrlabs.example.timer1app.app.UpdateReceiver; import com.rdrrlabs.example.timer1app.core.app.BackupWrapper; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; import com.rdrrlabs.example.timer1app.core.utils.AgentWrapper; import com.rdrrlabs.example.timer1app.ui.EditProfileUI; import com.rdrrlabs.example.timer1app.ui.ErrorReporterUI; import com.rdrrlabs.example.timer1app.ui.GlobalStatus; import com.rdrrlabs.example.timer1app.ui.GlobalToggle; import com.rdrrlabs.example.timer1app.ui.IActivityDelegate; import com.rdrrlabs.example.timer1app.ui.IntroUI; import com.rdrrlabs.example.timer1app.ui.PrefsUI; public class ProfilesUiImpl implements IActivityDelegate<ProfilesUiImpl> { private static final boolean DEBUG = true; public static final String TAG = ProfilesUiImpl.class.getSimpleName(); public static final int DATA_CHANGED = 42; static final int SETTINGS_UPDATED = 43; static final int CHECK_SERVICES = 44; static final int DIALOG_RESET_CHOICES = 0; public static final int DIALOG_DELETE_ACTION = 1; public static final int DIALOG_DELETE_PROFILE = 2; static final int DIALOG_CHECK_SERVICES = 3; private final Activity mActivity; private ListView mProfilesList; private ProfileCursorAdapter mAdapter; private LayoutInflater mLayoutInflater; private ProfilesDB mProfilesDb; private AgentWrapper mAgentWrapper; private PrefsValues mPrefsValues; private Drawable mGrayDot; private Drawable mGreenDot; private Drawable mPurpleDot; private Drawable mCheckOn; private Drawable mCheckOff; private GlobalToggle mGlobalToggle; private GlobalStatus mGlobalStatus; private long mTempDialogRowId; private String mTempDialogTitle; private Cursor mCursor; public static class ColIndexes { public int mIdColIndex; public int mTypeColIndex; public int mDescColIndex; public int mEnableColIndex; public int mProfIdColIndex; }; private ColIndexes mColIndexes = new ColIndexes(); private BackupWrapper mBackupWrapper; public ProfilesUiImpl(Activity profileActivity) { mActivity = profileActivity; } /** * Called when the activity is created. * <p/> * Initializes row indexes and buttons. * Profile list & db is initialized in {@link #onResume()}. */ public void onCreate(Bundle savedInstanceState) { Log.d(TAG, String.format("Started %s", getClass().getSimpleName())); mActivity.setContentView(R.layout.profiles_screen); mLayoutInflater = mActivity.getLayoutInflater(); mPrefsValues = new PrefsValues(mActivity); mGrayDot = mActivity.getResources().getDrawable(R.drawable.dot_gray); mGreenDot = mActivity.getResources().getDrawable(R.drawable.dot_green); mPurpleDot = mActivity.getResources().getDrawable(R.drawable.dot_purple); mCheckOn = mActivity.getResources().getDrawable(R.drawable.btn_check_on); mCheckOff = mActivity.getResources().getDrawable(R.drawable.btn_check_off); initButtons(); showIntroAtStartup(); mAgentWrapper = new AgentWrapper(); mAgentWrapper.start(mActivity); mAgentWrapper.event(AgentWrapper.Event.OpenProfileUI); } private void showIntroAtStartup() { final TimerifficApp tapp = TimerifficApp.getInstance(mActivity); if (tapp.isFirstStart() && mGlobalToggle != null) { final Runnable action = new Runnable() { public void run() { showIntro(false, true); tapp.setFirstStart(false); } }; final ViewTreeObserver obs = mGlobalToggle.getViewTreeObserver(); obs.addOnPreDrawListener(new OnPreDrawListener() { public boolean onPreDraw() { mGlobalToggle.postDelayed(action, 200 /*delayMillis*/); ViewTreeObserver obs2 = mGlobalToggle.getViewTreeObserver(); obs2.removeOnPreDrawListener(this); return true; } }); } } private void showIntro(boolean force, boolean checkServices) { // force is set when this comes from Menu > About boolean showIntro = force; // if not forcing, does the user wants to see the intro? // true by default, unless disabled in the prefs if (!showIntro) { showIntro = !mPrefsValues.isIntroDismissed(); } // user doesn't want to see it... but we force it anyway if this is // a version upgrade int currentVersion = -1; try { currentVersion = mActivity.getPackageManager().getPackageInfo( mActivity.getPackageName(), 0).versionCode; // the version number is in format n.m.kk where n.m is the // actual version number, incremented for features and kk is // a sub-minor index of minor fixes. We clear these last digits // out and don't force to see the intro for these minor fixes. currentVersion = (currentVersion / 100) * 100; } catch (NameNotFoundException e) { // ignore. should not happen. } if (!showIntro && currentVersion > 0) { showIntro = currentVersion > mPrefsValues.getLastIntroVersion(); } if (showIntro) { // mark it as seen if (currentVersion > 0) { mPrefsValues.setLastIntroVersion(currentVersion); } Intent i = new Intent(mActivity, IntroUI.class); if (force) i.putExtra(IntroUI.EXTRA_NO_CONTROLS, true); mActivity.startActivityForResult(i, CHECK_SERVICES); return; } if (checkServices) { onCheckServices(); } } public Activity getActivity() { return mActivity; } public Cursor getCursor() { return mCursor; }; public ColIndexes getColIndexes() { return mColIndexes; } public ProfilesDB getProfilesDb() { return mProfilesDb; } public Drawable getGrayDot() { return mGrayDot; } public Drawable getGreenDot() { return mGreenDot; } public Drawable getPurpleDot() { return mPurpleDot; } public Drawable getCheckOff() { return mCheckOff; } public Drawable getCheckOn() { return mCheckOn; } /** * Initializes the profile list widget with a cursor adapter. * Creates a db connection. */ private void initProfileList() { Log.d(TAG, "init profile list"); if (mProfilesList == null) { mProfilesList = (ListView) mActivity.findViewById(R.id.profilesList); mProfilesList.setEmptyView(mActivity.findViewById(R.id.empty)); mProfilesList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View clickedView, int position, long id) { if (DEBUG) Log.d(TAG, String.format("onItemClick: pos %d, id %d", position, id)); BaseHolder h = null; h = getHolder(null, clickedView); if (h != null) h.onItemSelected(); } }); mProfilesList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View listview, ContextMenuInfo menuInfo) { if (DEBUG) Log.d(TAG, "onCreateContextMenu"); BaseHolder h = null; h = getHolder(menuInfo, null); if (h != null) h.onCreateContextMenu(menu); } }); } if (mProfilesDb == null) { mProfilesDb = new ProfilesDB(); mProfilesDb.onCreate(mActivity); String next = mPrefsValues.getStatusNextTS(); if (next == null) { // schedule a profile check to initialize the last/next status requestSettingsCheck(UpdateReceiver.TOAST_NONE); } } if (mAdapter == null) { if (mCursor != null) { mCursor.close(); mCursor = null; } mCursor = mProfilesDb.query( -1, //id new String[] { Columns._ID, Columns.TYPE, Columns.DESCRIPTION, Columns.IS_ENABLED, Columns.PROFILE_ID, // enable these only if they are actually used here //Columns.HOUR_MIN, //Columns.DAYS, //Columns.ACTIONS, //Columns.NEXT_MS } , //projection null, //selection null, //selectionArgs null //sortOrder ); mColIndexes.mIdColIndex = mCursor.getColumnIndexOrThrow(Columns._ID); mColIndexes.mTypeColIndex = mCursor.getColumnIndexOrThrow(Columns.TYPE); mColIndexes.mDescColIndex = mCursor.getColumnIndexOrThrow(Columns.DESCRIPTION); mColIndexes.mEnableColIndex = mCursor.getColumnIndexOrThrow(Columns.IS_ENABLED); mColIndexes.mProfIdColIndex = mCursor.getColumnIndexOrThrow(Columns.PROFILE_ID); mAdapter = new ProfileCursorAdapter(this, mColIndexes, mLayoutInflater); mProfilesList.setAdapter(mAdapter); Log.d(TAG, String.format("adapter count: %d", mProfilesList.getCount())); } } /** * Called when activity is resumed, or just after creation. * <p/> * Initializes the profile list & db. */ public void onResume() { initOnResume(); } private void initOnResume() { initProfileList(); setDataListener(); } /** * Called when the activity is getting paused. It might get destroyed * at any point. * <p/> * Reclaim all views (so that they tag's cursor can be cleared). * Destroys the db connection. */ public void onPause() { removeDataListener(); } public void onStop() { mAgentWrapper.stop(mActivity); } private void setDataListener() { TimerifficApp app = TimerifficApp.getInstance(mActivity); if (app != null) { app.setDataListener(new Runnable() { public void run() { onDataChanged(true /*backup*/); } }); // No backup on the first init onDataChanged(false /*backup*/); } } private void removeDataListener() { TimerifficApp app = TimerifficApp.getInstance(mActivity); if (app != null) { app.setDataListener(null); } } public void onRestoreInstanceState(Bundle savedInstanceState) { mTempDialogRowId = savedInstanceState.getLong("dlg_rowid"); mTempDialogTitle = savedInstanceState.getString("dlg_title"); } public void onSaveInstanceState(Bundle outState) { outState.putLong("dlg_rowid", mTempDialogRowId); outState.putString("dlg_title", mTempDialogTitle); } public void onDestroy() { if (mAdapter != null) { mAdapter.changeCursor(null); mAdapter = null; } if (mCursor != null) { mCursor.close(); mCursor = null; } if (mProfilesDb != null) { mProfilesDb.onDestroy(); mProfilesDb = null; } if (mProfilesList != null) { ArrayList<View> views = new ArrayList<View>(); mProfilesList.reclaimViews(views); mProfilesList.setAdapter(null); mProfilesList = null; } } public void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case DATA_CHANGED: onDataChanged(true /*backup*/); requestSettingsCheck(UpdateReceiver.TOAST_IF_CHANGED); break; case SETTINGS_UPDATED: updateGlobalState(); requestSettingsCheck(UpdateReceiver.TOAST_IF_CHANGED); break; case CHECK_SERVICES: onCheckServices(); } } private void onDataChanged(boolean backup) { if (mCursor != null) mCursor.requery(); mAdapter = null; initProfileList(); updateGlobalState(); if (backup) { if (mBackupWrapper == null) mBackupWrapper = new BackupWrapper(mActivity); mBackupWrapper.dataChanged(); } } public Dialog onCreateDialog(int id) { // In case of configuration change (e.g. screen rotation), // the activity is restored but onResume hasn't been called yet // so we do it now. initOnResume(); switch(id) { case DIALOG_RESET_CHOICES: return createDialogResetChoices(); case DIALOG_DELETE_PROFILE: return createDeleteProfileDialog(); case DIALOG_DELETE_ACTION: return createDialogDeleteTimedAction(); case DIALOG_CHECK_SERVICES: return createDialogCheckServices(); default: return null; } } private void onCheckServices() { String msg = getCheckServicesMessage(); if (DEBUG) Log.d(TAG, "Check Services: " + msg == null ? "null" : msg); if (msg.length() > 0 && mPrefsValues.getCheckService()) { mActivity.showDialog(DIALOG_CHECK_SERVICES); } } private String getCheckServicesMessage() { SettingFactory factory = SettingFactory.getInstance(); StringBuilder sb = new StringBuilder(); if (!factory.getSetting(Columns.ACTION_RING_VOLUME).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_audio_service)); } if (!factory.getSetting(Columns.ACTION_WIFI).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_wifi_service)); } if (!factory.getSetting(Columns.ACTION_AIRPLANE).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_airplane)); } if (!factory.getSetting(Columns.ACTION_BRIGHTNESS).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_brightness)); } // Bluetooth and APNDroid are not essential settings. We can't just bug the // user at start if they are missing (which is also highly probably, especially for // APNDroid). So here is not the right place to check for them. // // if (!factory.getSetting(Columns.ACTION_BLUETOOTH).isSupported(this)) { // sb.append("\n- ").append(getString(R.string.checkservices_miss_bluetooh)); // } // if (!factory.getSetting(Columns.ACTION_APN_DROID).isSupported(this)) { // sb.append("\n- ").append(getString(R.string.checkservices_miss_apndroid)); // } if (sb.length() > 0) { sb.insert(0, mActivity.getString(R.string.checkservices_warning)); } return sb.toString(); } private Dialog createDialogCheckServices() { Builder b = new AlertDialog.Builder(mActivity); b.setTitle(R.string.checkservices_dlg_title); b.setMessage(getCheckServicesMessage()); b.setPositiveButton(R.string.checkservices_ok_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_CHECK_SERVICES); } }); b.setNegativeButton(R.string.checkservices_skip_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mPrefsValues.setCheckService(false); mActivity.removeDialog(DIALOG_CHECK_SERVICES); } }); b.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_CHECK_SERVICES); } }); return b.create(); } public boolean onContextItemSelected(MenuItem item) { ContextMenuInfo info = item.getMenuInfo(); BaseHolder h = getHolder(info, null); if (h != null) { h.onContextMenuSelected(item); return true; } return false; } private BaseHolder getHolder(ContextMenuInfo menuInfo, View selectedView) { if (selectedView == null && menuInfo instanceof AdapterContextMenuInfo) { selectedView = ((AdapterContextMenuInfo) menuInfo).targetView; } Object tag = selectedView.getTag(); if (tag instanceof BaseHolder) { return (BaseHolder) tag; } Log.d(TAG, "Holder missing"); return null; } /** * Initializes the list-independent buttons: global toggle, check now. */ private void initButtons() { mGlobalToggle = (GlobalToggle) mActivity.findViewById(R.id.global_toggle); mGlobalStatus = (GlobalStatus) mActivity.findViewById(R.id.global_status); updateGlobalState(); mGlobalToggle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPrefsValues.setServiceEnabled(!mPrefsValues.isServiceEnabled()); updateGlobalState(); requestSettingsCheck(UpdateReceiver.TOAST_ALWAYS); } }); mGlobalStatus.setWindowVisibilityChangedCallback(new Runnable() { public void run() { updateGlobalState(); } }); } private void updateGlobalState() { boolean isEnabled = mPrefsValues.isServiceEnabled(); mGlobalToggle.setActive(isEnabled); mGlobalStatus.setTextLastTs(mPrefsValues.getStatusLastTS()); if (isEnabled) { mGlobalStatus.setTextNextTs(mPrefsValues.getStatusNextTS()); mGlobalStatus.setTextNextDesc(mPrefsValues.getStatusNextAction()); } else { mGlobalStatus.setTextNextTs(mActivity.getString(R.string.globalstatus_disabled)); mGlobalStatus.setTextNextDesc(mActivity.getString(R.string.help_to_enable)); } mGlobalStatus.invalidate(); } public void onCreateOptionsMenu(Menu menu) { menu.add(0, R.string.menu_append_profile, 0, R.string.menu_append_profile).setIcon(R.drawable.ic_menu_add); menu.add(0, R.string.menu_settings, 0, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences); menu.add(0, R.string.menu_about, 0, R.string.menu_about).setIcon(R.drawable.ic_menu_help); menu.add(0, R.string.menu_report_error, 0, R.string.menu_report_error).setIcon(R.drawable.ic_menu_report); menu.add(0, R.string.menu_check_now, 0, R.string.menu_check_now).setIcon(R.drawable.ic_menu_rotate); menu.add(0, R.string.menu_reset, 0, R.string.menu_reset).setIcon(R.drawable.ic_menu_revert); // TODO save to sd } public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.string.menu_settings: mAgentWrapper.event(AgentWrapper.Event.MenuSettings); showPrefs(); break; case R.string.menu_check_now: requestSettingsCheck(UpdateReceiver.TOAST_ALWAYS); break; case R.string.menu_about: mAgentWrapper.event(AgentWrapper.Event.MenuAbout); showIntro(true /*force*/, false /* checkService */); break; case R.string.menu_reset: mAgentWrapper.event(AgentWrapper.Event.MenuReset); showResetChoices(); break; // TODO save to sd case R.string.menu_append_profile: appendNewProfile(); break; case R.string.menu_report_error: showErrorReport(); break; default: return false; } return true; // handled } private void showPrefs() { mActivity.startActivityForResult(new Intent(mActivity, PrefsUI.class), SETTINGS_UPDATED); } private void showErrorReport() { mActivity.startActivity(new Intent(mActivity, ErrorReporterUI.class)); } /** * Requests a setting check. * * @param displayToast Must be one of {@link UpdateReceiver#TOAST_ALWAYS}, * {@link UpdateReceiver#TOAST_IF_CHANGED} or {@link UpdateReceiver#TOAST_NONE} */ private void requestSettingsCheck(int displayToast) { if (DEBUG) Log.d(TAG, "Request settings check"); Intent i = new Intent(UpdateReceiver.ACTION_UI_CHECK); i.putExtra(UpdateReceiver.EXTRA_TOAST_NEXT_EVENT, displayToast); mActivity.sendBroadcast(i); } protected void showResetChoices() { mActivity.showDialog(DIALOG_RESET_CHOICES); } // TODO save to sd private Dialog createDialogResetChoices() { Builder d = new AlertDialog.Builder(mActivity); d.setCancelable(true); d.setTitle(R.string.resetprofiles_msg_confirm_delete); d.setIcon(R.drawable.app_icon); d.setItems(mProfilesDb.getResetLabels(), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mProfilesDb.resetProfiles(which); mActivity.removeDialog(DIALOG_RESET_CHOICES); onDataChanged(true /*backup*/); requestSettingsCheck(UpdateReceiver.TOAST_IF_CHANGED); } }); d.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_RESET_CHOICES); } }); d.setNegativeButton(R.string.resetprofiles_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_RESET_CHOICES); } }); return d.create(); } //-------------- public void showTempDialog(long row_id, String title, int dlg_id) { mTempDialogRowId = row_id; mTempDialogTitle = title; mActivity.showDialog(dlg_id); } //-------------- private Dialog createDeleteProfileDialog() { final long row_id = mTempDialogRowId; final String title = mTempDialogTitle; Builder d = new AlertDialog.Builder(mActivity); d.setCancelable(true); d.setTitle(R.string.deleteprofile_title); d.setIcon(R.drawable.app_icon); d.setMessage(String.format( mActivity.getString(R.string.deleteprofile_msgbody), title)); d.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_DELETE_PROFILE); } }); d.setNegativeButton(R.string.deleteprofile_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_DELETE_PROFILE); } }); d.setPositiveButton(R.string.deleteprofile_button_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int count = mProfilesDb.deleteProfile(row_id); if (count > 0) { mAdapter.notifyDataSetChanged(); onDataChanged(true /*backup*/); } mActivity.removeDialog(DIALOG_DELETE_PROFILE); } }); return d.create(); } private Dialog createDialogDeleteTimedAction() { final long row_id = mTempDialogRowId; final String description = mTempDialogTitle; Builder d = new AlertDialog.Builder(mActivity); d.setCancelable(true); d.setTitle(R.string.deleteaction_title); d.setIcon(R.drawable.app_icon); d.setMessage(mActivity.getString(R.string.deleteaction_msgbody, description)); d.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_DELETE_ACTION); } }); d.setNegativeButton(R.string.deleteaction_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_DELETE_ACTION); } }); d.setPositiveButton(R.string.deleteaction_button_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int count = mProfilesDb.deleteAction(row_id); if (count > 0) { mAdapter.notifyDataSetChanged(); onDataChanged(true /*backup*/); } mActivity.removeDialog(DIALOG_DELETE_ACTION); } }); return d.create(); } public void appendNewProfile() { long prof_index = mProfilesDb.insertProfile(0, mActivity.getString(R.string.insertprofile_new_profile_title), true /*isEnabled*/); Intent intent = new Intent(mActivity, EditProfileUI.class); intent.putExtra(EditProfileUI.EXTRA_PROFILE_ID, prof_index << Columns.PROFILE_SHIFT); mActivity.startActivityForResult(intent, DATA_CHANGED); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; /** * A custom {@link CursorAdapter} that can provide the two views we * need: the profile header and the timed action entry. * <p/> * For each new view, the tag is set to either {@link ProfileHeaderHolder} * or {@link TimedActionHolder}, a subclass of {@link BaseHolder}. * <p/> * When a view is reused, it's tag is reused with a new cursor by using * {@link BaseHolder#setUiData}. This also updates the view * with the data from the cursor.. */ public class ProfileCursorAdapter extends CursorAdapter { /** View type is a profile header. */ private final static int TYPE_PROFILE = 0; /** View type is a timed action item. */ private final static int TYPE_TIMED_ACTION = 1; private final LayoutInflater mLayoutInflater; private final ColIndexes mColIndexes; private final ProfilesUiImpl mActivity; /** * Creates a new {@link ProfileCursorAdapter} for that cursor * and context. */ public ProfileCursorAdapter(ProfilesUiImpl activity, ColIndexes colIndexes, LayoutInflater layoutInflater) { super(activity.getActivity(), activity.getCursor()); mActivity = activity; mColIndexes = colIndexes; mLayoutInflater = layoutInflater; } /** * All items are always enabled in this view. */ @Override public boolean areAllItemsEnabled() { return true; } /** * All items are always enabled in this view. */ @Override public boolean isEnabled(int position) { return true; } /** * This adapter can serve 2 view types. */ @Override public int getViewTypeCount() { return 2; } /** * View types served are either {@link #TYPE_PROFILE} or * {@link #TYPE_TIMED_ACTION}. This is based on the value of * {@link Columns#TYPE} in the cursor. */ @Override public int getItemViewType(int position) { Cursor c = (Cursor) getItem(position); int type = c.getInt(mColIndexes.mTypeColIndex); if (type == Columns.TYPE_IS_PROFILE) return TYPE_PROFILE; if (type == Columns.TYPE_IS_TIMED_ACTION) return TYPE_TIMED_ACTION; return IGNORE_ITEM_VIEW_TYPE; } // --- /** * Depending on the value of {@link Columns#TYPE} in the cursor, * this inflates either a profile_header or a timed_action resource. * <p/> * It then associates the tag with a new {@link ProfileHeaderHolder} * or {@link TimedActionHolder} and initializes the holder using * {@link BaseHolder#setUiData}. * */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = null; BaseHolder h = null; int type = cursor.getInt(mColIndexes.mTypeColIndex); if (type == Columns.TYPE_IS_PROFILE) { v = mLayoutInflater.inflate(R.layout.profile_header, null); h = new ProfileHeaderHolder(mActivity, v); } else if (type == Columns.TYPE_IS_TIMED_ACTION) { v = mLayoutInflater.inflate(R.layout.timed_action, null); h = new TimedActionHolder(mActivity, v); } if (v != null) { v.setTag(h); h.setUiData(); } return v; } /** * To recycle a view, we just re-associate its tag using * {@link BaseHolder#setUiData}. */ @Override public void bindView(View view, Context context, Cursor cursor) { int type = cursor.getInt(mColIndexes.mTypeColIndex); if (type == Columns.TYPE_IS_PROFILE || type == Columns.TYPE_IS_TIMED_ACTION) { BaseHolder h = (BaseHolder) view.getTag(); h.setUiData(); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import java.io.File; import java.security.InvalidParameterException; import java.util.ArrayList; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteStatement; import android.util.Log; import android.widget.Toast; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.TimedActionUtils; //----------------------------------------------- /* * Debug Tip; to view content of database, use: * $ cd /cygdrive/c/.../android-sdk_..._windows/tools * $ ./adb shell 'echo ".dump" | sqlite3 data/data/com.rdrrlabs.example.timer1app/databases/profiles.db' */ /** * Helper to access the profiles database. * <p/> * The interface is similar to a {@link ContentProvider}, which should make it * easy to use only later. * <p/> * To be depreciated */ public class ProfilesDB { private static final boolean DEBUG = false; public static final String TAG = ProfilesDB.class.getSimpleName(); private static final String PROFILES_TABLE = "profiles"; private static final String DB_NAME = "profiles.db"; private static final int DB_VERSION = 1 * 100 + 1; // major*100 + minor private SQLiteDatabase mDb; private DatabaseHelper mDbHelper; private Context mContext; // ---------------------------------- /** Call this after creating this object. */ public boolean onCreate(Context context) { mContext = context; mDbHelper = new DatabaseHelper(context, DB_NAME, DB_VERSION); for (int i = 0; i < 10; i++) { try { mDb = mDbHelper.getWritableDatabase(); break; } catch (SQLiteException e) { Log.e(TAG, "DBHelper.getWritableDatabase", e); try { Thread.sleep(100 /*ms*/); } catch (InterruptedException e1) { // ignore } } } boolean created = mDb != null; return created; } /** Call this when the database is no longer needed. */ public void onDestroy() { mContext = null; if (mDbHelper != null) { for (int i = 0; i < 10; i++) { try { mDbHelper.close(); break; } catch (SQLiteException e) { Log.e(TAG, "DBHelper.close", e); try { Thread.sleep(100 /*ms*/); } catch (InterruptedException e1) { // ignore } } } mDbHelper = null; } } public static File getDatabaseFile(Context context) { return context.getDatabasePath(DB_NAME); } // ---------------------------------- /** * @see SQLiteDatabase#beginTransaction() */ public void beginTransaction() { mDb.beginTransaction(); } /** * @see SQLiteDatabase#setTransactionSuccessful() */ public void setTransactionSuccessful() { mDb.setTransactionSuccessful(); } /** * @see SQLiteDatabase#endTransaction() */ public void endTransaction() { mDb.endTransaction(); } // ---------------------------------- public long getProfileIdForRowId(long row_id) { SQLiteStatement sql = null; try { sql = mDb.compileStatement( String.format("SELECT %s FROM %s WHERE %s=%d;", Columns.PROFILE_ID, PROFILES_TABLE, Columns._ID, row_id)); return sql.simpleQueryForLong(); } catch (SQLiteDoneException e) { // no profiles return 0; } finally { if (sql != null) sql.close(); } } /** * Returns the max profile index (not id!). * * If maxProfileIndex == 0, returns the absolute max profile index, * i.e. the very last one. * If maxProfileIndex > 0, returns the max profile index that is smaller * than the given index (so basically the profile just before the one * given). * Returns 0 if there is no such index. */ public long getMaxProfileIndex(long maxProfileIndex) { SQLiteStatement sql = null; try { String testMaxProfId = ""; if (maxProfileIndex > 0) { testMaxProfId = String.format("AND %s<%d", Columns.PROFILE_ID, maxProfileIndex << Columns.PROFILE_SHIFT); } // e.g. SELECT MAX(prof_id) FROM profiles WHERE type=1 [ AND prof_id < 65536 ] sql = mDb.compileStatement( String.format("SELECT MAX(%s) FROM %s WHERE %s=%d %s;", Columns.PROFILE_ID, PROFILES_TABLE, Columns.TYPE, Columns.TYPE_IS_PROFILE, testMaxProfId)); return sql.simpleQueryForLong() >> Columns.PROFILE_SHIFT; } catch (SQLiteDoneException e) { // no profiles return 0; } finally { if (sql != null) sql.close(); } } /** * Returns the min action index (not id!) that is greater than the * requested minActionIndex. * <p/> * So for a given index (including 0), returns the next one used. * If there's no such index (i.e. not one used after the given index) * returns -1. */ public long getMinActionIndex(long profileIndex, long minActionIndex) { SQLiteStatement sql = null; try { long pid = (profileIndex << Columns.PROFILE_SHIFT) + minActionIndex; long maxPid = (profileIndex + 1) << Columns.PROFILE_SHIFT; // e.g. SELECT MIN(prof_id) FROM profiles WHERE type=2 AND prof_id > 32768+256 AND prof_id < 65536 sql = mDb.compileStatement( String.format("SELECT MIN(%s) FROM %s WHERE %s=%d AND %s>%d AND %s<%d;", Columns.PROFILE_ID, PROFILES_TABLE, Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, pid, Columns.PROFILE_ID, maxPid)); long result = sql.simpleQueryForLong(); if (result > pid && result < maxPid) return result & Columns.ACTION_MASK; } catch (SQLiteDoneException e) { // no actions } finally { if (sql != null) sql.close(); } return -1; } /** * Returns the max action index (not id!) for this profile. * Returns -1 if there are not actions. */ public long getMaxActionIndex(long profileIndex) { SQLiteStatement sql = null; try { long pid = (profileIndex << Columns.PROFILE_SHIFT); long maxPid = (profileIndex + 1) << Columns.PROFILE_SHIFT; // e.g. SELECT MAX(prof_id) FROM profiles WHERE type=2 AND prof_id > 32768 AND prof_id < 65536 sql = mDb.compileStatement( String.format("SELECT MAX(%s) FROM %s WHERE %s=%d AND %s>%d AND %s<%d;", Columns.PROFILE_ID, PROFILES_TABLE, Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, pid, Columns.PROFILE_ID, maxPid)); long result = sql.simpleQueryForLong(); if (result > pid && result < maxPid) return result & Columns.ACTION_MASK; } catch (SQLiteDoneException e) { // no actions } finally { if (sql != null) sql.close(); } return -1; } // ---------------------------------- /** * Inserts a new profile before the given profile index. * If beforeProfileIndex is <= 0, insert at the end. * * @return the profile index (not the row id) */ public long insertProfile(long beforeProfileIndex, String title, boolean isEnabled) { beginTransaction(); try { long index = getMaxProfileIndex(beforeProfileIndex); if (beforeProfileIndex <= 0) { long max = Long.MAX_VALUE >> Columns.PROFILE_SHIFT; if (index >= max - 1) { // TODO repack throw new UnsupportedOperationException("Profile index at maximum."); } else if (index < max - Columns.PROFILE_GAP) { index += Columns.PROFILE_GAP; } else { index += (max - index) / 2; } } else { if (index == beforeProfileIndex - 1) { // TODO repack throw new UnsupportedOperationException("No space left to insert profile before profile."); } else { index = (index + beforeProfileIndex) / 2; // get middle offset } } long id = index << Columns.PROFILE_SHIFT; ContentValues values = new ContentValues(2); values.put(Columns.PROFILE_ID, id); values.put(Columns.TYPE, Columns.TYPE_IS_PROFILE); values.put(Columns.DESCRIPTION, title); values.put(Columns.IS_ENABLED, isEnabled); id = mDb.insert(PROFILES_TABLE, Columns.TYPE, values); if (DEBUG) Log.d(TAG, String.format("Insert profile: %d => row %d", index, id)); if (id < 0) throw new SQLException("insert profile row failed"); setTransactionSuccessful(); return index; } finally { endTransaction(); } } /** * Inserts a new action for the given profile index. * If afterActionIndex is == 0, inserts at the beginning of these actions. * * NOTE: currently ignore afterActionIndex and always add at the end. * * @return the action index (not the row id) */ public long insertTimedAction(long profileIndex, long afterActionIndex, int hourMin, int days, String actions, long nextMs) { beginTransaction(); try { long pid = profileIndex << Columns.PROFILE_SHIFT; long maxIndex = getMaxActionIndex(profileIndex); if (maxIndex >= Columns.ACTION_MASK) { // Last index is used. Try to repack the action list. maxIndex = repackTimeActions(profileIndex); if (maxIndex == Columns.ACTION_MASK) { // definitely full... too bad. Toast.makeText(mContext, "No space left to insert action. Please delete some first.", Toast.LENGTH_LONG).show(); return -1; } } if (maxIndex < 0) { maxIndex = 0; } long index = maxIndex + 1; pid += index; String description = TimedActionUtils.computeDescription( mContext, hourMin, days, actions); ContentValues values = new ContentValues(2); values.put(Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION); values.put(Columns.PROFILE_ID, pid); values.put(Columns.DESCRIPTION, description); values.put(Columns.IS_ENABLED, 0); values.put(Columns.HOUR_MIN, hourMin); values.put(Columns.DAYS, days); values.put(Columns.ACTIONS, actions); values.put(Columns.NEXT_MS, nextMs); long id = mDb.insert(PROFILES_TABLE, Columns.TYPE, values); if (DEBUG) Log.d(TAG, String.format("Insert profile %d, action: %d => row %d", profileIndex, index, id)); if (id < 0) throw new SQLException("insert action row failed"); setTransactionSuccessful(); return index; } finally { endTransaction(); } } /** * Called by insertTimedAction within an existing transaction. * * Returns the new highest action index (not id) used. * Returns 0 if there were no actions. */ private long repackTimeActions(long profileIndex) { long pid = (profileIndex << Columns.PROFILE_SHIFT); long maxPid = (profileIndex + 1) << Columns.PROFILE_SHIFT; // Generates query with WHERE type=2 AND prof_id > 32768 AND prof_id < 65536 String where = String.format("%s=%d AND (%s>%d) AND (%s<%d)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, pid, Columns.PROFILE_ID, maxPid); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns.PROFILE_ID } , // columns where, // selection null, // selectionArgs null, // groupBy null, // having Columns.PROFILE_ID // orderBy ); int numActions = c.getCount(); if (DEBUG) Log.d(TAG, String.format("Repacking %d action", numActions)); if (numActions == 0 || numActions == Columns.ACTION_MASK) { // we know the table is empty or full, no need to repack. return numActions; } int colProfId = c.getColumnIndexOrThrow(Columns.PROFILE_ID); if (c.moveToFirst()) { int i = 1; do { long profId = c.getLong(colProfId); long newId = pid + (i++); if (profId != newId) { // generates update with WHERE type=2 AND prof_id=id where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, profId); ContentValues values = new ContentValues(1); values.put(Columns.PROFILE_ID, newId); mDb.update( PROFILES_TABLE, // table values, // values where, // whereClause null // whereArgs ); } } while (c.moveToNext()); } // new highest index is numActions return numActions; } finally { if (c != null) c.close(); } } // ---------------------------------- /** id is used if >= 0 */ public Cursor query(long id, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(PROFILES_TABLE); if (id >= 0) { qb.appendWhere(String.format("%s=%d", Columns._ID, id)); } if (sortOrder == null || sortOrder.length() == 0) sortOrder = Columns.DEFAULT_SORT_ORDER; Cursor c = qb.query(mDb, projection, selection, selectionArgs, null, // groupBy null, // having, sortOrder); return c; } // ---------------------------------- /** * @param name Profile name to update, if not null. * @param isEnabled Profile is enable flag to update. * @return Number of rows affected. 1 on success, 0 on failure. */ public int updateProfile(long prof_id, String name, boolean isEnabled) { String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_PROFILE, Columns.PROFILE_ID, prof_id); ContentValues cv = new ContentValues(); if (name != null) cv.put(Columns.DESCRIPTION, name); cv.put(Columns.IS_ENABLED, isEnabled); beginTransaction(); try { int count = mDb.update(PROFILES_TABLE, cv, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } /** * @param isEnabled Timed action is enable flag to update. * @return Number of rows affected. 1 on success, 0 on failure. */ public int updateTimedAction(long action_id, boolean isEnabled) { String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, action_id); ContentValues cv = new ContentValues(); cv.put(Columns.IS_ENABLED, isEnabled); beginTransaction(); try { int count = mDb.update(PROFILES_TABLE, cv, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } /** * @return Number of rows affected. 1 on success, 0 on failure. */ public int updateTimedAction(long action_id, int hourMin, int days, String actions, String description) { String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, action_id); ContentValues cv = new ContentValues(); cv.put(Columns.HOUR_MIN, hourMin); cv.put(Columns.DAYS, days); cv.put(Columns.ACTIONS, actions); if (description != null) cv.put(Columns.DESCRIPTION, description); beginTransaction(); try { int count = mDb.update(PROFILES_TABLE, cv, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } // ---------------------------------- /** * @param row_id The SQL row id, NOT the prof_id * @return The number of deleted rows, >= 1 on success, 0 on failure. */ public int deleteProfile(long row_id) { beginTransaction(); try { long pid = getProfileIdForRowId(row_id); if (pid == 0) throw new InvalidParameterException("No profile id for this row id."); pid = pid & (~Columns.ACTION_MASK); // DELETE FROM profiles WHERE prof_id >= 65536 AND prof_id < 65536+65535 String where = String.format("%s>=%d AND %s<%d", Columns.PROFILE_ID, pid, Columns.PROFILE_ID, pid + Columns.ACTION_MASK); int count = mDb.delete(PROFILES_TABLE, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } /** * @param row_id The SQL row id, NOT the prof_id * @return The number of deleted rows, 1 on success, 0 on failure. */ public int deleteAction(long row_id) { beginTransaction(); try { // DELETE FROM profiles WHERE TYPE=2 AND _id=65537 String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns._ID, row_id); int count = mDb.delete(PROFILES_TABLE, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } // ---------------------------------- /** Convenience helper to open/create/update the database */ private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context, String db_name, int version) { super(context, db_name, null /* cursor factory */, version); } @Override public void onCreate(SQLiteDatabase db) { SQLiteDatabase old_mDb = mDb; mDb = db; onResetTables(); initDefaultProfiles(); mDb = old_mDb; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, String.format("Upgrading database from version %1$d to %2$d.", oldVersion, newVersion)); db.execSQL("DROP TABLE IF EXISTS " + PROFILES_TABLE); onCreate(db); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); // pass } } /** * Called by {@link DatabaseHelper} to reset the tables. */ private void onResetTables() { // hand over that chocolate and nobody gets hurt! mDb.execSQL(String.format("DROP TABLE IF EXISTS %s;", PROFILES_TABLE)); mDb.execSQL(String.format("CREATE TABLE %s " + "(%s INTEGER PRIMARY KEY AUTOINCREMENT, " + "%s INTEGER, " + "%s TEXT, " + "%s INTEGER, " + "%s INTEGER, " + "%s INTEGER, " + "%s INTEGER, " + "%s TEXT, " + "%s INTEGER);" , PROFILES_TABLE, Columns._ID, Columns.TYPE, Columns.DESCRIPTION, Columns.IS_ENABLED, Columns.PROFILE_ID, Columns.HOUR_MIN, Columns.DAYS, Columns.ACTIONS, Columns.NEXT_MS)); } /** * Called by {@link DatabaseHelper} when the database has just been * created to initialize it with initial data. It's safe to use * {@link ProfilesDB#insertProfile} or {@link ProfilesDB#insertTimedAction} * at that point. */ private void initDefaultProfiles() { long pindex = insertProfile(0, "Weekdaze", true /*isEnabled*/); long action = insertTimedAction(pindex, 0, 7*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY, "RR,VV", //actions 0 //nextMs ); insertTimedAction(pindex, action, 20*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY, "RM,VV", //actions 0 //nextMs ); pindex = insertProfile(0, "Party Time", true /*isEnabled*/); action = insertTimedAction(pindex, 0, 9*60+0, //hourMin Columns.FRIDAY + Columns.SATURDAY, "RR", //actions 0 //nextMs ); insertTimedAction(pindex, action, 22*60+0, //hourMin Columns.FRIDAY + Columns.SATURDAY, "RM,VV", //actions 0 //nextMs ); pindex = insertProfile(0, "Sleeping-In", true /*isEnabled*/); action = insertTimedAction(pindex, 0, 10*60+30, //hourMin Columns.SUNDAY, "RR", //actions 0 //nextMs ); insertTimedAction(pindex, action, 21*60+0, //hourMin Columns.SUNDAY, "RM,VV", //actions 0 //nextMs ); } /** * Some simple profiles for me */ private void initRalfProfiles() { long pindex = insertProfile(0, "Ralf Week", true /*isEnabled*/); long action = insertTimedAction(pindex, 0, 9*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY + Columns.FRIDAY + Columns.SATURDAY + Columns.SUNDAY, "RR,VV,M75,Ba", //actions 0 //nextMs ); insertTimedAction(pindex, action, 21*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY + Columns.FRIDAY + Columns.SATURDAY + Columns.SUNDAY, "RM,VN,M0,B0,U0", //actions 0 //nextMs ); } // -------------- /** * Labels of the reset profiles choices. * Default is index 0. */ public String[] getResetLabels() { return new String[] { "Default Profiles", "Ralf Profiles", "Empty Profile", }; } /** * Reset profiles according to choices. * * @param labelIndex An index from the {@link #getResetLabels()} array. */ public void resetProfiles(int labelIndex) { if (DEBUG) Log.d(TAG, "Reset profiles: " + Integer.toString(labelIndex)); switch(labelIndex) { case 0: // default profiles beginTransaction(); try { // empty tables onResetTables(); initDefaultProfiles(); setTransactionSuccessful(); } finally { endTransaction(); } break; case 1: // ralf profiles beginTransaction(); try { // empty tables onResetTables(); initRalfProfiles(); setTransactionSuccessful(); } finally { endTransaction(); } break; case 2: // empty profile beginTransaction(); try { // empty tables onResetTables(); setTransactionSuccessful(); } finally { endTransaction(); } break; } } // -------------- public void removeAllActionExecFlags() { // generates WHERE type=2 (aka action) AND enable=1 String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.IS_ENABLED, 1); ContentValues values = new ContentValues(1); values.put(Columns.IS_ENABLED, false); beginTransaction(); try { mDb.update( PROFILES_TABLE, // table values, // values where, // whereClause null // whereArgs ); setTransactionSuccessful(); } finally { endTransaction(); } } /** * Returns the list of all profiles, dumped in a structure that is * mostly for debugging. It is not designed to be read back for restoring * although we could change it to be later. */ public String[] getProfilesDump() { Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table null, // *ALL* columns null, // selection null, // selectionArgs null, // groupBy null, // having null // orderBy ); int colType = c.getColumnIndexOrThrow(Columns.TYPE); int colDesc = c.getColumnIndexOrThrow(Columns.DESCRIPTION); int colIsEnabled = c.getColumnIndexOrThrow(Columns.IS_ENABLED); int colProfId = c.getColumnIndexOrThrow(Columns.PROFILE_ID); int colHourMin = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int colDays = c.getColumnIndexOrThrow(Columns.DAYS); int colActions = c.getColumnIndexOrThrow(Columns.ACTIONS); int colNextMs = c.getColumnIndexOrThrow(Columns.NEXT_MS); String[] summaries = new String[c.getCount()]; StringBuilder sb = new StringBuilder(); if (c.moveToFirst()) { int i = 0; do { String desc = c.getString(colDesc); String actions = c.getString(colActions); int enable = c.getInt(colIsEnabled); int type = c.getInt (colType); long profId = c.getLong(colProfId); int hourMin = c.getInt (colHourMin); int days = c.getInt (colDays); long nextMs = c.getLong(colNextMs); sb.setLength(0); if (type == Columns.TYPE_IS_TIMED_ACTION) { sb.append("- "); } // Format: { profile/action prof-index:action-index enable/active } sb.append(String.format("{ %1$s 0x%2$04x:%3$04x %4$s } ", type == Columns.TYPE_IS_PROFILE ? "P" : type == Columns.TYPE_IS_TIMED_ACTION ? "A" : Integer.toString(type), profId >> Columns.PROFILE_SHIFT, profId & Columns.ACTION_MASK, type == Columns.TYPE_IS_PROFILE ? (enable == 0 ? "D" : /*1*/ "E") : // profile: enable/disabled (enable == 0 ? "I" : // action: inactive/prev/next (enable == 1 ? "P" : /*2*/ "N")) )); // Description profile:user name, action: display summary sb.append(desc); if (type == Columns.TYPE_IS_TIMED_ACTION) { // Format: [ d:days-bitfield, hm:hour*60+min, a:actions/-, n:next MS ] sb.append(String.format(" [ d:%1$01x, hm:%2$04d, a:'%3$s', n:%d ]", days, hourMin, actions == null ? "-" : actions, nextMs )); } sb.append("\n"); summaries[i++] = sb.toString(); } while (c.moveToNext()); } return summaries; } finally { if (c != null) c.close(); } } /** * Returns the list of all enabled profiles. * This is a list of profiles indexes. * Can return an empty list, but not null. */ public long[] getEnabledProfiles() { // generates WHERE type=1 (aka profile) AND enable=1 String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_PROFILE, Columns.IS_ENABLED, 1); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns.PROFILE_ID }, // columns where, // selection null, // selectionArgs null, // groupBy null, // having null // orderBy ); int profIdColIndex = c.getColumnIndexOrThrow(Columns.PROFILE_ID); long[] indexes = new long[c.getCount()]; if (c.moveToFirst()) { int i = 0; do { indexes[i++] = c.getLong(profIdColIndex) >> Columns.PROFILE_SHIFT; } while (c.moveToNext()); } return indexes; } finally { if (c != null) c.close(); } } /** * Returns the list of timed actions that should be activated "now", * as defined by the given day and hour/minute and limited to the * given list of profiles. * <p/> * Returns a list of action prof_id (ids, not indexes) or null. * prof_indexes is a list of profile indexes (not ids) that are currently * enabled. * <p/> * Synopsis: * - If there are no profiles activated, abort. That is we support prof_ids * being an empty list. * - Selects actions which action_day & given_day != 0 (bitfield match) * - Selects all actions for that day, independently of the hourMin. * The hourMin check is done after on the result. * - Can return an empty list, but not null. */ public ActionInfo[] getDayActivableActions(int hourMin, int day, long[] prof_indexes) { if (prof_indexes.length < 1) return null; StringBuilder profList = new StringBuilder(); for (long prof_index : prof_indexes) { if (profList.length() > 0) profList.append(","); profList.append(Long.toString(prof_index)); } // generates WHERE type=2 (aka action) // AND hourMin <= targetHourMin // AND days & MASK != 0 // AND prof_id >> SHIFT IN (profList) String where = String.format("%s=%d AND (%s <= %d) AND (%s & %d) != 0 AND (%s >> %d) IN (%s)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.HOUR_MIN, hourMin, Columns.DAYS, day, Columns.PROFILE_ID, Columns.PROFILE_SHIFT, profList); // ORDER BY hourMin DESC String orderBy = String.format("%s DESC", Columns.HOUR_MIN); if (DEBUG) Log.d(TAG, "Get actions: WHERE " + where + " ORDER BY " + orderBy); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns._ID, Columns.HOUR_MIN, Columns.ACTIONS }, // columns where, // selection null, // selectionArgs null, // groupBy null, // having orderBy ); int rowIdColIndex = c.getColumnIndexOrThrow(Columns._ID); int hourMinColIndex = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int actionsColInfo = c.getColumnIndexOrThrow(Columns.ACTIONS); // Above we got the list of all actions for the requested day // that happen before the requested hourMin, in descending time // order, e.g. the most recent action is first in the list. // // We want to return the first action found. There might be more // than one action with the same time, so return them all. ArrayList<ActionInfo> infos = new ArrayList<ActionInfo>(); if (c.moveToFirst()) { int firstHourMin = c.getInt(hourMinColIndex); do { infos.add(new ActionInfo( c.getLong(rowIdColIndex), firstHourMin, // all actions have the same time c.getString(actionsColInfo))); if (DEBUG) Log.d(TAG, String.format("ActivableAction: day %d, hourMin %04d", day, firstHourMin)); } while (c.moveToNext() && c.getInt(hourMinColIndex) == firstHourMin); } return infos.toArray(new ActionInfo[infos.size()]); } finally { if (c != null) c.close(); } } /** * Invokes {@link #getDayActivableActions(int, int, long[])} for the current * day. If nothing is found, look at the 6 previous days to see if we can * find an action. */ public ActionInfo[] getWeekActivableActions(int hourMin, int day, long[] prof_indexes) { ActionInfo[] actions = null; // Look for the last enabled action for day. // If none was found, loop up to 6 days before and check the last // action before 24:00. for (int k = 0; k < 7; k++) { actions = getDayActivableActions(hourMin, day, prof_indexes); if (actions != null && actions.length > 0) { break; } // Switch to previous day and loop from monday to sunday as needed. day = day >> 1; if (day == 0) day = Columns.SUNDAY; // Look for anything "before the end of the day". Since we // want to match 23:59 we need to add one minute thus 24h00 // is our target. hourMin = 24*60 + 0; } return actions; } /** * Given a day and an hourMin time, try to find the first event that happens * after that timestamp. If nothing if found on the day, look up to 6 days * ahead. * * prof_indexes is a list of profile indexes (not ids) that are currently * enabled. * * @return The number of minutes from the given timestamp to the next event * or 0 if there's no such event ("now" is not a valid next event) */ public int getWeekNextEvent(int hourMin, int day, long[] prof_indexes, ActionInfo[] out_actions) { // First try to find something today that is past the requested time. ActionInfo found = getDayNextEvent(hourMin, day, prof_indexes); if (found != null) { out_actions[0] = found; int delta = found.mHourMin - hourMin; if (delta > 0) { return delta; } } // Otherwise look for the 6 days of events int minutes = 24*60 - hourMin; for(int k = 1; k < 7; k++, minutes += 24*60) { // Switch to next day. Loop from sunday back to monday. day = day << 1; if (day > Columns.SUNDAY) day = Columns.MONDAY; found = getDayNextEvent(-1 /*One minute before 00:00*/, day, prof_indexes); if (found != null) { out_actions[0] = found; return minutes + found.mHourMin; } } return 0; } /** * Given a day and an hourMin time, try to find the first event that happens * after that timestamp on the singular day. * * prof_indexes is a list of profile indexes (not ids) that are currently * enabled. * * @return The hourMin of the event found (hourMin..23:59) or -1 if nothing found. * If the return value is not -1, it is guaranteed to be greater than the * given hourMin since we look for an event *past* this time. */ private ActionInfo getDayNextEvent(int hourMin, int day, long[] prof_indexes) { if (prof_indexes.length < 1) return null; StringBuilder profList = new StringBuilder(); for (long prof_index : prof_indexes) { if (profList.length() > 0) profList.append(","); profList.append(Long.toString(prof_index)); } // generates WHERE type=2 (aka action) // AND hourMin > targetHourMin // AND days & MASK != 0 // AND prof_id >> SHIFT IN (profList) String hourTest; if (hourMin == -1) { hourTest = String.format("%s >= 0", Columns.HOUR_MIN); } else { hourTest = String.format("%s > (%d)", Columns.HOUR_MIN, hourMin); } String where = String.format("%s=%d AND (%s) AND (%s & %d) != 0 AND (%s >> %d) IN (%s)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, hourTest, Columns.DAYS, day, Columns.PROFILE_ID, Columns.PROFILE_SHIFT, profList); // ORDER BY hourMin ASC String orderBy = String.format("%s ASC", Columns.HOUR_MIN); // LIMIT 1 (we only want the first result) String limit = "1"; if (DEBUG) Log.d(TAG, "Get actions: WHERE " + where + " ORDER BY " + orderBy + " LIMIT " + limit); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns._ID, Columns.HOUR_MIN, Columns.ACTIONS }, // columns where, // selection null, // selectionArgs null, // groupBy null, // having orderBy, limit ); int rowIdColIndex = c.getColumnIndexOrThrow(Columns._ID); int hourMinColIndex = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int actionColIndex = c.getColumnIndexOrThrow(Columns.ACTIONS); if (c.moveToFirst()) { hourMin = c.getInt(hourMinColIndex); if (DEBUG) Log.d(TAG, String.format("NextEvent: day %d, hourMin %04d", day, hourMin)); return new ActionInfo( c.getLong(rowIdColIndex), hourMin, c.getString(actionColIndex)); } } finally { if (c != null) c.close(); } return null; } /** * Struct that describes a Timed Action returned by * {@link ProfilesDB#getDayActivableActions(int, int, long[])} */ public static class ActionInfo { public final long mRowId; private final int mHourMin; public final String mActions; public ActionInfo(long rowId, int hourMin, String actions) { mRowId = rowId; mHourMin = hourMin; mActions = actions; } @Override public String toString() { return String.format("Action<#.%d @%04d: %s>", mRowId, mActions); } } /** * Mark all the given actions as enabled for the given state. * Any previous actions with the given state are cleared. */ public void markActionsEnabled(ActionInfo[] actions, int state) { StringBuilder rowList = new StringBuilder(); for (ActionInfo info : actions) { if (rowList.length() > 0) rowList.append(","); rowList.append(Long.toString(info.mRowId)); } // generates WHERE type=2 (aka action) AND _id in (profList) String where_set = String.format("%s=%d AND %s IN (%s)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns._ID, rowList); ContentValues values_set = new ContentValues(1); values_set.put(Columns.IS_ENABLED, state); if (DEBUG) Log.d(TAG, "Mark actions: WHERE " + where_set); // generates WHERE type=2 (aka action) AND is_enabled == state String where_clear = String.format("%s=%d AND %s == %d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.IS_ENABLED, state); ContentValues values_clear = new ContentValues(1); values_clear.put(Columns.IS_ENABLED, Columns.ACTION_MARK_DEFAULT); beginTransaction(); try { // clear previous marks mDb.update( PROFILES_TABLE, // table values_clear, // values where_clear, // whereClause null // whereArgs ); // set new ones mDb.update( PROFILES_TABLE, // table values_set, // values where_set, // whereClause null // whereArgs ); setTransactionSuccessful(); } finally { endTransaction(); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import android.provider.BaseColumns; //----------------------------------------------- /** * Column names for the profiles/timed_actions table. */ public class Columns implements BaseColumns { /** The type of this row. * Enum: {@link #TYPE_IS_PROFILE} or {@link #TYPE_IS_TIMED_ACTION}. * <p/> * Note: 0 is not a valid value. Makes it easy to identify a non-initialized row. * <p/> * Type: INTEGER */ public static final String TYPE = "type"; /** type TYPE_IS_PROFILE: the row is a profile definition */ public static final int TYPE_IS_PROFILE = 1; /** type TYPE_IS_TIMED_ACTION: the row is a timed action definition */ public static final int TYPE_IS_TIMED_ACTION = 2; // --- fields common to both a profile definition and a timed action /** Description: * - Profile: user title. * - Time action: pre-computed summary description. * <p/> * Type: TEXT */ public static final String DESCRIPTION = "descrip"; /** Is Enabled: * - Profile: user-selected enabled toggle. * 0=disabled, 1=enabled * - Timed action: is executing (pre-computed value). * 0=default, 1=last, 2=next * <p/> * Type: INTEGER */ public static final String IS_ENABLED = "enable"; public static final int PROFILE_ENABLED = 0; public static final int PROFILE_DISABLED = 1; public static final int ACTION_MARK_DEFAULT = 0; public static final int ACTION_MARK_PREV = 1; public static final int ACTION_MARK_NEXT = 2; // --- fields for a profile definition // --- fields for a timed action /** Profile ID = profile_index << PROFILE_SHIFT + action_index. * <p/> * - Profile: The base number of the profile << {@link #PROFILE_SHIFT} * e.g. PROF << 16. * - Timed action: The profile's profile_id + index of the action, * e.g. PROF << 16 + INDEX_ACTION. * <p/> * Allocation rules: * - Profile's index start at 1, not 0. So first profile_id is 1<<16. * - Action index start at 1, so 1<<16+0 is a profile but 1<<16+1 is an action. * - Max 1<<16-1 actions per profile. * - On delete, don't compact numbers. * - On insert before or after, check if the number is available. * - On insert, if not available, need to move items to make space. * - To avoid having to move, leave gaps: * - Make initial first index at profile 256*capacity. * - When inserting at the end, leave a 256 gap between profiles or actions. * - When inserting between 2 existing entries, pick middle point. * <p/> * Type: INTEGER */ public static final String PROFILE_ID = "prof_id"; public static final int PROFILE_SHIFT = 16; public static final int ACTION_MASK = (1<<PROFILE_SHIFT)-1; public static final int PROFILE_GAP = 256; public static final int TIMED_ACTION_GAP = 256; /** Hour-Min Time, computed as hour*60+min in a day (from 0 to 23*60+59) * <p/> * Type: INTEGER */ public static final String HOUR_MIN = "hourMin"; /** Day(s) of the week. * This is a bitfield: {@link #MONDAY} thru {@link #SUNDAY} at * bit indexes {@link #MONDAY_BIT_INDEX} thru {@link #SUNDAY_BIT_INDEX}. * <p/> * Type: INTEGER */ public static final String DAYS = "days"; /** The first day of the bit field: monday is bit 0. */ public static final int MONDAY_BIT_INDEX = 0; /** The last day of the bit field: sunday is bit 6. */ public static final int SUNDAY_BIT_INDEX = 6; public static final int MONDAY = 1 << MONDAY_BIT_INDEX; public static final int TUESDAY = 1 << 1; public static final int WEDNESDAY = 1 << 2; public static final int THURSDAY = 1 << 3; public static final int FRIDAY = 1 << 4; public static final int SATURDAY = 1 << 5; public static final int SUNDAY = 1 << SUNDAY_BIT_INDEX; /** Actions to execute. * This is an encoded string: * - action letter * - digits for parameter (optional) * - comma (except for last). * Example: "M0,V1,R50" * <p/> * Type: STRING */ public static final String ACTIONS = "actions"; /** Ringer: R)ring, M)muted */ public static final char ACTION_RINGER = 'R'; /** Vibrate Ringer: V)ibrate, N)o vibrate all, R)no ringer vibrate, O)no notif vibrate */ public static final char ACTION_VIBRATE = 'V'; /** Ringer volume. Integer: 0..100 */ public static final char ACTION_RING_VOLUME = 'G'; /** Notification volume. Integer: 0..100 or 'r' for uses-ring-volume */ public static final char ACTION_NOTIF_VOLUME = 'N'; /** Media volume. Integer: 0..100 */ public static final char ACTION_MEDIA_VOLUME = 'M'; /** Alarm volume. Integer: 0..100 */ public static final char ACTION_ALARM_VOLUME = 'L'; /** System volume. Integer: 0..100 */ public static final char ACTION_SYSTEM_VOLUME = 'S'; /** Voice call volume. Integer: 0..100 */ public static final char ACTION_VOICE_CALL_VOLUME = 'C'; /** Screen Brightness. Integer: 0..100 or 'a' for automatic brightness */ public static final char ACTION_BRIGHTNESS = 'B'; /** Wifi. Boolean: 0..1 */ public static final char ACTION_WIFI = 'W'; /** AirplaneMode. Boolean: 0..1 */ public static final char ACTION_AIRPLANE = 'A'; /** Bluetooth. Boolean: 0..1 */ public static final char ACTION_BLUETOOTH = 'U'; /** APN Droid. Boolean: 0..1 */ public static final char ACTION_APN_DROID = 'D'; /** Data toggle. Boolean: 0..1 */ public static final char ACTION_DATA = 'd'; /** Sync. Boolean: 0..1 */ public static final char ACTION_SYNC = 'Y'; /** Special value for {@link #ACTION_BRIGHTNESS} to set it to automatic. */ public static final char ACTION_BRIGHTNESS_AUTO = 'a'; /** Special value for {@link #ACTION_NOTIF_VOLUME} to indicate it uses ring volume. */ public static final char ACTION_NOTIF_RING_VOL_SYNC = 'r'; /** * The precomputed System.currentTimeMillis timestamp of the next event for this action. * Type: INTEGER (long) */ public static final String NEXT_MS = "next_ms"; /** The default sort order for this table, _ID ASC */ public static final String DEFAULT_SORT_ORDER = PROFILE_ID + " ASC"; }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import android.database.Cursor; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; /** * The holder for a profile header row. */ public class ProfileHeaderHolder extends BaseHolder { private static boolean DEBUG = false; public static final String TAG = ProfileHeaderHolder.class.getSimpleName(); public ProfileHeaderHolder(ProfilesUiImpl activity, View view) { super(activity, view); } @Override public void setUiData() { ColIndexes colIndexes = mActivity.getColIndexes(); Cursor cursor = mActivity.getCursor(); super.setUiData(cursor.getString(colIndexes.mDescColIndex), cursor.getInt(colIndexes.mEnableColIndex) != 0 ? mActivity.getCheckOn() : mActivity.getCheckOff()); } @Override public void onCreateContextMenu(ContextMenu menu) { menu.setHeaderTitle(R.string.profilecontextmenu_title); menu.add(0, R.string.menu_insert_profile, 0, R.string.menu_insert_profile); menu.add(0, R.string.menu_insert_action, 0, R.string.menu_insert_action); menu.add(0, R.string.menu_delete, 0, R.string.menu_delete); menu.add(0, R.string.menu_rename, 0, R.string.menu_rename); } @Override public void onItemSelected() { Cursor cursor = mActivity.getCursor(); if (cursor == null) return; ColIndexes colIndexes = mActivity.getColIndexes(); boolean enabled = cursor.getInt(colIndexes.mEnableColIndex) != 0; enabled = !enabled; ProfilesDB profDb = mActivity.getProfilesDb(); profDb.updateProfile( cursor.getLong(colIndexes.mProfIdColIndex), null, // name enabled); // update ui cursor.requery(); setUiData(null, enabled ? mActivity.getCheckOn() : mActivity.getCheckOff()); } @Override public void onContextMenuSelected(MenuItem item) { switch (item.getItemId()) { case R.string.menu_insert_profile: if (DEBUG) Log.d(TAG, "profile - insert_profile"); insertNewProfile(mActivity.getCursor()); break; case R.string.menu_insert_action: if (DEBUG) Log.d(TAG, "profile - insert_action"); insertNewAction(mActivity.getCursor()); break; case R.string.menu_delete: if (DEBUG) Log.d(TAG, "profile - delete"); deleteProfile(mActivity.getCursor()); break; case R.string.menu_rename: if (DEBUG) Log.d(TAG, "profile - rename"); editProfile(mActivity.getCursor()); break; default: break; } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; import com.rdrrlabs.example.timer1app.app.TimerifficBackupAgent; import android.app.backup.BackupManager; import android.content.Context; import android.util.Log; /** * Wrapper around the {@link BackupManager} API, which is only available * starting with Froyo (Android API 8). * * The actual work is done in the class BackupWrapperImpl, which uses the * API methods, and thus will fail to load with a VerifyError exception * on older Android versions. The wrapper defers to the impl class if * it loaded, and otherwise just drops all the calls. */ public class BackupWrapper { public static final String TAG = BackupWrapper.class.getSimpleName(); private static final boolean DEBUG = true; private static Object[] sLock = new Object[0]; private final BackupWrapperImpl mImpl; public BackupWrapper(Context context) { BackupWrapperImpl b = null; try { // Try to load the actual implementation. This may fail. b = new BackupWrapperImpl(context); } catch (VerifyError e) { // No need to log an error, this is expected if API < 8. if (DEBUG) Log.w(TAG, "BackupWrapperImpl failed to load: VerifyError."); } catch (Throwable e) { // This is not expected. if (DEBUG) Log.e(TAG, "BackupWrapperImpl failed to load", e); } mImpl = b; } public void dataChanged() { if (mImpl != null) { mImpl.dataChanged(); if (DEBUG) Log.d(TAG, "Backup dataChanged"); } } /** * Returns the TAG for TimerifficBackupAgent if it loaded, or null. * @return */ public String getTAG_TimerifficBackupAgent() { if (mImpl != null) { mImpl.getTAG_TimerifficBackupAgent(); } return null; } /** * This lock must be used by all parties that want to manipulate * directly the files being backup/restored. This ensures that the * backup agent isn't trying to backup or restore whilst the other * party is modifying them directly. * <p/> * In our case, this MUST be used by the save/restore from SD operations. * <p/> * Implementation detail: since {@link TimerifficBackupAgent} depends * on the BackupAgent class, it is not available on platform < API 8. * This means any direct access to this class must be avoided. */ public static Object getBackupLock() { return sLock; } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; import com.rdrrlabs.example.timer1app.app.TimerifficBackupAgent; import android.app.backup.BackupManager; import android.content.Context; /** * Wrapper around the {@link BackupManager} API, only available with * Froyo (Android API level 8). * <p/> * This class should not be used directly. Instead, use {@link BackupWrapper} * which will delegate calls to this one if it can be loaded (that is if the * backup API is available.) */ /* package */ class BackupWrapperImpl { private BackupManager mManager; public BackupWrapperImpl(Context context) { mManager = new BackupManager(context); } public void dataChanged() { if (mManager != null) { mManager.dataChanged(); } } public String getTAG_TimerifficBackupAgent() { return TimerifficBackupAgent.TAG; } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; /** * Holder for app-wide encoded strings. */ public class CoreStrings { public enum Strings { ERR_UI_MAILTO, ERR_UI_DOMTO } CoreStrings() { } public String get(Strings code) { return "undefined"; } public String format(Strings code, Object...args) { return String.format(get(code), args); } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager.WakeLock; import android.util.Log; import android.widget.Toast; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.app.UpdateReceiver; import com.rdrrlabs.example.timer1app.app.UpdateService; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.utils.VolumeChange; public class UpdateServiceImpl { public static final String TAG = UpdateServiceImpl.class.getSimpleName(); private static final boolean DEBUG = true; private static final String EXTRA_RELEASE_WL = "releaseWL"; private static final String EXTRA_OLD_INTENT = "old_intent"; private static final String EXTRA_RETRY_ACTIONS = "retry_actions"; /** Failed Actions Notification ID. 'FaiL' as an int. */ private static final int FAILED_ACTION_NOTIF_ID = 'F' << 24 + 'a' << 16 + 'i' << 8 + 'L'; private WakeLock sWakeLock = null; /** * Starts the service from the {@link UpdateReceiver}. * This is invoked from the {@link UpdateReceiver} so code should be * at its minimum. No logging or DB access here. * * @param intent Original {@link UpdateReceiver}'s intent. *Could* be null. * @param wakeLock WakeLock created by {@link UpdateReceiver}. Could be null. */ public void startFromReceiver(Context context, Intent intent, WakeLock wakeLock) { Intent i = new Intent(context, UpdateService.class); if (intent != null) { i.putExtra(EXTRA_OLD_INTENT, intent); } if (wakeLock != null) { i.putExtra(EXTRA_RELEASE_WL, true); // if there's a current wake lock, release it first synchronized (UpdateServiceImpl.class) { WakeLock oldWL = sWakeLock; if (oldWL != wakeLock) { sWakeLock = wakeLock; if (oldWL != null) oldWL.release(); } } } context.startService(i); } public void createRetryNotification( Context context, PrefsValues prefs, String actions, String details) { if (DEBUG) Log.d(TAG, "create retry notif: " + actions); try { NotificationManager ns = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (ns == null) return; Intent i = new Intent(context, UpdateServiceImpl.class); i.putExtra(EXTRA_RETRY_ACTIONS, actions); PendingIntent pi = PendingIntent.getService( context, 0 /*requestCode*/, i, PendingIntent.FLAG_UPDATE_CURRENT); Notification notif = new Notification( R.drawable.app_icon, // icon "Timeriffic actions failed", // status bar tickerText System.currentTimeMillis() // when to show it ); notif.flags |= Notification.FLAG_AUTO_CANCEL; notif.defaults = Notification.DEFAULT_ALL; notif.setLatestEventInfo(context, "Timeriffic actions failed", // contentTitle "Click here to retry: " + details, // contentText pi // contentIntent ); ns.notify(FAILED_ACTION_NOTIF_ID, notif); } catch (Throwable t) { Log.e(TAG, "Notification crashed", t); ExceptionHandler.addToLog(prefs, t); } } //---- public void onStart(Context context, Intent intent, int startId) { try { String actions = intent.getStringExtra(EXTRA_RETRY_ACTIONS); if (actions != null) { retryActions(context, actions); return; } Intent i = intent.getParcelableExtra(EXTRA_OLD_INTENT); if (i == null) { // Not supposed to happen. String msg = "Missing old_intent in UpdateService.onStart"; PrefsValues prefs = new PrefsValues(context); ApplySettings as = new ApplySettings(context, prefs); as.addToDebugLog(msg); Log.e(TAG, msg); } else { applyUpdate(context, i); return; } } finally { if (intent.getBooleanExtra(EXTRA_RELEASE_WL, false)) { releaseWakeLock(); } } } public void onDestroy(Context context) { VolumeChange.unregisterVolumeReceiver(context); releaseWakeLock(); } // --- private void releaseWakeLock() { synchronized (UpdateServiceImpl.class) { WakeLock oldWL = sWakeLock; if (oldWL != null) { sWakeLock = null; oldWL.release(); } } } private void applyUpdate(Context context, Intent intent) { PrefsValues prefs = new PrefsValues(context); ApplySettings as = new ApplySettings(context, prefs); String action = intent.getAction(); int displayToast = intent.getIntExtra(UpdateReceiver.EXTRA_TOAST_NEXT_EVENT, UpdateReceiver.TOAST_NONE); boolean fromUI = UpdateReceiver.ACTION_UI_CHECK.equals(action); // We *only* apply settings if we recognize the action as being: // - Profiles UI > check now // - a previous alarm with Apply State // - boot completed // In all other cases (e.g. time/timezone changed), we'll recompute the // next alarm but we won't enforce settings. boolean applyState = fromUI || UpdateReceiver.ACTION_APPLY_STATE.equals(action) || Intent.ACTION_BOOT_COMPLETED.equals(action); // Log all actions except for "TIME_SET" which can happen too // frequently on some carriers and then pollutes the log. if (!Intent.ACTION_TIME_CHANGED.equals(action)) { String logAction = action.replace("android.intent.action.", ""); logAction = logAction.replace("com.rdrrlabs.intent.action.", ""); String debug = String.format("UpdateService %s%s", applyState ? "*Apply* " : "", logAction ); as.addToDebugLog(debug); Log.d(TAG, debug); } if (!prefs.isServiceEnabled()) { String debug = "Checking disabled"; as.addToDebugLog(debug); Log.d(TAG, debug); if (displayToast == UpdateReceiver.TOAST_ALWAYS) { showToast(context, prefs, R.string.globalstatus_disabled, Toast.LENGTH_LONG); } return; } as.apply(applyState, displayToast); } private void retryActions(Context context, String actions) { PrefsValues prefs = new PrefsValues(context); ApplySettings as = new ApplySettings(context, prefs); if (!prefs.isServiceEnabled()) { String debug = "[Retry] Checking disabled"; as.addToDebugLog(debug); Log.d(TAG, debug); // Since this comes from user intervention clicking on a // notifcation, it's OK to display a status via a toast UI. showToast(context, prefs, R.string.globalstatus_disabled, Toast.LENGTH_LONG); return; } as.retryActions(actions); } private void showToast(Context context, PrefsValues pv, int id, int duration) { try { Toast.makeText(context, id, duration).show(); } catch (Throwable t) { Log.e(TAG, "Toast.show crashed", t); ExceptionHandler.addToLog(pv, t); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; import java.util.Random; import android.content.Context; import com.rdrrlabs.example.timer1app.core.prefs.PrefsStorage; public class AppId { private static final int ID_LEN = 8; public static final String TAG = AppId.class.getSimpleName(); /** * Returns an id specific to this instance of the app. * The id is based on a random code generated once and stored in prefs. */ public static String getIssueId(Context context, PrefsStorage storage) { storage.endReadAsync(); String id = storage.getString("issue_id", null); if (id == null) { // Generate a new installation-specific ID. // We not longer use the device id from telephony. First // because it's not relevant for non-telephone devices and // second because there's just too many issues with it that // it's not even funny. See this blog post for the details: // http://android-developers.blogspot.com/2011/03/identifying-app-installations.html // Generate a random code with 8 unique symbols out of 34 // (0-9 + A-Z). We avoid letter O and I which look like 0 and 1. // We avoid repeating the same symbol twice in a row so // the number of combinations is n*(n-1)*(n-1)*..*(n-1) // or c = n * (n-1)^(k-1) // k=6, n=34 => c= 1,330,603,362 ... 1 million is a bit low. // k=8, n=34 => c=1,449,027,061,218 ... 1 trillion will do it. Random r = new Random(); char c[] = new char[ID_LEN]; // Mark O and I (the letters) as used, to avoid using them. int index_i = 10 + 'I' - 'A'; int index_o = 10 + 'O' - 'A'; for (int i = 0; i < c.length; i++) { int j = r.nextInt(10+26-2); if (j >= index_i) j++; if (j >= index_o) j++; if (j < 10) { c[i] = (char) ('0' + j); } else { c[i] = (char) ('A' + j - 10); } } id = new String(c); } if (id != null) { storage.putString("issue_id", id); storage.flushSync(context.getApplicationContext()); } return id; } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.util.Log; import android.util.SparseArray; import android.widget.Toast; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.app.TimerifficApp; import com.rdrrlabs.example.timer1app.app.UpdateReceiver; import com.rdrrlabs.example.timer1app.core.actions.TimedActionUtils; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB.ActionInfo; import com.rdrrlabs.example.timer1app.core.settings.ISetting; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper.RingerMode; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper.VibrateRingerMode; public class ApplySettings { private final static boolean DEBUG = true; public final static String TAG = ApplySettings.class.getSimpleName(); private final Context mContext; private final PrefsValues mPrefs; private final SimpleDateFormat mUiDateFormat; private final SimpleDateFormat mDebugDateFormat; public ApplySettings(Context context, PrefsValues prefs) { mContext = context; mPrefs = prefs; mDebugDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"); String format = null; SimpleDateFormat dt = null; try { format = context.getString(R.string.globalstatus_nextlast_date_time); dt = new SimpleDateFormat(format); } catch (Exception e) { Log.e(TAG, "Invalid R.string.globalstatus_nextlast_date_time: " + (format == null ? "null" : format)); } mUiDateFormat = dt == null ? mDebugDateFormat : dt; } private void showToast(String s, int duration) { try { Toast.makeText(mContext, s, duration).show(); } catch (Throwable t) { ExceptionHandler.addToLog(mPrefs, t); Log.w(TAG, "Toast.show crashed", t); } } public void apply(boolean applyState, int displayToast) { if (DEBUG) Log.d(TAG, "Checking enabled"); checkProfiles(applyState, displayToast); notifyDataChanged(); } public void retryActions(String actions) { if (DEBUG) Log.d(TAG, "Retry actions: " + actions); SettingsHelper settings = new SettingsHelper(mContext); if (performAction(settings, actions, null /*failedActions*/)) { showToast("Timeriffic retried the actions", Toast.LENGTH_LONG); if (DEBUG) Log.d(TAG, "Retry succeed"); } else { showToast("Timeriffic found no action to retry", Toast.LENGTH_LONG); if (DEBUG) Log.d(TAG, "Retry no-op"); } } private void checkProfiles(boolean applyState, int displayToast) { ProfilesDB profilesDb = new ProfilesDB(); try { profilesDb.onCreate(mContext); profilesDb.removeAllActionExecFlags(); // Only do something if at least one profile is enabled. long[] prof_indexes = profilesDb.getEnabledProfiles(); if (prof_indexes != null && prof_indexes.length != 0) { Calendar c = new GregorianCalendar(); c.setTimeInMillis(System.currentTimeMillis()); int hourMin = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); int day = TimedActionUtils.calendarDayToActionDay(c); if (applyState) { ActionInfo[] actions = profilesDb.getWeekActivableActions(hourMin, day, prof_indexes); if (actions != null && actions.length > 0) { performActions(actions); profilesDb.markActionsEnabled(actions, Columns.ACTION_MARK_PREV); } } // Compute next event and set an alarm for it ActionInfo[] nextActions = new ActionInfo[] { null }; int nextEventMin = profilesDb.getWeekNextEvent(hourMin, day, prof_indexes, nextActions); if (nextEventMin > 0) { scheduleAlarm(c, nextEventMin, nextActions[0], displayToast); if (applyState) { profilesDb.markActionsEnabled(nextActions, Columns.ACTION_MARK_NEXT); } } } } catch (Exception e) { Log.e(TAG, "checkProfiles failed", e); ExceptionHandler.addToLog(mPrefs, e); } finally { profilesDb.onDestroy(); } } private void performActions(ActionInfo[] actions) { String logActions = null; String lastAction = null; SettingsHelper settings = null; SparseArray<String> failedActions = new SparseArray<String>(); for (ActionInfo info : actions) { try { if (settings == null) settings = new SettingsHelper(mContext); if (performAction(settings, info.mActions, failedActions)) { lastAction = info.mActions; if (logActions == null) { logActions = lastAction; } else { logActions += " | " + lastAction; } } } catch (Exception e) { Log.w(TAG, "Failed to apply setting", e); ExceptionHandler.addToLog(mPrefs, e); } } if (lastAction != null) { // Format the timestamp of the last action to be "now" String time = mUiDateFormat.format(new Date(System.currentTimeMillis())); // Format the action description String a = TimedActionUtils.computeLabels(mContext, lastAction); synchronized (mPrefs.editLock()) { Editor e = mPrefs.startEdit(); try { mPrefs.editStatusLastTS(e, time); mPrefs.editStatusNextAction(e, a); } finally { mPrefs.endEdit(e, TAG); } } addToDebugLog(logActions); } if (failedActions.size() > 0) { notifyFailedActions(failedActions); } } private boolean performAction( SettingsHelper settings, String actions, SparseArray<String> failedActions) { if (actions == null) return false; boolean didSomething = false; RingerMode ringerMode = null; VibrateRingerMode vibRingerMode = null; for (String action : actions.split(",")) { if (action.length() > 1) { char code = action.charAt(0); char v = action.charAt(1); switch(code) { case Columns.ACTION_RINGER: for (RingerMode mode : RingerMode.values()) { if (mode.getActionLetter() == v) { ringerMode = mode; break; } } break; case Columns.ACTION_VIBRATE: for (VibrateRingerMode mode : VibrateRingerMode.values()) { if (mode.getActionLetter() == v) { vibRingerMode = mode; break; } } break; default: ISetting s = SettingFactory.getInstance().getSetting(code); if (s != null && s.isSupported(mContext)) { if (!s.performAction(mContext, action)) { // Record failed action if (failedActions != null) { failedActions.put(code, action); } } else { didSomething = true; } } break; } } } if (ringerMode != null || vibRingerMode != null) { didSomething = true; settings.changeRingerVibrate(ringerMode, vibRingerMode); } return didSomething; } /** Notify UI to update */ private void notifyDataChanged() { TimerifficApp app = TimerifficApp.getInstance(mContext); if (app != null) { app.invokeDataListener(); } } /** * Schedule an alarm to happen at nextEventMin minutes from now. * * @param now The time that was used at the beginning of the update. * @param nextEventMin The number of minutes ( > 0) after "now" where to set the alarm. * @param nextActions * @param displayToast One of {@link UpdateReceiver#TOAST_NONE}, * {@link UpdateReceiver#TOAST_IF_CHANGED} or {@link UpdateReceiver#TOAST_ALWAYS} */ private void scheduleAlarm( Calendar now, int nextEventMin, ActionInfo nextActions, int displayToast) { AlarmManager manager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(mContext, UpdateReceiver.class); intent.setAction(UpdateReceiver.ACTION_APPLY_STATE); PendingIntent op = PendingIntent.getBroadcast( mContext, 0 /*requestCode*/, intent, PendingIntent.FLAG_UPDATE_CURRENT); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); now.add(Calendar.MINUTE, nextEventMin); long timeMs = now.getTimeInMillis(); manager.set(AlarmManager.RTC_WAKEUP, timeMs, op); boolean shouldDisplayToast = displayToast != UpdateReceiver.TOAST_NONE; if (displayToast == UpdateReceiver.TOAST_IF_CHANGED) { shouldDisplayToast = timeMs != mPrefs.getLastScheduledAlarm(); } SimpleDateFormat sdf = null; String format = null; try { format = mContext.getString(R.string.toast_next_alarm_date_time); sdf = new SimpleDateFormat(format); } catch (Exception e) { Log.e(TAG, "Invalid R.string.toast_next_alarm_date_time: " + (format == null ? "null" : format)); } if (sdf == null) sdf = mDebugDateFormat; sdf.setCalendar(now); String s2 = sdf.format(now.getTime()); synchronized (mPrefs.editLock()) { Editor e = mPrefs.startEdit(); try { mPrefs.editLastScheduledAlarm(e, timeMs); mPrefs.editStatusNextTS(e, s2); mPrefs.editStatusNextAction(e, TimedActionUtils.computeLabels(mContext, nextActions.mActions)); } finally { mPrefs.endEdit(e, TAG); } } s2 = mContext.getString(R.string.toast_next_change_at_datetime, s2); if (shouldDisplayToast) showToast(s2, Toast.LENGTH_LONG); if (DEBUG) Log.d(TAG, s2); addToDebugLog(s2); } protected static final String SEP_START = " [ "; protected static final String SEP_END = " ]\n"; /** Add debug log for now. */ public /* package */ void addToDebugLog(String message) { String time = mDebugDateFormat.format(new Date(System.currentTimeMillis())); addToDebugLog(time, message); } /** Add time:action specific log. */ protected synchronized void addToDebugLog(String time, String logActions) { logActions = time + SEP_START + logActions + SEP_END; int len = logActions.length(); // We try to keep only 4k in the buffer int max = 4096; String a = null; if (logActions.length() < max) { a = mPrefs.getLastActions(); if (a != null) { int lena = a.length(); if (lena + len > max) { int extra = lena + len - max; int pos = -1; int p = -1; do { pos = a.indexOf(SEP_END, pos + 1); p = pos + SEP_END.length(); } while (pos >= 0 && p < extra); if (pos < 0 || p >= lena) { a = null; } else { a = a.substring(p); } } } } if (a == null) { mPrefs.setLastActions(logActions); } else { a += logActions; mPrefs.setLastActions(a); } } public static synchronized int getNumActionsInLog(Context context) { try { PrefsValues pv = new PrefsValues(context); String curr = pv.getLastActions(); if (curr == null) { return 0; } int count = -1; int pos = -1; do { count++; pos = curr.indexOf(" ]", pos + 1); } while (pos >= 0); return count; } catch (Exception e) { Log.w(TAG, "getNumActionsInLog failed", e); ExceptionHandler.addToLog(new PrefsValues(context), e); } return 0; } /** * Send a notification indicating the given actions have failed. */ private void notifyFailedActions(SparseArray<String> failedActions) { StringBuilder sb = new StringBuilder(); for (int n = failedActions.size(), i = 0; i < n; i++) { if (i > 0) sb.append(','); sb.append(failedActions.valueAt(i)); } String actions = sb.toString(); String details = TimedActionUtils.computeLabels(mContext, actions); Core core = TimerifficApp.getInstance(mContext).getCore(); core.getUpdateService().createRetryNotification(mContext, mPrefs, actions, details); } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.app; /** * Holder for app-wide implementation-specific instances. * <p/> * Think of it has the kind of global instances one would typically * define using dependency injection. Tests could override this, etc. */ public class Core { protected UpdateServiceImpl mUpdateServiceImpl; protected CoreStrings mCoreStrings; /** Base constructor with defaults. */ public Core() { mUpdateServiceImpl = new UpdateServiceImpl(); mCoreStrings = new CoreStrings(); } /** Derived constructor with overrides. */ public Core(CoreStrings strings) { mUpdateServiceImpl = new UpdateServiceImpl(); mCoreStrings = strings; } public UpdateServiceImpl getUpdateService() { return mUpdateServiceImpl; } public CoreStrings getCoreStrings() { return mCoreStrings; } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.actions; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import android.content.Context; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.core.settings.ISetting; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper.RingerMode; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper.VibrateRingerMode; public class TimedActionUtils { static private final int[] CALENDAR_DAYS = { Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, Calendar.SUNDAY }; static private final String[] DAYS_NAMES_EN = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; static protected String[] sDaysNames = null; static public int calendarDayToActionDay(Calendar c) { int day = c.get(Calendar.DAY_OF_WEEK); for (int i = Columns.MONDAY_BIT_INDEX; i <= Columns.SUNDAY_BIT_INDEX; i++) { if (day == CALENDAR_DAYS[i]) { day = 1<<i; break; } } return day; } static public String computeDescription(Context context, int hourMin, int days, String actions) { String desc_time = computeTime(context, hourMin); String desc_days = computeDays(context, days); String desc_actions = computeLabels(context, actions); String description = String.format("%s %s, %s", desc_time, desc_days, desc_actions); return description; } private static String computeTime(Context context, int hourMin) { Calendar c = new GregorianCalendar(); c.setTimeInMillis(System.currentTimeMillis()); c.set(Calendar.HOUR_OF_DAY, hourMin / 60); int min = hourMin % 60; c.set(Calendar.MINUTE, min); String desc_time = null; if (min != 0) { desc_time = context.getString(R.string.timedaction_time_with_minutes, c); } else { desc_time = context.getString(R.string.timedaction_time_0_minute, c); } return desc_time; } static public String[] getDaysNames() { if (sDaysNames != null) return sDaysNames; sDaysNames = new String[CALENDAR_DAYS.length]; Calendar loc = new GregorianCalendar(Locale.getDefault()); loc.setTimeInMillis(System.currentTimeMillis()); for (int i = 0; i < CALENDAR_DAYS.length; i++) { loc.set(Calendar.DAY_OF_WEEK, CALENDAR_DAYS[i]); String s = String.format("%ta", loc); // In Android 1.5, "%ta" doesn't seem to work properly so // we just hardcode them. if (s == null || s.length() == 0 || s.matches("[0-9]")) { s = DAYS_NAMES_EN[i]; } sDaysNames[i] = s; } return sDaysNames; } static private String computeDays(Context context, int days) { int start = -2; int count = 0; StringBuilder desc_days = new StringBuilder(); String[] dayNames = getDaysNames(); for (int i = Columns.MONDAY_BIT_INDEX; i <= Columns.SUNDAY_BIT_INDEX; i++) { if ((days & (1<<i)) != 0 ) { if (start == i-1) { // continue range start = i; count++; } else { // start new range if (desc_days.length() > 0) desc_days.append(", "); desc_days.append(dayNames[i]); start = i; count = 0; } } else { if (start >= 0 && count > 0) { // close range desc_days.append(" - "); desc_days.append(dayNames[start]); } start = -2; count = 0; } } if (start >= 0 && count > 0) { // close range desc_days.append(" - "); desc_days.append(dayNames[start]); } if (desc_days.length() == 0) { desc_days.append(context.getString(R.string.timedaction_nodays_never)); } return desc_days.toString(); } static public String computeLabels(Context context, String actions) { ArrayList<String> actions_labels = new ArrayList<String>(); if (actions != null) { for (String action : actions.split(",")) { if (action.length() > 1) { char code = action.charAt(0); char v = action.charAt(1); switch(code) { case Columns.ACTION_RINGER: for (RingerMode mode : RingerMode.values()) { if (mode.getActionLetter() == v) { actions_labels.add(mode.toUiString(context)); // ringer name break; } } break; case Columns.ACTION_VIBRATE: for (VibrateRingerMode mode : VibrateRingerMode.values()) { if (mode.getActionLetter() == v) { actions_labels.add(mode.toUiString(context)); // vibrate name break; } } break; default: ISetting s = SettingFactory.getInstance().getSetting(code); if (s != null && s.isSupported(context)) { String label = s.getActionLabel(context, action); if (label != null) { actions_labels.add(label); } } break; } } } } StringBuilder desc_actions = new StringBuilder(); if (actions_labels.size() == 0) { desc_actions.append(context.getString(R.string.timedaction_no_action)); } else { for (String name : actions_labels) { if (desc_actions.length() > 0) desc_actions.append(", "); desc_actions.append(name); } } return desc_actions.toString(); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.actions; import android.app.Activity; import com.rdrrlabs.example.timer1app.base.R; //----------------------------------------------- public class PrefToggle extends PrefEnum { public PrefToggle(Activity activity, int buttonResId, String[] actions, char actionPrefix, String menuTitle) { super(activity, buttonResId, null /*values*/, actions, actionPrefix, menuTitle, null /*uiStrings*/); } /** * Special constructor that lets the caller override the on/off strings. * uiStrings[0]==on string, uiStrings[1]==off string. */ public PrefToggle(Activity activity, int buttonResId, String[] actions, char actionPrefix, String menuTitle, String[] uiStrings) { super(activity, buttonResId, null /*values*/, actions, actionPrefix, menuTitle, uiStrings); } @Override protected void initChoices(Object[] values, String[] actions, char prefix, String[] uiStrings) { String on = getActivity().getResources().getString(R.string.toggle_turn_on); String off = getActivity().getResources().getString(R.string.toggle_turn_off); if (uiStrings != null && uiStrings.length >= 2) { on = uiStrings[0]; off = uiStrings[1]; } Choice c1 = new Choice( '1', on, ID_DOT_STATE_ON); Choice c0 = new Choice( '0', off, ID_DOT_STATE_OFF); mChoices.add(c1); mChoices.add(c0); String currentValue = getActionValue(actions, prefix); if ("1".equals(currentValue)) { mCurrentChoice = c1; } else if ("0".equals(currentValue)) { mCurrentChoice = c0; } } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.actions; import com.rdrrlabs.example.timer1app.base.R; import android.app.Activity; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ViewParent; import android.widget.Button; //----------------------------------------------- public abstract class PrefBase { public static final String TAG = PrefBase.class.getSimpleName(); private final Activity mActivity; protected final static int ID_DOT_UNCHANGED = R.drawable.dot_gray; protected final static int ID_DOT_STATE_ON = R.drawable.dot_green; protected final static int ID_DOT_STATE_OFF = R.drawable.dot_red; protected final static int ID_DOT_PERCENT = R.drawable.dot_purple; protected final static int ID_DOT_EXTRA = R.drawable.dot_purple; public PrefBase(Activity activity) { mActivity = activity; } public Activity getActivity() { return mActivity; } protected String getActionValue(String[] actions, char prefix) { if (actions == null) return null; for (String action : actions) { if (action.length() > 1 && action.charAt(0) == prefix) { return action.substring(1); } } return null; } protected void appendAction(StringBuilder actions, char prefix, String value) { if (actions.length() > 0) actions.append(","); actions.append(prefix); actions.append(value); } public abstract void setEnabled(boolean enable, String disabledMessage); public abstract boolean isEnabled(); public abstract void requestFocus(); public abstract void onCreateContextMenu(ContextMenu menu); public abstract void onContextItemSelected(MenuItem item); // --- private final static int[] sExtraButtonsResId = { R.id.button0, R.id.button1, R.id.button2, R.id.button3, }; public Button findButtonById(int buttonResId) { if (buttonResId == -1) { // This is a dynamically allocated button. // Use the first one that is free. for (int id : sExtraButtonsResId) { Button b = (Button) getActivity().findViewById(id); if (b != null && b.getTag() == null) { b.setTag(this); b.setEnabled(true); b.setVisibility(View.VISIBLE); ViewParent p = b.getParent(); if (p instanceof View) { ((View) p).setVisibility(View.VISIBLE); } return b; } } Log.e(TAG, "No free button slot for " + this.getClass().getSimpleName()); throw new RuntimeException("No free button slot for " + this.getClass().getSimpleName()); } return (Button) getActivity().findViewById(buttonResId); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.actions; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.View; import android.widget.RadioButton; import android.widget.SeekBar; import com.rdrrlabs.example.timer1app.base.R; public class PrefPercentDialog extends AlertDialog implements DialogInterface.OnDismissListener, DialogInterface.OnClickListener, SeekBar.OnSeekBarChangeListener, View.OnClickListener { private final int mInitialValue; private final PrefPercent mPrefPercent; private SeekBar mSeekBar; private Accessor mAccessor; private RadioButton mRadioNoChange; private RadioButton mRadioChange; private RadioButton mRadioCustomChoice; private String mRadioChangeText; /** Callback to communicate back with client */ public interface Accessor { /** Returns actual percentage value for this pref. */ public int getPercent(); /** Live change to given value when user is dragging the seek bar. */ public void changePercent(int percent); /** Indicates whether this pref needs a custom choice. * Returns <=0 to remove the custom choice, otherwise return the resource id * of the string to display. */ public int getCustomChoiceLabel(); /** Returns the text used on the action UI when the custom choice has been used. * Should be shorter than the radio button text returned by * {@link #getCustomChoiceLabel()}. */ public int getCustomChoiceButtonLabel(); /** Returns the internal value to use for the custom choice (appended to the prefix). * This has nothing to do with the actually setting value. * Returns 0 if there's no custom choice. */ public char getCustomChoiceValue(); } public PrefPercentDialog(Context context, PrefPercent prefPercent) { super(context); mPrefPercent = prefPercent; if (mPrefPercent.getIconResId() != 0) setIcon(mPrefPercent.getIconResId()); if (mPrefPercent.getDialogTitle() != null) setTitle(mPrefPercent.getDialogTitle()); View content = getLayoutInflater().inflate(R.layout.percent_alert, null/* root */); setView(content); mAccessor = mPrefPercent.getAccessor(); mInitialValue = mAccessor == null ? -1 : mAccessor.getPercent(); mRadioNoChange = (RadioButton) content.findViewById(R.id.radio_nochange); mRadioNoChange.setOnClickListener(this); mRadioChange = (RadioButton) content.findViewById(R.id.radio_change); mRadioChange.setOnClickListener(this); mRadioCustomChoice = (RadioButton) content.findViewById(R.id.custom_choice); int strId = mAccessor.getCustomChoiceLabel(); if (strId <= 0) { mRadioCustomChoice.setEnabled(false); mRadioCustomChoice.setVisibility(View.GONE); mRadioCustomChoice = null; } else { mRadioCustomChoice.setText(strId); mRadioCustomChoice.setOnClickListener(this); } mSeekBar = (SeekBar) content.findViewById(R.id.seekbar); mSeekBar.setOnSeekBarChangeListener(this); mSeekBar.setMax(100); setOnDismissListener(this); setButton(context.getResources().getString(R.string.percent_button_accept), this); // set initial value int percent = mPrefPercent.getCurrentValue(); if (percent >= 0) { if (mAccessor != null) mAccessor.changePercent(percent); mRadioChange.setChecked(true); mRadioNoChange.setChecked(false); mSeekBar.setProgress(percent); mSeekBar.setEnabled(true); } else if (mRadioCustomChoice != null && percent == PrefPercent.VALUE_CUSTOM_CHOICE) { mRadioCustomChoice.setChecked(true); mRadioChange.setChecked(false); mRadioNoChange.setChecked(false); mSeekBar.setEnabled(false); } else { // Default is PrefPercent.VALUE_UNCHANGED mRadioChange.setChecked(false); mRadioNoChange.setChecked(true); mSeekBar.setProgress(mInitialValue); mSeekBar.setEnabled(false); } updatePercentLabel(-1); } private void updatePercentLabel(int percent) { if (percent < 0) percent = mSeekBar.getProgress(); if (mRadioChangeText == null) { mRadioChangeText = mRadioChange.getText().toString(); if (mRadioChangeText == null) mRadioChangeText = ":"; if (!mRadioChangeText.trim().endsWith(":")) mRadioChangeText += ":"; } mRadioChange.setText(String.format("%s %3d%% ", mRadioChangeText, percent)); } public void onDismiss(DialogInterface dialog) { if (mAccessor != null) mAccessor.changePercent(mInitialValue); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { if (fromTouch) { progress = roundup(progress); mSeekBar.setProgress(progress); updatePercentLabel(progress); if (mAccessor != null) mAccessor.changePercent(progress); } } /** * If progress is > 10%, round up to nearest 5%, otherwise use 1%. */ private int roundup(int progress) { if (progress > 10) { progress -= 10; progress = 10 + (int) (5.0 * Math.round(((double) progress) / 5.0)); } return progress; } public void onStartTrackingTouch(SeekBar seekBar) { // pass } public void onStopTrackingTouch(SeekBar seekBar) { // pass } /** DialogInterface.OnClickListener callback, when dialog is accepted */ public void onClick(DialogInterface dialog, int which) { // Update button with percentage selected if (mRadioChange.isChecked()) { mPrefPercent.setValue(mSeekBar.getProgress()); } else if (mRadioCustomChoice != null && mRadioCustomChoice.isChecked()) { mPrefPercent.setValue(PrefPercent.VALUE_CUSTOM_CHOICE); } else { mPrefPercent.setValue(PrefPercent.VALUE_UNCHANGED); } dismiss(); } public void onClick(View toggle) { mSeekBar.setEnabled(mRadioChange.isChecked()); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.actions; import java.util.ArrayList; import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper.RingerMode; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper.VibrateRingerMode; //----------------------------------------------- public class PrefEnum extends PrefBase implements View.OnClickListener { protected static final char UNCHANGED_KEY = '-'; private final char mActionPrefix; protected static class Choice { public final char mKey; public final String mUiName; public final int mDotColor; public Choice(char key, String uiName, int dot_color) { mKey = key; mUiName = uiName; mDotColor = dot_color; } } protected ArrayList<Choice> mChoices = new ArrayList<Choice>(); protected Choice mCurrentChoice; private Button mButton; private final String mMenuTitle; private String mDisabledMessage; public PrefEnum(Activity activity, int buttonResId, Object[] values, String[] actions, char actionPrefix, String menuTitle) { this(activity, buttonResId, values, actions, actionPrefix, menuTitle, null /*uiStrings*/ ); } public PrefEnum(Activity activity, int buttonResId, Object[] values, String[] actions, char actionPrefix, String menuTitle, String[] uiStrings) { super(activity); mActionPrefix = actionPrefix; mMenuTitle = menuTitle; mButton = findButtonById(buttonResId); getActivity().registerForContextMenu(mButton); mButton.setOnClickListener(this); mButton.setTag(this); Choice c = new Choice(UNCHANGED_KEY, activity.getResources().getString(R.string.enum_unchanged), ID_DOT_UNCHANGED); mChoices.add(c); mCurrentChoice = c; initChoices(values, actions, actionPrefix, uiStrings); updateButtonState(mCurrentChoice); } @Override public void setEnabled(boolean enable, String disabledMessage) { mDisabledMessage = disabledMessage; mButton.setEnabled(enable); updateButtonState(mCurrentChoice); } @Override public boolean isEnabled() { return mButton.isEnabled(); } @Override public void requestFocus() { mButton.requestFocus(); } protected void initChoices(Object[] values, String[] actions, char prefix, String[] uiStrings) { String currentValue = getActionValue(actions, prefix); int counter = 0; for (Object value : values) { String s = "#PrefEnum: Error Unknown Setting#"; char p = 0; if (value instanceof RingerMode) { p = ((RingerMode) value).getActionLetter(); s = ((RingerMode) value).toUiString(getActivity()); } else if (value instanceof VibrateRingerMode) { p = ((VibrateRingerMode) value).getActionLetter(); s = ((VibrateRingerMode) value).toUiString(getActivity()); } int dot = counter == 0 ? ID_DOT_STATE_ON : counter == 1 ? ID_DOT_STATE_OFF : ID_DOT_EXTRA; counter++; Choice c = new Choice(p, s, dot); mChoices.add(c); if (currentValue != null && currentValue.length() >= 1 && currentValue.charAt(0) == p) { mCurrentChoice = c; } } } public void onClick(View view) { getActivity().openContextMenu(mButton); } @Override public void onCreateContextMenu(ContextMenu menu) { menu.setHeaderTitle(mMenuTitle); for (Choice choice : mChoices) { menu.add(choice.mUiName); } } @Override public void onContextItemSelected(MenuItem item) { CharSequence title = item.getTitle(); for (Choice choice : mChoices) { if (choice.mUiName.equals(title)) { mCurrentChoice = choice; updateButtonState(mCurrentChoice); break; } } } public void collectResult(StringBuilder actions) { if (isEnabled() && mCurrentChoice != null && mCurrentChoice.mKey != UNCHANGED_KEY) { appendAction(actions, mActionPrefix, Character.toString(mCurrentChoice.mKey)); } } /** * Buttons labels (from resources) can contain @ (for menu title) or * $ for ui name. */ private void updateButtonState(Choice choice) { Resources r = getActivity().getResources(); CharSequence t = r.getText(R.string.editaction_button_label); SpannableStringBuilder sb = new SpannableStringBuilder(t); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if (c == '@') { sb.replace(i, i + 1, mMenuTitle); } else if (c == '$') { if (!isEnabled() && mDisabledMessage != null) { sb.replace(i, i + 1, mDisabledMessage); } else { sb.replace(i, i + 1, choice.mUiName); } } } mButton.setText(sb); Drawable d = r.getDrawable(choice.mDotColor); mButton.setCompoundDrawablesWithIntrinsicBounds( d, // left null, // top null, // right null // bottom ); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.actions; import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefPercentDialog.Accessor; //----------------------------------------------- public class PrefPercent extends PrefBase implements View.OnClickListener { private char mActionPrefix; private Button mButton; /** Indicates the preference is set to "unchanged" */ public final static int VALUE_UNCHANGED = -1; /** Indicates the preference is set to the custom choice */ public final static int VALUE_CUSTOM_CHOICE = -2; /** One of {@link #VALUE_UNCHANGED}, {@link #VALUE_CUSTOM_CHOICE}, or 0..100 */ private int mCurrentValue; private final String mDialogTitle; private final int mIconResId; private int mDialogId; private final Accessor mAccessor; private String mDisabledMessage; public PrefPercent(Activity activity, int buttonResId, String[] actions, char actionPrefix, String dialogTitle, int iconResId, PrefPercentDialog.Accessor accessor) { super(activity); mActionPrefix = actionPrefix; mDialogTitle = dialogTitle; mIconResId = iconResId; mAccessor = accessor; mButton = findButtonById(buttonResId); mButton.setOnClickListener(this); mButton.setTag(this); mCurrentValue = VALUE_UNCHANGED; initValue(actions, actionPrefix); updateButtonText(); } @Override public void setEnabled(boolean enable, String disabledMessage) { mDisabledMessage = disabledMessage; mButton.setEnabled(enable); updateButtonText(); } @Override public boolean isEnabled() { return mButton.isEnabled(); } @Override public void requestFocus() { mButton.requestFocus(); } public String getDialogTitle() { return mDialogTitle; } public int getIconResId() { return mIconResId; } public Accessor getAccessor() { return mAccessor; } /** Returns one of {@link #VALUE_UNCHANGED}, {@link #VALUE_CUSTOM_CHOICE}, or 0..100 */ public int getCurrentValue() { return mCurrentValue; } /** Sets to one of {@link #VALUE_UNCHANGED}, {@link #VALUE_CUSTOM_CHOICE}, or 0..100 */ public void setValue(int percent) { mCurrentValue = percent; updateButtonText(); } private void initValue(String[] actions, char prefix) { String currentValue = getActionValue(actions, prefix); char customChoiceValue = mAccessor.getCustomChoiceValue(); if (currentValue != null && currentValue.length() == 1 && currentValue.charAt(0) == customChoiceValue) { mCurrentValue = VALUE_CUSTOM_CHOICE; } else { try { mCurrentValue = Integer.parseInt(currentValue); } catch (Exception e) { mCurrentValue = VALUE_UNCHANGED; } } } private void updateButtonText() { Resources r = getActivity().getResources(); String label = r.getString(R.string.percent_button_unchanged); int customStrId = mAccessor.getCustomChoiceButtonLabel(); if (customStrId > 0 && mCurrentValue == VALUE_CUSTOM_CHOICE) { label = r.getString(customStrId); } else if (mCurrentValue >= 0) { label = String.format("%d%%", mCurrentValue); } CharSequence t = r.getText(R.string.editaction_button_label); SpannableStringBuilder sb = new SpannableStringBuilder(t); for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if (c == '@') { sb.replace(i, i + 1, mDialogTitle); } else if (c == '$') { if (!isEnabled() && mDisabledMessage != null) { sb.replace(i, i + 1, mDisabledMessage); } else { sb.replace(i, i + 1, label); } } } mButton.setText(sb); Drawable d = r.getDrawable( mCurrentValue == VALUE_CUSTOM_CHOICE ? ID_DOT_EXTRA : mCurrentValue < 0 ? ID_DOT_UNCHANGED : ID_DOT_PERCENT); mButton.setCompoundDrawablesWithIntrinsicBounds( d, // left null, // top null, // right null // bottom ); } public void collectResult(StringBuilder actions) { if (isEnabled()) { char customChoiceValue = mAccessor.getCustomChoiceValue(); if (customChoiceValue > 0 && mCurrentValue == VALUE_CUSTOM_CHOICE) { appendAction(actions, mActionPrefix, Character.toString(customChoiceValue)); } else if (mCurrentValue >= 0) { appendAction(actions, mActionPrefix, Integer.toString(mCurrentValue)); } } } @Override public void onContextItemSelected(MenuItem item) { // from PrefBase, not used here } @Override public void onCreateContextMenu(ContextMenu menu) { // from PrefBase, not used here } public void onClick(View v) { getActivity().showDialog(mDialogId); } public int setDialogId(int dialogId) { mDialogId = dialogId; return mDialogId; } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.utils; import android.content.Context; import android.media.AudioManager; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; /** * Helper class that changes settings. * <p/> * Methods here directly correspond to something available in the UI. * Currently the different cases are: * <ul> * <li> Ringer: normal, silent.. * <li> Ringer Vibrate: on, off. * <li> Ringer volume: percent. * <li> Wifi: on/off. * <li> Brightness: percent (disabled due to API) * </ul> */ public class SettingsHelper { private static final boolean DEBUG = true; public static final String TAG = SettingsHelper.class.getSimpleName(); private final Context mContext; public SettingsHelper(Context context) { mContext = context; } public boolean canControlAudio() { AudioManager manager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); return manager != null; } public enum RingerMode { /** Normal ringer: actually rings. */ RING, /** Muted ringed. */ MUTE; public char getActionLetter() { return (this == RING) ? 'R' : 'M'; } /** Capitalizes the string */ public String toUiString(Context context) { return (this == RING) ? context.getString(R.string.ringermode_ring) : context.getString(R.string.ringermode_mute); } } public enum VibrateRingerMode { /** Vibrate is on (Ringer & Notification) */ VIBRATE, /** Vibrate is off, both ringer & notif */ NO_VIBRATE_ALL, /** Ringer vibrate is off but notif is on */ NO_RINGER_VIBRATE, /** Ringer vibrate is on but notif is off */ NO_NOTIF_VIBRATE; public char getActionLetter() { if (this == NO_VIBRATE_ALL) return 'N'; if (this == NO_RINGER_VIBRATE) return 'R'; if (this == NO_NOTIF_VIBRATE) return 'O'; assert this == VIBRATE; return 'V'; } /** Capitalizes the string */ public String toUiString(Context context) { if (this == NO_VIBRATE_ALL) { return context.getString(R.string.vibrateringermode_no_vibrate); } if (this == NO_RINGER_VIBRATE) { return context.getString(R.string.vibrateringermode_no_ringer_vibrate); } if (this == NO_NOTIF_VIBRATE) { return context.getString(R.string.vibrateringermode_no_notif_vibrate); } assert this == VIBRATE; return context.getString(R.string.vibrateringermode_vibrate); } } // --- ringer: vibrate & volume --- public void changeRingerVibrate(RingerMode ringer, VibrateRingerMode vib) { AudioManager manager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); if (manager == null) { Log.w(TAG, "changeRingerMode: AUDIO_SERVICE missing!"); return; } if (DEBUG) Log.d(TAG, String.format("changeRingerVibrate: %s + %s", ringer != null ? ringer.toString() : "ringer-null", vib != null ? vib.toString() : "vib-null")); if (vib != null) { switch(vib) { case VIBRATE: // set both ringer & notification vibrate modes to on manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON); break; case NO_VIBRATE_ALL: // set both ringer & notification vibrate modes to off manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF); manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); break; case NO_RINGER_VIBRATE: // ringer vibrate off, notification vibrate on manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF); manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON); break; case NO_NOTIF_VIBRATE: // ringer vibrate on, notification vibrate off manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); manager.setVibrateSetting( AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); break; } } if (ringer != null) { switch (ringer) { case RING: // normal may or may not vibrate, cf setting above // (for RingGuard intent, need to keep volume unchanged) VolumeChange.changeRinger( mContext, AudioManager.RINGER_MODE_NORMAL); break; case MUTE: if (vib != null && vib == VibrateRingerMode.VIBRATE) { VolumeChange.changeRinger( mContext, AudioManager.RINGER_MODE_VIBRATE); } else { // this turns off the vibrate, which unfortunately doesn't respect // the case where vibrate should not be changed when going silent. // TODO read the system pref for the default "vibrate" mode and use // when vib==null. VolumeChange.changeRinger( mContext, AudioManager.RINGER_MODE_SILENT); } break; } } } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.utils; import android.content.Context; /** * Wrapper so that we don't depend directly on the agent lib. * <p/> * Status: not currently used. */ @SuppressWarnings("unused") public class AgentWrapper { private static final boolean ENABLE = false; private static final boolean DEBUG = false; public static final String TAG = AgentWrapper.class.getSimpleName(); private static Class<?> mAgentClazz; private static String mK; public enum Event { OpenProfileUI, OpenTimeActionUI, OpenIntroUI, OpenErrorReporterUI, MenuSettings, MenuAbout, MenuReset, CheckProfiles, } public AgentWrapper() { } public void start(Context context) { if (!ENABLE) return; // if (mAgentClazz == null) { // String ks[] = null; // // try { // InputStream is = null; // try { // is = context.getResources().getAssets().open("Keyi.txt"); // } catch (Exception e) { // is = context.getResources().getAssets().open("Keyu.txt"); // } // try { // byte[] buf = new byte[255]; // is.read(buf); // String k = new String(buf); // ks = k.trim().split(" "); // } finally { // if (is != null) is.close(); // } // // if (ks == null || ks.length != 2) { // if (DEBUG) Log.d(TAG, "startk failed"); // return; // } // // ClassLoader cl = context.getClassLoader(); // Class<?> clazz = cl.loadClass(ks[0]); // // // start ok, keep the class // mAgentClazz = clazz; // mK = ks[1]; // // } catch (Exception e) { // // ignore silently // } // } // if (mAgentClazz != null) { // try { // Method m = mAgentClazz.getMethod("onStartSession", new Class<?>[] { Context.class, String.class }); // m.invoke(null, new Object[] { context, mK }); // } catch (Exception e) { // // ignore silently // } // } } public void event(Event event) { if (!ENABLE) return; // if (mAgentClazz != null) { // try { // Method m = mAgentClazz.getMethod("onEvent", new Class<?>[] { String.class }); // m.invoke(null, new Object[] { event.toString() }); // } catch (Exception e) { // // ignore silently // } // } } public void stop(Context context) { if (!ENABLE) return; // if (mAgentClazz != null) { // try { // Method m = mAgentClazz.getMethod("onEndSession", new Class<?>[] { Context.class }); // m.invoke(null, new Object[] { context }); // } catch (Exception e) { // // ignore silently // } // } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.utils; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.util.Log; //----------------------------------------------- public class ApplyVolumeReceiver extends BroadcastReceiver { public static final String TAG = ApplyVolumeReceiver.class.getSimpleName(); private static final boolean DEBUG = true; @Override public void onReceive(Context context, Intent intent) { if (getResultCode() == Activity.RESULT_CANCELED) { Log.d(TAG, "VolumeReceiver was canceled (and ignored)"); } applyVolumeIntent(context, intent); } public static void applyVolumeIntent(Context context, Intent intent) { try { if (intent == null) { Log.d(TAG, "null intent"); return; } int stream = intent.getIntExtra(VolumeChange.EXTRA_OI_STREAM, -1); int vol = intent.getIntExtra(VolumeChange.EXTRA_OI_VOLUME, -1); int ringMode = intent.getIntExtra(VolumeChange.EXTRA_OI_RING_MODE, -1); if (stream >= 0 && vol >= 0) { changeStreamVolume(context, stream, vol); } if (ringMode >= 0) { changeRingMode(context, ringMode); } } catch (Exception e) { Log.w(TAG, e); } } private static void changeStreamVolume(Context context, int stream, int vol) { //-- if (DEBUG) Log.d(TAG, String.format("applyVolume: stream=%d, vol=%d%%", stream, vol)); AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (manager != null) { //-- if (DEBUG) Log.d(TAG, String.format("current=%d%%", manager.getStreamVolume(stream))); manager.setStreamVolume(stream, vol, 0 /*flags*/); try { Thread.sleep(1 /*ms*/); } catch (InterruptedException e) { // ignore } int actual = manager.getStreamVolume(stream); if (actual == vol) { if (DEBUG) Log.d(TAG, String.format("Vol change OK, stream %d, vol %d", stream, vol)); } else { if (DEBUG) Log.d(TAG, String.format("Vol change FAIL, stream %d, vol %d, actual %d", stream, vol, actual)); } } else { Log.d(TAG, "No audio manager found"); } } private static void changeRingMode(Context context, int ringMode) { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (manager != null) { manager.setRingerMode(ringMode); if (DEBUG) Log.d(TAG, String.format("Ring mode set to %d", ringMode)); } else { Log.d(TAG, "No audio manager found"); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.utils; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ResolveInfo; import android.media.AudioManager; import android.util.Log; //----------------------------------------------- /** * Notify ring-guard app types that the volume change was automated * and intentional, and then performs the actual action. * <p/> * See http://code.google.com/p/autosettings/issues/detail?id=4 </br> * See http://www.openintents.org/en/node/380 */ public class VolumeChange { public static final String TAG = VolumeChange.class.getSimpleName(); private static final boolean DEBUG = true; public static final String INTENT_OI_VOL_UPDATE = "org.openintents.audio.action_volume_update"; public static final String EXTRA_OI_VOLUME = "org.openintents.audio.extra_volume_index"; public static final String EXTRA_OI_STREAM = "org.openintents.audio.extra_stream_type"; public static final String EXTRA_OI_RING_MODE = "org.openintents.audio.extra_ringer_mode"; /** Static instance of the volume receiver. */ private static ApplyVolumeReceiver sVolumeReceiver; /** * Notify ring-guard app types that the volume change was automated * and intentional, and then performs the actual action. * <p/> * See http://code.google.com/p/autosettings/issues/detail?id=4 </br> * See http://www.openintents.org/en/node/380 * * @param context App context * @param volume The new volume level or -1 for a ringer/mute change */ public static void changeVolume(Context context, int stream, int volume) { broadcast(context, stream, volume, -1 /*ring*/); } /** * Notify ring-guard app types that the ringer change was automated * and intentional, and then performs the actual action. * <p/> * See http://code.google.com/p/autosettings/issues/detail?id=4 </br> * See http://www.openintents.org/en/node/380 * * @param context App context * @param volume The new volume level or -1 for a ringer/mute change */ public static void changeRinger(Context context, int ringMode) { broadcast(context, -1 /*stream*/, -1 /*vol*/, ringMode); } private static void broadcast(Context context, int stream, int volume, int ringMode) { try { Intent intent = new Intent(INTENT_OI_VOL_UPDATE); if (volume != -1) { intent.putExtra(EXTRA_OI_STREAM, stream); intent.putExtra(EXTRA_OI_VOLUME, volume); } if (ringMode != -1) { intent.putExtra(EXTRA_OI_RING_MODE, ringMode); } List<ResolveInfo> receivers = context.getPackageManager().queryBroadcastReceivers(intent, 0 /*flags*/); if (receivers == null || receivers.isEmpty()) { Log.d(TAG, "No vol_update receivers found. Doing direct call."); ApplyVolumeReceiver.applyVolumeIntent(context, intent); return; } // If we get here, we detected something is listening to // the ringguard intent. if (ringMode != -1 && volume == -1 && stream == -1) { // Note: RingGuard will ignore the ringMode change if we don't // also provide a stream/volume information. It's up to the caller // to pass in the stream/volume too. AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); stream = AudioManager.STREAM_RING; volume = ringMode == AudioManager.RINGER_MODE_NORMAL ? manager.getStreamVolume(stream) : 0; intent.putExtra(EXTRA_OI_STREAM, stream); intent.putExtra(EXTRA_OI_VOLUME, volume); } synchronized (VolumeChange.class) { if (sVolumeReceiver == null) { sVolumeReceiver = new ApplyVolumeReceiver(); context.getApplicationContext().registerReceiver(sVolumeReceiver, new IntentFilter()); } } if (DEBUG) Log.d(TAG, String.format("Broadcast: %s %s", intent.toString(), intent.getExtras().toString())); context.sendOrderedBroadcast(intent, null, //receiverPermission sVolumeReceiver, null, //scheduler Activity.RESULT_OK, //initialCode null, //initialData intent.getExtras() //initialExtras ); } catch (Exception e) { Log.w(TAG, e); } } public static void unregisterVolumeReceiver(Context context) { synchronized (VolumeChange.class) { if (sVolumeReceiver != null) { try { context.getApplicationContext().unregisterReceiver(sVolumeReceiver); } catch (Exception e) { Log.w(TAG, e); } finally { sVolumeReceiver = null; } } } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import java.lang.reflect.Method; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; //----------------------------------------------- public class BluetoothSetting implements ISetting { private static final boolean DEBUG = true; public static final String TAG = BluetoothSetting.class.getSimpleName(); private boolean mCheckSupported = true; private boolean mIsSupported = false; public boolean isSupported(Context context) { if (mCheckSupported) { try { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (manager == null) return false; if (!checkMinApiLevel(5)) return false; // Is a bluetooth adapter actually available? Class<?> btaClass = Class.forName("android.bluetooth.BluetoothAdapter"); Method getter = btaClass.getMethod("getDefaultAdapter"); Object result = getter.invoke(null); mIsSupported = result != null; if (!mIsSupported) { String fp = Build.FINGERPRINT; if (fp != null && fp.startsWith("generic/sdk/generic/:") && fp.endsWith(":eng/test-keys")) { // This looks like an emulator that has no BT emulation. // Just enable it anyway. mIsSupported = true; } } } catch (Exception e) { Log.d(TAG, "Missing BTA API"); } finally { mCheckSupported = false; } } return mIsSupported; } public Object createUi(Activity activity, String[] currentActions) { PrefToggle p = new PrefToggle(activity, R.id.bluetoothButton, currentActions, Columns.ACTION_BLUETOOTH, activity.getString(R.string.editaction_bluetooth)); p.setEnabled(isSupported(activity), activity.getString(R.string.setting_not_supported)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefToggle) { ((PrefToggle) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); return context.getString(value > 0 ? R.string.timedaction_bluetooth_on : R.string.timedaction_bluetooth_off); } catch (NumberFormatException e) { // ignore } return null; } public boolean performAction(Context context, String action) { try { Object t = context.getSystemService(Context.TELEPHONY_SERVICE); if (t instanceof TelephonyManager) { if (((TelephonyManager) t).getCallState() != TelephonyManager.CALL_STATE_IDLE) { // There's an ongoing call or a ringing one. // Either way, not a good time to switch bluetooth on or off. return false; } } int value = Integer.parseInt(action.substring(1)); change(value > 0); } catch (Throwable e) { if (DEBUG) Log.e(TAG, "Perform action failed for " + action, e); } return true; } // ---- private boolean checkMinApiLevel(int minApiLevel) { // Build.SDK_INT is only in API 4 and we're still compatible with API 3 try { int n = Integer.parseInt(Build.VERSION.SDK); return n >= minApiLevel; } catch (Exception e) { Log.d(TAG, "Failed to parse Build.VERSION.SDK=" + Build.VERSION.SDK, e); } return false; } private void change(boolean enabled) { // This requires permission android.permission.BLUETOOTH_ADMIN try { Class<?> btaClass = Class.forName("android.bluetooth.BluetoothAdapter"); Method getter = btaClass.getMethod("getDefaultAdapter"); Object bt = getter.invoke(null); if (bt == null) { if (DEBUG) Log.w(TAG, "changeBluetooh: BluetoothAdapter null!"); return; } if (DEBUG) Log.d(TAG, "changeBluetooh: " + (enabled ? "on" : "off")); if (enabled) { bt.getClass().getMethod("enable").invoke(bt); } else { bt.getClass().getMethod("disable").invoke(bt); } } catch (Exception e) { if (DEBUG) Log.d(TAG, "Missing BTA API"); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * based on a contribution by: * http://code.google.com/p/autosettings/issues/detail?id=73 * Copyright (C) 2010 timendum gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import android.app.Activity; import android.content.Context; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; //----------------------------------------------- public class SyncSetting implements ISetting { public static final String TAG = SyncSetting.class.getSimpleName(); private static final boolean DEBUG = true; private boolean mCheckSupported = true; private boolean mIsSupported = false; public boolean isSupported(Context context) { if (mCheckSupported) { try { // This will fail to load with a VerifyError exception if the // API to set the master sync doesn't exists (Android API >= 5). // Also it requires permission android.permission.READ_SYNC_SETTINGS SyncHelper.getMasterSyncAutomatically(); mIsSupported = true; } catch (Throwable t) { // We expect VerifyError when the API isn't supported. Log.d(TAG, "Auto-Sync not supported", t); } finally { mCheckSupported = false; } } return mIsSupported; } public Object createUi(Activity activity, String[] currentActions) { PrefToggle p = new PrefToggle(activity, -1 /*button id*/, currentActions, Columns.ACTION_SYNC, activity.getString(R.string.editaction_sync)); p.setEnabled(isSupported(activity), activity.getString(R.string.setting_not_supported)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefToggle) { ((PrefToggle) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); return context.getString(value > 0 ? R.string.timedaction_sync_on : R.string.timedaction_sync_off); } catch (NumberFormatException e) { // ignore } return null; } public boolean performAction(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); change(context, value > 0); } catch (NumberFormatException e) { if (DEBUG) Log.d(TAG, "Perform action failed for " + action); } return true; } private void change(Context context, boolean enabled) { // This requires permission android.permission.WRITE_SYNC_SETTINGS if (DEBUG) Log.d(TAG, "changeSync: " + (enabled ? "on" : "off")); try { if (mIsSupported) { SyncHelper.setMasterSyncAutomatically(enabled); } } catch (Throwable t) { if (DEBUG) { Log.e(TAG, "Change failed", t); } } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import java.util.List; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorManager; import android.provider.Settings; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefPercent; import com.rdrrlabs.example.timer1app.core.actions.PrefPercentDialog.Accessor; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.ui.ChangeBrightnessUI; //----------------------------------------------- public class BrightnessSetting implements ISetting { public static final String TAG = BrightnessSetting.class.getSimpleName(); private boolean mCheckAutoSupported = true; private boolean mIsAutoSupported = false; /** android.provider.Settings.SCREEN_BRIGHTNESS_MODE, available starting with API 8. */ private static final String AUTO_BRIGHT_KEY = Settings.System.SCREEN_BRIGHTNESS_MODE; /** Auto-brightness is supported and in "manual" mode. */ public static final int AUTO_BRIGHT_MANUAL = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL; /** Auto-brightness is supported and in automatic mode. */ public static final int AUTO_BRIGHT_AUTO = Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; /** Auto-brightness is not supported. */ public static final int AUTO_BRIGHT_UNSUPPORTED = -1; public boolean isSupported(Context context) { return true; } public boolean isAutoBrightnessSupported(Context context) { if (!mCheckAutoSupported) return mIsAutoSupported; int mode = AUTO_BRIGHT_UNSUPPORTED; try { mode = getAutoBrightness(context); } catch (Throwable e) { // There's no good reason for this to crash but it's been // shown to fail when trying to perform it at boot. So in this // case return false but do not mark it as checked so that we // can retry later. return false; } try { if (mode == AUTO_BRIGHT_UNSUPPORTED) return false; SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); if (manager != null) { List<Sensor> list = manager.getSensorList(Sensor.TYPE_LIGHT); mIsAutoSupported = list != null && list.size() > 0; } } finally { mCheckAutoSupported = false; } return mIsAutoSupported; } public Object createUi(final Activity activity, String[] currentActions) { PrefPercent p = new PrefPercent(activity, R.id.brightnessButton, currentActions, Columns.ACTION_BRIGHTNESS, activity.getString(R.string.editaction_brightness), R.drawable.ic_menu_view_brightness, new Accessor() { public void changePercent(int percent) { // disable the immediate slider feedback, it flickers too much and is very slow. } public int getPercent() { return getCurrentBrightness(activity); } public int getCustomChoiceLabel() { if (isAutoBrightnessSupported(activity)) { return R.string.timedaction_auto_brightness; } return 0; } public int getCustomChoiceButtonLabel() { return R.string.timedaction_automatic; } public char getCustomChoiceValue() { return Columns.ACTION_BRIGHTNESS_AUTO; } }); p.setEnabled(isSupported(activity), activity.getString(R.string.setting_not_supported)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefPercent) { ((PrefPercent) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { if (action.length() < 2) return null; char v = action.charAt(1); if (isAutoBrightnessSupported(context) && v == Columns.ACTION_BRIGHTNESS_AUTO) { return context.getString(R.string.timedaction_auto_brightness); } else { try { int value = Integer.parseInt(action.substring(1)); return context.getString( R.string.timedaction_brightness_int, value); } catch (NumberFormatException e) { // ignore } } return null; } public boolean performAction(Context context, String action) { if (action.length() < 2) return true; char v = action.charAt(1); try { if (v == Columns.ACTION_BRIGHTNESS_AUTO) { changeAutoBrightness(context, true); } else { int value = Integer.parseInt(action.substring(1)); changeAutoBrightness(context, false); changeBrightness(context, value); } } catch (NumberFormatException e) { // pass } catch (Throwable e) { // Shouldn't happen. Offer to retry later. return false; } return true; } private void changeAutoBrightness(Context context, boolean auto) { ContentResolver resolver = context.getContentResolver(); Settings.System.putInt(resolver, AUTO_BRIGHT_KEY, auto ? AUTO_BRIGHT_AUTO : AUTO_BRIGHT_MANUAL); } /** * Returns one of {@link #AUTO_BRIGHT_MANUAL}, {@link #AUTO_BRIGHT_AUTO} or * {@link #AUTO_BRIGHT_UNSUPPORTED}. */ private int getAutoBrightness(Context context) { ContentResolver resolver = context.getContentResolver(); return Settings.System.getInt(resolver, AUTO_BRIGHT_KEY, AUTO_BRIGHT_UNSUPPORTED); } /** * @param percent The new value in 0..100 range (will get mapped to adequate OS values) */ private void changeBrightness(Context context, int percent) { // Reference: // http://android.git.kernel.org/?p=platform/packages/apps/Settings.git;a=blob;f=src/com/android/settings/BrightnessPreference.java // The source indicates // - Backlight range is 0..255 // - Must not set to 0 (user would see nothing) so they use 10 as minimum // - All constants are in android.os.Power which is hidden in the SDK. // - To get value: Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); // - To set value: Settings.System.putInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, v); int actual = getCurrentBrightness(context); if (actual == percent) { Log.d(TAG, "NOT changed, already " + Integer.toString(percent)); return; } Log.d(TAG, "SET to " + Integer.toString(percent)); Intent i = new Intent(context, ChangeBrightnessUI.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(ChangeBrightnessUI.INTENT_SET_BRIGHTNESS, percent / 100.0f); context.startActivity(i); } /** * Returns screen brightness in range 0..100%. * <p/> * See comments in {@link #changeBrightness(Context, int)}. The real range is 0..255, * maps it 0..100. */ private int getCurrentBrightness(Context context) { return (int) (100 * ChangeBrightnessUI.getCurrentBrightness(context)); } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.media.AudioManager; import android.provider.Settings; import android.util.Log; import android.util.SparseArray; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefPercent; import com.rdrrlabs.example.timer1app.core.actions.PrefPercentDialog.Accessor; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.core.utils.VolumeChange; //----------------------------------------------- public class VolumeSetting implements ISetting { private static final boolean DEBUG = true; public static final String TAG = VolumeSetting.class.getSimpleName(); /** android.provider.Settings.NOTIFICATION_USE_RING_VOLUME, available starting with API 3 * but it's hidden from the SDK. The Settings.java comment says eventually this setting * will go away later once there are "profile" support, whatever that is. */ private static final String NOTIF_RING_VOL_KEY = "notifications_use_ring_volume"; /** Notification vol and ring volumes are synched. */ private static final int NOTIF_RING_VOL_SYNCED = 1; /** Notification vol and ring volumes are not synched. */ private static final int NOTIF_RING_VOL_NOT_SYNCHED = 0; /** No support for notification and ring volume sync. */ private static final int NOTIF_RING_VOL_UNSUPPORTED = -1; private final int mStream; private boolean mCheckSupported = true; private boolean mIsSupported = false; private static SparseArray<StreamInfo> sStreamInfo = new SparseArray<StreamInfo>(6); static { sStreamInfo.put(AudioManager.STREAM_RING, new StreamInfo(Columns.ACTION_RING_VOLUME, R.id.ringerVolButton, R.string.editaction_volume, R.string.timedaction_ringer_int)); sStreamInfo.put(AudioManager.STREAM_NOTIFICATION, new StreamInfo(Columns.ACTION_NOTIF_VOLUME, R.id.notifVolButton, R.string.editaction_notif_volume, R.string.timedaction_notif_int)); sStreamInfo.put(AudioManager.STREAM_MUSIC, new StreamInfo(Columns.ACTION_MEDIA_VOLUME, R.id.mediaVolButton, R.string.editaction_media_volume, R.string.timedaction_media_int)); sStreamInfo.put(AudioManager.STREAM_ALARM, new StreamInfo(Columns.ACTION_ALARM_VOLUME, R.id.alarmVolButton, R.string.editaction_alarm_volume, R.string.timedaction_alarm_int)); sStreamInfo.put(AudioManager.STREAM_SYSTEM, new StreamInfo(Columns.ACTION_SYSTEM_VOLUME, R.id.systemVolButton, R.string.editaction_system_volume, R.string.timedaction_system_vol_int)); sStreamInfo.put(AudioManager.STREAM_VOICE_CALL, new StreamInfo(Columns.ACTION_VOICE_CALL_VOLUME, R.id.voiceCallVolButton, R.string.editaction_voice_call_volume, R.string.timedaction_voice_call_vol_int)); } public VolumeSetting(int stream) { mStream = stream; } public boolean isSupported(Context context) { if (mCheckSupported) { if (sStreamInfo.get(mStream) == null) { mIsSupported = false; } else { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); mIsSupported = manager != null; } mCheckSupported = false; } return mIsSupported; } public Object createUi(final Activity activity, String[] currentActions) { StreamInfo info = sStreamInfo.get(mStream); if (info == null) return null; // should not happen PrefPercent p = new PrefPercent(activity, info.getButtonResId(), currentActions, info.getActionPrefix(), activity.getString(info.getDialogTitleResId()), 0, new Accessor() { public void changePercent(int percent) { // Don't do live feedback of the volume change from the action UI // -- changeVolume(activity, percent); } public int getPercent() { return getVolume(activity, mStream); } public int getCustomChoiceLabel() { if (mStream == AudioManager.STREAM_NOTIFICATION && canSyncNotificationRingVol(activity)) { return R.string.editaction_notif_ring_sync; } return 0; } public int getCustomChoiceButtonLabel() { if (mStream == AudioManager.STREAM_NOTIFICATION) { return R.string.actionlabel_notif_ring_sync; } return 0; } public char getCustomChoiceValue() { if (mStream == AudioManager.STREAM_NOTIFICATION) { return Columns.ACTION_NOTIF_RING_VOL_SYNC; } return 0; } }); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefPercent) { ((PrefPercent) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { if (mStream == AudioManager.STREAM_NOTIFICATION) { char v = action.charAt(1); if (v == Columns.ACTION_NOTIF_RING_VOL_SYNC) { return context.getString(R.string.timedaction_notif_ring_sync); } } try { StreamInfo info = sStreamInfo.get(mStream); if (info == null) return null; // should not happen int value = Integer.parseInt(action.substring(1)); return context.getString(info.getActionLabelResId(), value); } catch (NumberFormatException e) { if (DEBUG) Log.d(TAG, "Invalid volume number for action " + action); } return null; } public boolean performAction(Context context, String action) { if (mStream == AudioManager.STREAM_NOTIFICATION) { char v = action.charAt(1); if (v == Columns.ACTION_NOTIF_RING_VOL_SYNC) { changeNotifRingVolSync(context, NOTIF_RING_VOL_SYNCED); return true; } } try { int value = Integer.parseInt(action.substring(1)); if (mStream == AudioManager.STREAM_NOTIFICATION) { changeNotifRingVolSync(context, NOTIF_RING_VOL_NOT_SYNCHED); } changeVolume(context, value); } catch (Throwable e) { if (DEBUG) Log.e(TAG, "Perform action failed for " + action, e); } return true; } // ----- private int getVolume(Context context, int stream) { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (manager == null) { if (DEBUG) Log.w(TAG, "getVolume: AUDIO_SERVICE missing!"); return 50; } int vol = manager.getStreamVolume(stream); int max = manager.getStreamMaxVolume(stream); return (vol * 100 / max); } private void changeVolume(Context context, int percent) { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (manager == null) { if (DEBUG) Log.w(TAG, "changeVolume: AUDIO_SERVICE missing!"); return; } if (DEBUG) Log.d(TAG, String.format("changeVolume: stream=%d, vol=%d%%", mStream, percent)); int max = manager.getStreamMaxVolume(mStream); int vol = (max * percent) / 100; VolumeChange.changeVolume( context, mStream, vol); } /** * Returns one of {@link #NOTIF_RING_VOL_SYNCED}, {@link #NOTIF_RING_VOL_NOT_SYNCHED} or * {@link #NOTIF_RING_VOL_UNSUPPORTED}. */ private int getSyncNotifRingVol(Context context) { final ContentResolver resolver = context.getContentResolver(); return Settings.System.getInt(resolver, NOTIF_RING_VOL_KEY, NOTIF_RING_VOL_UNSUPPORTED); } private boolean canSyncNotificationRingVol(Context context) { return getSyncNotifRingVol(context) != NOTIF_RING_VOL_UNSUPPORTED; } private void changeNotifRingVolSync(Context context, int notifSync) { ContentResolver resolver = context.getContentResolver(); Settings.System.putInt(resolver, NOTIF_RING_VOL_KEY, notifSync); if (DEBUG) Log.d(TAG, String.format("Notif Sync set to %d", notifSync)); } private static class StreamInfo { private final char mActionPrefix; private final int mButtonResId; private final int mDialogTitleResId; private final int mActionLabelResId; public StreamInfo(char actionPrefix, int buttonResId, int dialogTitleResId, int actionLabelResId) { mActionPrefix = actionPrefix; mButtonResId = buttonResId; mDialogTitleResId = dialogTitleResId; mActionLabelResId = actionLabelResId; } public char getActionPrefix() { return mActionPrefix; } public int getActionLabelResId() { return mActionLabelResId; } public int getButtonResId() { return mButtonResId; } public int getDialogTitleResId() { return mDialogTitleResId; } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import java.lang.reflect.Method; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.ServiceManager; import android.telephony.TelephonyManager; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.android.internal.telephony.ITelephony; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; //----------------------------------------------- /** * An attempt to toggle data off by directly accessing ITelephony.enableDataConnectivity(). * Requires permission android.permission.MODIFY_PHONE_STATE which is * unfortunately not granted (probably a signatureOrSystem permission). */ public class DataSetting implements ISetting { private static final boolean DEBUG = true; public static final String TAG = DataSetting.class.getSimpleName(); private boolean mCheckSupported = true; private boolean mIsSupported = false; private boolean mIsEnabled = false; public boolean isSupported(Context context) { if (mCheckSupported) { try { if (!mIsEnabled) { // check prefs to see if we should enable this. PrefsValues pv = new PrefsValues(context); mIsEnabled = pv.getUseDataToggle(); } if (!mIsEnabled) { mIsSupported = checkMinApiLevel(7); if (mIsSupported) { // Requires permission android.permission.MODIFY_PHONE_STATE which is // usually not granted (a signatureOrSystem permission.) mIsSupported = context.getPackageManager().checkPermission( Manifest.permission.MODIFY_PHONE_STATE, context.getPackageName()) == PackageManager.PERMISSION_GRANTED; } if (mIsSupported) { ITelephony it = getITelephony(context); // just check we can call one of the method. we don't need the info it.isDataConnectivityPossible(); // check we have the methods we want to call mIsSupported = (it.getClass().getDeclaredMethod("disableDataConnectivity", (Class[]) null) != null) && (it.getClass().getDeclaredMethod("enableDataConnectivity", (Class[]) null) != null); } } } catch (Throwable e) { Log.d(TAG, "Missing Data toggle API"); mIsSupported = false; } finally { mCheckSupported = false; } } return mIsSupported || mIsEnabled; } public Object createUi(Activity activity, String[] currentActions) { boolean supported = isSupported(activity); if (!mIsEnabled) { // New in version 1.9.14: if not enabled in the prefs, the UI // is not shown at all. // It's OK to return null here as EditActionUI just stores the // value as-is and collectUiResults() checks using instanceof // so it's null-safe. return null; } PrefToggle p = new PrefToggle(activity, -1 /*button id*/, currentActions, Columns.ACTION_DATA, activity.getString(R.string.editaction_data)); p.setEnabled(supported, mIsEnabled ? activity.getString(R.string.setting_not_supported) : activity.getString(R.string.setting_not_enabled)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefToggle) { ((PrefToggle) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); return context.getString(value > 0 ? R.string.timedaction_data_on : R.string.timedaction_data_off); } catch (NumberFormatException e) { // ignore } return null; } public boolean performAction(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); change(context, value > 0); } catch (Throwable e) { if (DEBUG) Log.e(TAG, "Perform action failed for " + action, e); } return true; } // ---- private ITelephony getITelephony(Context context) { try { // Get the internal ITelephony proxy directly. ITelephony it = ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE)); if (it != null) return it; } catch (Throwable t) { // Ignore any error, we'll retry differently below. } try { // Let's try harder, although this is unlikely to work if the previous one failed. TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) return null; Class<? extends TelephonyManager> c = manager.getClass(); Method getIT = c.getDeclaredMethod("getITelephony", (Class[]) null); getIT.setAccessible(true); Object t = getIT.invoke(manager, (Object[]) null); return (ITelephony) t; } catch (Throwable t) { Log.d(TAG, "Missing Data toggle API"); } return null; } private boolean checkMinApiLevel(int minApiLevel) { // Build.SDK_INT is only in API 4 and we're still compatible with API 3 try { int n = Integer.parseInt(Build.VERSION.SDK); return n >= minApiLevel; } catch (Exception e) { Log.d(TAG, "Failed to parse Build.VERSION.SDK=" + Build.VERSION.SDK, e); } return false; } private void change(Context context, boolean enabled) { // This requires permission android.permission.MODIFY_PHONE_STATE try { ITelephony it = getITelephony(context); if (it != null) { if (enabled) { it.enableApnType("default"); it.enableDataConnectivity(); } else { it.disableDataConnectivity(); it.disableApnType("default"); } } } catch (Throwable e) { // We're not supposed to get here since isSupported() should return false. if (DEBUG) Log.d(TAG, "Missing Data toggle API", e); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.google.code.apndroid.ApplicationConstants; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; //----------------------------------------------- public class ApnDroidSetting implements ISetting { private static final boolean DEBUG = true; public static final String TAG = ApnDroidSetting.class.getSimpleName(); public boolean isSupported(Context context) { // We don't want to cache the state here -- each time we create the // UI we want to check whether the app is installed. That's because // the instance has an app-lifetime scope and it's entirely possible // for the user to start the app, notice apndroid is missing, install // it and come back. The alternative is to listen for app (un)installs // but I rather not do that. PackageManager pm = context.getPackageManager(); Intent intent = new Intent(ApplicationConstants.CHANGE_STATUS_REQUEST); ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); return ri != null; } public Object createUi(Activity activity, String[] currentActions) { PrefToggle p = new PrefToggle(activity, -1 /*button id*/, currentActions, Columns.ACTION_APN_DROID, activity.getString(R.string.editaction_apndroid), new String[] { activity.getString(R.string.timedaction_apndroid_on), activity.getString(R.string.timedaction_apndroid_off) } ); p.setEnabled(isSupported(activity), activity.getString(R.string.setting_not_installed)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefToggle) { ((PrefToggle) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); return context.getString(value > 0 ? R.string.timedaction_apndroid_on : R.string.timedaction_apndroid_off); } catch (NumberFormatException e) { // ignore } return null; } public boolean performAction(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); change(context, value > 0); } catch (Throwable e) { if (DEBUG) Log.e(TAG, "Perform action failed for " + action, e); } return true; } private void change(Context context, boolean enabled) { if (DEBUG) Log.d(TAG, "changeApnDroid: " + (enabled ? "on" : "off")); try { Intent intent = new Intent(ApplicationConstants.CHANGE_STATUS_REQUEST); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(ApplicationConstants.TARGET_APN_STATE, enabled ? ApplicationConstants.State.ON : ApplicationConstants.State.OFF); context.startActivity(intent); } catch (Exception e) { if (DEBUG) Log.e(TAG, "Change failed", e); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import android.content.ContentResolver; /** * Gives access to {@link ContentResolver#getMasterSyncAutomatically()} * which is only available starting with API 5. * * {@link SyncSetting} uses this. When trying to load in API < 5, the class * will fail to load with a VerifyError exception since the sync method does * not exists. */ public class SyncHelper { /** * This will fail to load with a VerifyError exception if the * API to read the master sync doesn't exists (Android API Level 5). * * This requires permission android.permission.READ_SYNC_SETTINGS * @see ContentResolver#getMasterSyncAutomatically() */ public static boolean getMasterSyncAutomatically() { return ContentResolver.getMasterSyncAutomatically(); } /** * This will fail to load with a VerifyError exception if the * API to set the master sync doesn't exists (Android API Level 5). * * This requires permission android.permission.WRITE_SYNC_SETTINGS * @see ContentResolver#setMasterSyncAutomatically(boolean) */ public static void setMasterSyncAutomatically(boolean sync) { ContentResolver.setMasterSyncAutomatically(sync); } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.provider.Settings; import android.telephony.TelephonyManager; import android.util.Log; //----------------------------------------------- public class AirplaneSetting implements ISetting { private static final boolean DEBUG = true; public static final String TAG = AirplaneSetting.class.getSimpleName(); public boolean isSupported(Context context) { return true; } public Object createUi(Activity activity, String[] currentActions) { PrefToggle p = new PrefToggle(activity, R.id.airplaneButton, currentActions, Columns.ACTION_AIRPLANE, activity.getString(R.string.editaction_airplane)); p.setEnabled(isSupported(activity), activity.getString(R.string.setting_not_supported)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefToggle) { ((PrefToggle) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); return context.getString(value > 0 ? R.string.timedaction_airplane_on : R.string.timedaction_airplane_off); } catch (NumberFormatException e) { // ignore } return null; } public boolean performAction(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); if (value > 0) { Object t = context.getSystemService(Context.TELEPHONY_SERVICE); if (t instanceof TelephonyManager) { if (((TelephonyManager) t).getCallState() != TelephonyManager.CALL_STATE_IDLE) { // There's an ongoing call or a ringing one. // Either way, not a good time to switch airplane mode on. return false; } } } change(context, value > 0); } catch (Throwable e) { if (DEBUG) Log.e(TAG, "Perform action failed for " + action, e); } return true; } /** Changes the airplane mode */ private void change(Context context, boolean turnOn) { // Reference: settings source is in the cupcake gitweb tree at // packages/apps/Settings/src/com/android/settings/AirplaneModeEnabler.java // http://android.git.kernel.org/?p=platform/packages/apps/Settings.git;a=blob;f=src/com/android/settings/AirplaneModeEnabler.java;h=f105712260fd7b2d7804460dd180d1d6cea01afa;hb=HEAD if (DEBUG) Log.d(TAG, "changeAirplaneMode: " + (turnOn ? "on" : "off")); try { // Change the system setting Settings.System.putInt( context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, turnOn ? 1 : 0); // Post the intent Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); intent.putExtra("state", turnOn); context.sendBroadcast(intent); } catch (Exception e) { if (DEBUG) Log.e(TAG, "Change failed", e); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import android.app.Activity; import android.content.Context; import android.media.AudioManager; //----------------------------------------------- public class RingerSetting implements ISetting { public static final String TAG = RingerSetting.class.getSimpleName(); private boolean mCheckSupported = true; private boolean mIsSupported = false; public boolean isSupported(Context context) { if (mCheckSupported) { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); mIsSupported = manager != null; mCheckSupported = false; } return mIsSupported; } public Object createUi(Activity activity, String[] currentActions) { return null; } public void collectUiResults(Object settingUi, StringBuilder outActions) { } public String getActionLabel(Context context, String action) { return null; } public boolean performAction(Context context, String action) { return true; } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import android.app.Activity; import android.content.Context; import android.media.AudioManager; //----------------------------------------------- public class VibrateSetting implements ISetting { public static final String TAG = VibrateSetting.class.getSimpleName(); private boolean mCheckSupported = true; private boolean mIsSupported = false; public boolean isSupported(Context context) { if (mCheckSupported) { AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); mIsSupported = manager != null; mCheckSupported = false; } return mIsSupported; } public Object createUi(Activity activity, String[] currentActions) { return null; } public void collectUiResults(Object settingUi, StringBuilder outActions) { } public String getActionLabel(Context context, String action) { return null; } public boolean performAction(Context context, String action) { return true; } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import java.util.Collections; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Context; import android.media.AudioManager; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; //----------------------------------------------- public class SettingFactory { public static final String TAG = SettingFactory.class.getSimpleName(); private static final SettingFactory sInstance = new SettingFactory(); private ISettingsFactory2 mSettingsFactory2; /** A synchronized map of existing loaded settings. */ private final Map<Character, ISetting> mSettings = Collections.synchronizedMap(new HashMap<Character, ISetting>()); public static SettingFactory getInstance() { return sInstance; } private SettingFactory() { } public void registerFactory2(ISettingsFactory2 factory2) { mSettingsFactory2 = factory2; } /** Unloads the setting if it's loaded. */ public void forgetSetting(char code) { mSettings.remove(code); } /** * Returns an {@link ISetting}. Never returns null. */ public ISetting getSetting(char code) { ISetting s = mSettings.get(code); if (s != null) return s; switch(code) { case Columns.ACTION_RINGER: s = new RingerSetting(); break; case Columns.ACTION_VIBRATE: s = new VibrateSetting(); break; case Columns.ACTION_RING_VOLUME: s = new VolumeSetting(AudioManager.STREAM_RING); break; case Columns.ACTION_NOTIF_VOLUME: s = new VolumeSetting(AudioManager.STREAM_NOTIFICATION); break; case Columns.ACTION_MEDIA_VOLUME: s = new VolumeSetting(AudioManager.STREAM_MUSIC); break; case Columns.ACTION_ALARM_VOLUME: s = new VolumeSetting(AudioManager.STREAM_ALARM); break; case Columns.ACTION_SYSTEM_VOLUME: s = new VolumeSetting(AudioManager.STREAM_SYSTEM); break; case Columns.ACTION_VOICE_CALL_VOLUME: s = new VolumeSetting(AudioManager.STREAM_VOICE_CALL); break; case Columns.ACTION_BRIGHTNESS: s = new BrightnessSetting(); break; case Columns.ACTION_WIFI: s = new WifiSetting(); break; case Columns.ACTION_AIRPLANE: s = new AirplaneSetting(); break; case Columns.ACTION_BLUETOOTH: s = new BluetoothSetting(); break; case Columns.ACTION_APN_DROID: s = new ApnDroidSetting(); break; case Columns.ACTION_DATA: s = new DataSetting(); break; } if (s == null && mSettingsFactory2 != null) { s = mSettingsFactory2.getSetting(code); } if (s == null) { s = new NullSetting(); } assert s != null; mSettings.put(code, s); return s; } private static class NullSetting implements ISetting { public boolean isSupported(Context context) { return false; } public Object createUi(Activity activity, String[] currentActions) { return null; } public void collectUiResults(Object settingUi, StringBuilder outActions) { // pass } public String getActionLabel(Context context, String action) { return null; } public boolean performAction(Context context, String action) { return true; } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; public interface ISettingsFactory2 { public ISetting getSetting(char code); }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import android.app.Activity; import android.content.Context; import android.net.wifi.WifiManager; import android.util.Log; //----------------------------------------------- public class WifiSetting implements ISetting { private static final boolean DEBUG = true; public static final String TAG = WifiSetting.class.getSimpleName(); private boolean mCheckSupported = true; private boolean mIsSupported = false; public boolean isSupported(Context context) { if (mCheckSupported) { WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); mIsSupported = manager != null; mCheckSupported = false; } return mIsSupported; } public Object createUi(Activity activity, String[] currentActions) { PrefToggle p = new PrefToggle(activity, R.id.wifiButton, currentActions, Columns.ACTION_WIFI, activity.getString(R.string.editaction_wifi)); p.setEnabled(isSupported(activity), activity.getString(R.string.setting_not_supported)); return p; } public void collectUiResults(Object settingUi, StringBuilder outActions) { if (settingUi instanceof PrefToggle) { ((PrefToggle) settingUi).collectResult(outActions); } } public String getActionLabel(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); return context.getString(value > 0 ? R.string.timedaction_wifi_on : R.string.timedaction_wifi_off); } catch (NumberFormatException e) { // ignore } return null; } public boolean performAction(Context context, String action) { try { int value = Integer.parseInt(action.substring(1)); change(context, value > 0); } catch (Throwable e) { if (DEBUG) Log.e(TAG, "Perform action failed for " + action, e); } return true; } private void change(Context context, boolean enabled) { // This requires two permissions: // android.permission.ACCESS_WIFI_STATE // and android.permission.CHANGE_WIFI_STATE if (DEBUG) Log.d(TAG, "changeWifi: " + (enabled ? "on" : "off")); try { WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (manager == null) { if (DEBUG) Log.w(TAG, "changeWifi: WIFI_SERVICE missing!"); return; } manager.setWifiEnabled(enabled); } catch (Exception e) { if (DEBUG) Log.e(TAG, "Change failed", e); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2010 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.settings; import com.rdrrlabs.example.timer1app.core.actions.PrefPercent; import com.rdrrlabs.example.timer1app.core.actions.PrefToggle; import android.app.Activity; import android.content.Context; //----------------------------------------------- public interface ISetting { /** * Return true if the setting is supported. * <p/> * Implementations may want to cache the value, depending on how * expensive it is to evaluate, knowing that this setting will * be long lived. */ boolean isSupported(Context context); /** * Create the UI to edit the setting. * The UI object is generally something like {@link PrefPercent} * or {@link PrefToggle}. * * @return Null if the UI is not supported for this setting. * Otherwise some king of object that will be later given to * {@link #collectUiResults}. * */ Object createUi(Activity activity, String[] currentActions); /** * Collects the actions to perform based on the choices made * by the user in the UI object from {@link #createUi(Activity, String[])}. * The action is a string that is happened to <code>outActions</code>. * * @param settingUi The object returned by {@link #createUi}. The * implementation must cope with whatever value that {@code createUi} * returns, which can be {@code null}. * @param outActions Buffer where to append the actions generated by * this setting. */ void collectUiResults(Object settingUi, StringBuilder outActions); /** * Returns a human-readable description of the given action. */ String getActionLabel(Context context, String action); /** * Performs the given action. * <p/> * Returns true if the action was (supposedly) performed. * <p/> * Must only return false when it is obvious that the action failed or * that it cannot/must not be carried now, in which case the caller might * want to try to reschedule it later. */ boolean performAction(Context context, String action); }
Java
/* * Project: Timeriffic * Copyright (C) 2012 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.prefs; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import android.content.Context; import android.util.Log; import android.util.SparseArray; import com.rdrrlabs.example.liblabs.serial.SerialKey; import com.rdrrlabs.example.liblabs.serial.SerialReader; import com.rdrrlabs.example.liblabs.serial.SerialWriter; /** * Wrapper around {@link SerialWriter} and {@link SerialReader} to deal with app prefs. * <p/> * Supported types are the minimal required for hour needs: boolean, string and int. * Callers need to ensure that only one instance exists for the same file. * <p/> * Caller initial cycle should be: * - begingReadAsync * - endReadAsync ... this waits for the read the finish. * - read, add or modify data. * - modifying data generates a delayed write (or delays an existing one) * - flushSync must be called by the owner at least once, typically when an activity/app * is paused or about to finish. It forces a write or wait for an existing one to finish. * <p/> * Values cannot be null. * Affecting a value to null is equivalent to removing it from the storage map. * */ public class PrefsStorage { public static class TypeMismatchException extends RuntimeException { private static final long serialVersionUID = -6386235026748640081L; public TypeMismatchException(String key, String expected, Object actual) { super(String.format("Key '%1$s' excepted type %2$s, got %3$s", key, expected, actual.getClass().getSimpleName())); } } private static final String FOOTER = "F0"; private static final String TAG = PrefsStorage.class.getSimpleName(); private static final String HEADER = "SPREFS.1"; private final SerialKey mKeyer = new SerialKey(); private final SparseArray<Object> mData = new SparseArray<Object>(); private final String mFilename; private boolean mDataChanged; private volatile Thread mLoadThread; private boolean mLoadResult; /** * Opens a serial prefs for "filename.sprefs" in the app's dir. * Caller must still read the file before anything happens. * * @param filename Filename. Must not be null or empty. */ public PrefsStorage(String filename) { mFilename = filename; } public String getFilename() { return mFilename; } /** * Starts reading an existing prefs file asynchronously. * Callers <em>must</em> call {@link #endReadAsync()}. * * @param context The {@link Context} to use. */ public void beginReadAsync(Context context) { final Context appContext = context.getApplicationContext(); if (mLoadThread != null) { throw new RuntimeException("Load already pending."); } mLoadThread = new Thread() { @Override public void run() { FileInputStream fis = null; try { fis = appContext.openFileInput(mFilename); mLoadResult = loadStream(fis); } catch (FileNotFoundException e) { // This is an expected error. Log.d(TAG, "fileNotFound"); mLoadResult = true; } catch (Exception e) { Log.d(TAG, "endReadAsync failed", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { // ignore } } } }; mLoadThread.start(); } /** * Makes sure the asynchronous read has finished. * Callers must call this at least once before they access * the underlying storage. * @return The result from the last load operation. */ public boolean endReadAsync() { Thread t = null; synchronized(this) { t = mLoadThread; if (t != null) mLoadThread = null; } if (t != null) { try { t.join(); } catch (InterruptedException e) { Log.w(TAG, e); } } return mLoadResult; } /** * Saves the prefs if they have changed. * @param context The app context. * @return True if prefs could be failed, false otherwise. */ public boolean flushSync(Context context) { if (!mDataChanged) return true; synchronized(this) { if (mDataChanged) { mDataChanged = false; FileOutputStream fos = null; try { fos = context.openFileOutput(mFilename, Context.MODE_PRIVATE); return saveStream(fos); } catch (Exception e) { Log.d(TAG, "flushSync failed", e); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { // ignore } } } } return false; } // --- put public void putInt(String key, int value) { mData.put(mKeyer.encodeNewKey(key), Integer.valueOf(value)); mDataChanged = true; } public void putBool(String key, boolean value) { mData.put(mKeyer.encodeNewKey(key), Boolean.valueOf(value)); mDataChanged = true; } public void putString(String key, String value) { mData.put(mKeyer.encodeNewKey(key), value); mDataChanged = true; } // --- has public boolean hasKey(String key) { return mData.indexOfKey(mKeyer.encodeKey(key)) >= 0; } public boolean hasInt(String key) { Object o = mData.get(mKeyer.encodeKey(key)); return o instanceof Integer; } public boolean hasBool(String key) { Object o = mData.get(mKeyer.encodeKey(key)); return o instanceof Boolean; } public boolean hasString(String key) { Object o = mData.get(mKeyer.encodeKey(key)); return o instanceof String; } // --- get public int getInt(String key, int defValue) { Object o = mData.get(mKeyer.encodeKey(key)); if (o instanceof Integer) { return ((Integer) o).intValue(); } else if (o != null) { throw new TypeMismatchException(key, "int", o); } return defValue; } public boolean getBool(String key, boolean defValue) { Object o = mData.get(mKeyer.encodeKey(key)); if (o instanceof Boolean) { return ((Boolean) o).booleanValue(); } else if (o != null) { throw new TypeMismatchException(key, "boolean", o); } return defValue; } public String getString(String key, String defValue) { Object o = mData.get(mKeyer.encodeKey(key)); if (o instanceof String) { return (String) o; } else if (o != null) { throw new TypeMismatchException(key, "String", o); } return defValue; } // ---- private boolean loadStream(InputStream is) { try { InputStreamReader isr = new InputStreamReader(is, "UTF-8"); BufferedReader br = new BufferedReader(isr, 4096); // get header String line = br.readLine(); if (!HEADER.equals(line)) { Log.d(TAG, "Invalid file format, header missing."); return false; } line = br.readLine(); SerialReader sr = new SerialReader(line); mData.clear(); for (SerialReader.Entry entry : sr) { mData.append(entry.getKey(), entry.getValue()); } line = br.readLine(); if (!FOOTER.equals(line)) { Log.d(TAG, "Invalid file format, footer missing."); return false; } return true; } catch(Exception e) { Log.d(TAG, "Error reading file.", e); } return false; } private boolean saveStream(OutputStream os) { BufferedWriter bw = null; try { OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); bw = new BufferedWriter(osw, 4096); bw.write(HEADER); bw.newLine(); SerialWriter sw = new SerialWriter(); for (int n = mData.size(), i = 0; i < n; i++) { int key = mData.keyAt(i); Object value = mData.valueAt(i); // no need to store null values. if (value == null) continue; if (value instanceof Integer) { sw.addInt(key, ((Integer) value).intValue()); } else if (value instanceof Boolean) { sw.addBool(key, ((Boolean) value).booleanValue()); } else if (value instanceof String) { sw.addString(key, (String) value); } else { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " does not support type " + value.getClass().getSimpleName()); } } bw.write(sw.encodeAsString()); bw.newLine(); bw.write(FOOTER); bw.newLine(); return true; } catch (Exception e) { Log.d(TAG, "Error writing file.", e); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { } } } return false; } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.prefs; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.Log; /** * Manipulates shared preferences. * * Notes: <br/> * - get() methods are not synchronized. <br/> * - set() methods are synchronized on the class object. <br/> * - edit() methods must be wrapped as follows: * * <pre> * synchronized (mPrefs.editLock()) { * Editor e = mPrefs.startEdit(); * try { * mPrefs.editXyz(e, value); * } finally { * mPrefs.endEdit(e, TAG); * } * } * </pre> */ public class PrefsValues { public static final int VERSION = 2; private SharedPreferences mPrefs; public PrefsValues(Context context) { mPrefs = PreferenceManager.getDefaultSharedPreferences(context); } public SharedPreferences getPrefs() { return mPrefs; } public Object editLock() { return PrefsValues.class; } /** Returns a shared pref editor. Must call endEdit() later. */ public Editor startEdit() { return mPrefs.edit(); } /** Commits an open editor. */ public boolean endEdit(Editor e, String tag) { boolean b = e.commit(); if (!b) Log.w(tag, "Prefs.edit.commit failed"); return b; } /** Returns pref version or 0 if not present. */ public int getVersion() { return mPrefs.getInt("version", 0); } public void setVersion() { mPrefs.edit().putInt("version", VERSION).commit(); } public boolean isServiceEnabled() { return mPrefs.getBoolean("enable_serv", true); } /** * Sets the dismiss_intro boolean value. * @return true if value was successfully changed if the prefs */ public boolean setServiceEnabled(boolean checked) { synchronized (editLock()) { return mPrefs.edit().putBoolean("enable_serv", checked).commit(); } } public boolean isIntroDismissed() { return mPrefs.getBoolean("dismiss_intro", false); } /** * Sets the dismiss_intro boolean value. * @return true if value was successfully changed if the prefs */ public boolean setIntroDismissed(boolean dismiss) { synchronized (editLock()) { return mPrefs.edit().putBoolean("dismiss_intro", dismiss).commit(); } } public int getLastIntroVersion() { return mPrefs.getInt("last_intro_vers", 0); } public boolean setLastIntroVersion(int lastIntroVers) { synchronized (editLock()) { return mPrefs.edit().putInt("last_intro_vers", lastIntroVers).commit(); } } public boolean getCheckService() { return mPrefs.getBoolean("check_service", false); } public boolean setCheckService(boolean check) { synchronized (editLock()) { return mPrefs.edit().putBoolean("check_service", check).commit(); } } public String getStatusLastTS() { return mPrefs.getString("last_ts", null); } public void editStatusLastTS(Editor e, String lastTS) { e.putString("last_ts", lastTS); } public String getStatusLastAction() { return mPrefs.getString("last_msg", null); } public void setStatusLastAction(String summary) { synchronized (editLock()) { mPrefs.edit().putString("last_msg", summary).commit(); } } public String getStatusNextTS() { return mPrefs.getString("next_ts", null); } public void editStatusNextTS(Editor e, String nextTS) { e.putString("next_ts", nextTS); } public String getStatusNextAction() { return mPrefs.getString("next_msg", null); } public void editStatusNextAction(Editor e, String summary) { e.putString("next_msg", summary); } public long getLastScheduledAlarm() { return mPrefs.getLong("last_alarm", 0); } public void editLastScheduledAlarm(Editor e, long timeMs) { e.putLong("last_alarm", timeMs); } public String getLastExceptions() { return mPrefs.getString("last_exceptions", null); } public void setLastExceptions(String s) { synchronized (editLock()) { mPrefs.edit().putString("last_exceptions", s).commit(); } } public String getLastActions() { return mPrefs.getString("last_actions", null); } public void setLastActions(String s) { synchronized (editLock()) { mPrefs.edit().putString("last_actions", s).commit(); } } public enum GlobalToggleAnimMode { NO_ANIM, SLOW, FAST } public GlobalToggleAnimMode getGlobalToggleAnim() { // "fast" is the default String s = mPrefs.getString("globaltoggle_anim", "fast"); if ("no_anim".equals(s)) { return GlobalToggleAnimMode.NO_ANIM; } else if ("slow".equals(s)) { return GlobalToggleAnimMode.SLOW; } return GlobalToggleAnimMode.FAST; } public boolean getUseDataToggle() { return mPrefs.getBoolean("use_data_toggle", false); } public boolean setUseDataToggle(boolean check) { synchronized (editLock()) { return mPrefs.edit().putBoolean("use_data_toggle", check).commit(); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.prefs; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class Oldv1PrefsValues { public static final String KEY_START_HOUR = "start_hour"; public static final String KEY_END_HOUR = "end_hour"; public static final int VERSION = 0; private SharedPreferences mPrefs; public Oldv1PrefsValues(Context context) { mPrefs = PreferenceManager.getDefaultSharedPreferences(context); } public SharedPreferences getPrefs() { return mPrefs; } public boolean isServiceEnabled() { return mPrefs.getBoolean("enable_serv", true); } /** * Sets the dismiss_intro boolean value. * @return true if value was successfully changed if the prefs */ public boolean setServiceEnabled(boolean checked) { return mPrefs.edit().putBoolean("enable_serv", checked).commit(); } /** Returns the start hour-min or -1 if not present. */ public int startHourMin() { try { return mPrefs.getInt(KEY_START_HOUR, -1); } catch (ClassCastException e) { // The field used to be a String, so it could fail here String s = mPrefs.getString(KEY_START_HOUR, null); return s == null ? -1 : parseHoursMin(s); } } /** Returns the stop hour-min or -1 if not present. */ public int stopHourMin() { try { return mPrefs.getInt(KEY_END_HOUR, -1); } catch (ClassCastException e) { // The field used to be a String, so it could fail here String s = mPrefs.getString(KEY_END_HOUR, null); return s == null ? -1 : parseHoursMin(s); } } private int parseHoursMin(String text) { int hours = 0; int minutes = 0; String[] numbers = text.trim().split(":"); if (numbers.length >= 1) hours = parseNumber(numbers[0], 23); if (numbers.length >= 2) minutes = parseNumber(numbers[1], 59); return hours*60 + minutes; } private static int parseNumber(String string, int maxValue) { try { int n = Integer.parseInt(string); if (n < 0) return 0; if (n > maxValue) return maxValue; return n; } catch (Exception e) { // ignore } return 0; } public boolean startMute() { return mPrefs.getBoolean("start_mute", true); } public boolean startVibrate() { return mPrefs.getBoolean("start_vibrate", true); } public boolean stopMute() { return mPrefs.getBoolean("end_mute", false); } public boolean stopVibrate() { return mPrefs.getBoolean("end_vibrate", false); } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB; public class EditProfileUI extends ExceptionHandlerUI { public static final String TAG = EditProfileUI.class.getSimpleName(); /** Extra long with the profile id (not index) to edit. */ public static final String EXTRA_PROFILE_ID = "prof_id"; private EditText mNameField; private CheckBox mEnabledCheck; private long mProfId; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_profile); setTitle(R.string.editprofile_title); Intent intent = getIntent(); mProfId = intent.getExtras().getLong(EXTRA_PROFILE_ID); Log.d(TAG, String.format("edit prof_id: %08x", mProfId)); if (mProfId == 0) { Log.e(TAG, "profile id not found in intent."); finish(); return; } // get profiles db helper ProfilesDB profilesDb = new ProfilesDB(); profilesDb.onCreate(this); // get cursor String prof_id_select = String.format("%s=%d", Columns.PROFILE_ID, mProfId); Cursor c = profilesDb.query( -1, // id // projection, a.k.a. the list of columns to retrieve from the db new String[] { Columns.PROFILE_ID, Columns.DESCRIPTION, Columns.IS_ENABLED }, prof_id_select, // selection null, // selectionArgs null // sortOrder ); try { if (!c.moveToFirst()) { Log.e(TAG, "cursor is empty: " + prof_id_select); finish(); return; } // get UI widgets mNameField = (EditText) findViewById(R.id.name); mEnabledCheck = (CheckBox) findViewById(R.id.enabled); // get column indexes int descColIndex = c.getColumnIndexOrThrow(Columns.DESCRIPTION); int enColIndex = c.getColumnIndexOrThrow(Columns.IS_ENABLED); // fill in UI from cursor data mNameField.setText(c.getString(descColIndex)); mEnabledCheck.setChecked(c.getInt(enColIndex) != 0); } finally { c.close(); profilesDb.onDestroy(); } Button accept = (Button) findViewById(R.id.ok); accept.setOnClickListener(new OnClickListener() { public void onClick(View v) { accept(); } }); } private void accept() { ProfilesDB profilesDb = new ProfilesDB(); try { profilesDb.onCreate(this); profilesDb.updateProfile( mProfId, mNameField.getText().toString(), mEnabledCheck.isChecked()); } finally { profilesDb.onDestroy(); } finish(); } @Override protected void onPause() { super.onPause(); // do nothing, discard changes } @Override protected void onStop() { super.onStop(); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.regex.Pattern; import android.app.Application; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Handler.Callback; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.RadioGroup.OnCheckedChangeListener; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.app.TimerifficApp; import com.rdrrlabs.example.timer1app.app.UpdateReceiver; import com.rdrrlabs.example.timer1app.app.UpdateService; import com.rdrrlabs.example.timer1app.core.app.AppId; import com.rdrrlabs.example.timer1app.core.app.ApplySettings; import com.rdrrlabs.example.timer1app.core.app.BackupWrapper; import com.rdrrlabs.example.timer1app.core.app.CoreStrings; import com.rdrrlabs.example.timer1app.core.app.CoreStrings.Strings; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; import com.rdrrlabs.example.timer1app.core.prefs.PrefsStorage; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.profiles1.BaseHolder; import com.rdrrlabs.example.timer1app.core.profiles1.ProfileHeaderHolder; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl; import com.rdrrlabs.example.timer1app.core.profiles1.TimedActionHolder; import com.rdrrlabs.example.liblabs.serial.SerialReader; import com.rdrrlabs.example.timer1app.core.settings.AirplaneSetting; import com.rdrrlabs.example.timer1app.core.settings.ApnDroidSetting; import com.rdrrlabs.example.timer1app.core.settings.BluetoothSetting; import com.rdrrlabs.example.timer1app.core.settings.BrightnessSetting; import com.rdrrlabs.example.timer1app.core.settings.DataSetting; import com.rdrrlabs.example.timer1app.core.settings.RingerSetting; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; import com.rdrrlabs.example.timer1app.core.settings.SyncSetting; import com.rdrrlabs.example.timer1app.core.settings.VibrateSetting; import com.rdrrlabs.example.timer1app.core.settings.VolumeSetting; import com.rdrrlabs.example.timer1app.core.settings.WifiSetting; import com.rdrrlabs.example.timer1app.core.utils.AgentWrapper; import com.rdrrlabs.example.timer1app.core.utils.ApplyVolumeReceiver; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper; import com.rdrrlabs.example.timer1app.core.utils.VolumeChange; /** * Screen to generate an error report. */ public class ErrorReporterUI extends ExceptionHandlerUI { private static final boolean DEBUG = true; public static final String TAG = ErrorReporterUI.class.getSimpleName(); /** Boolean extra: True if this is generated from an exception, false * if generated from a user request. */ public static final String EXTRA_IS_EXCEPTION = ErrorReporterUI.class.getPackage().getName() + "_isException"; // TODO more UTs private static final int MSG_REPORT_COMPLETE = 1; private AgentWrapper mAgentWrapper; private Handler mHandler; private boolean mAbortReport; private String mAppName; private String mAppVersion; private boolean mIsException; private Button mButtonGen; private Button mButtonPrev; private Button mButtonNext; private View mUserFrame; private RadioGroup mRadioGroup; private WebView mWebView; private EditText mUserText; private class JSErrorInfo { private final int mNumExceptions; private final int mNumActions; public JSErrorInfo(int numExceptions, int numActions) { mNumExceptions = numExceptions; mNumActions = numActions; } @SuppressWarnings("unused") public int getNumExceptions() { return mNumExceptions; } @SuppressWarnings("unused") public int getNumActions() { return mNumActions; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.error_report); mAppName = getString(R.string.app_name); setTitle(getString(R.string.errorreport_title).replaceAll("\\$APP", mAppName)); Intent i = getIntent(); mIsException = i == null ? false : i.getBooleanExtra(EXTRA_IS_EXCEPTION, false); mButtonGen = (Button) findViewById(R.id.generate); mButtonPrev = (Button) findViewById(R.id.prev); mButtonNext = (Button) findViewById(R.id.next); mUserFrame = findViewById(R.id.user_frame); mRadioGroup = (RadioGroup) findViewById(R.id.radio_group); mWebView = (WebView) findViewById(R.id.web); mUserText = (EditText) findViewById(R.id.user_text); adjustUserHint(mUserText); PackageManager pm = getPackageManager(); if (pm != null) { PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); mAppVersion = pi.versionName; if (mAppVersion == null) { mAppVersion = ""; } else { // Remove anything after the first space int pos = mAppVersion.indexOf(' '); if (pos > 0 && pos < mAppVersion.length() - 1) { mAppVersion = mAppVersion.substring(0, pos); } } } catch (Exception ignore) { // getPackageName typically throws NameNotFoundException } } if (mWebView == null) { if (DEBUG) Log.e(TAG, "Missing web view"); finish(); } // Make the webview transparent (for background gradient) mWebView.setBackgroundColor(0x00000000); String file = selectFile("error_report"); file = file.replaceAll("\\$APP", mAppName); loadFile(mWebView, file); setupJavaScript(mWebView); setupListeners(); setupHandler(); int page = mIsException ? 2 : 1; selectPage(page); updateButtons(); } /** * Get the text hint from the text field. If we current translation has a hint2 text * (which typically says "Please write comment in English" and is going to be empty * in English), then we append that text to the hint. */ private void adjustUserHint(EditText userText) { String str2 = getString(R.string.errorreport_user_hint_english); if (str2 == null) return; str2 = str2.trim(); if (str2.length() == 0) return; String str1 = userText.getHint().toString(); str1 = str1.trim(); if (str1.length() > 0) str1 += " "; userText.setHint(str1 + str2); } @Override protected void onResume() { super.onResume(); mAgentWrapper = new AgentWrapper(); mAgentWrapper.start(this); mAgentWrapper.event(AgentWrapper.Event.OpenIntroUI); } @Override protected void onPause() { super.onPause(); // If the generator thread is still running, just set the abort // flag and let the thread terminate itself. mAbortReport = true; mAgentWrapper.stop(this); } private String selectFile(String baseName) { String file; // Compute which file we want to display, i.e. try to select // one that matches baseName-LocaleCountryName.html or default // to intro.html Locale lo = Locale.getDefault(); String lang = lo.getLanguage(); String country = lo.getCountry(); if (lang != null && lang.length() > 2) { // There's a bug in the SDK "Locale Setup" app in Android 1.5/1.6 // where it sets the full locale such as "en_US" in the languageCode // field of the Locale instead of splitting it correctly. So we do it // here. int pos = lang.indexOf('_'); if (pos > 0 && pos < lang.length() - 1) { country = lang.substring(pos + 1); lang = lang.substring(0, pos); } } if (lang != null && lang.length() == 2) { AssetManager am = getResources().getAssets(); // Try with both language and country, e.g. -en-US, -zh-CN if (country != null && country.length() == 2) { file = baseName + "-" + lang.toLowerCase() + "-" + country.toUpperCase() + ".html"; if (checkFileExists(am, file)) { return file; } } // Try to fall back on just language, e.g. -zh, -fr file = baseName + "-" + lang.toLowerCase() + ".html"; if (checkFileExists(am, file)) { return file; } } if (!"en".equals(lang)) { if (DEBUG) Log.d(TAG, "Language not found: " + lang + "+" + country); } // This one just has to exist or we'll crash n' burn on the 101. return baseName + ".html"; } private boolean checkFileExists(AssetManager am, String filename) { InputStream is = null; try { is = am.open(filename); return is != null; } catch (IOException e) { // pass } finally { if (is != null) { try { is.close(); } catch (IOException e) { // pass } } } return false; } private void loadFile(final WebView wv, String file) { wv.loadUrl("file:///android_asset/" + file); wv.setFocusable(true); wv.setFocusableInTouchMode(true); wv.requestFocus(); } private void setupJavaScript(final WebView wv) { // TODO get numbers int num_ex = ExceptionHandler.getNumExceptionsInLog(this); int num_act = ApplySettings.getNumActionsInLog(this); // Inject a JS method to set the version JSErrorInfo js = new JSErrorInfo(num_ex, num_act); wv.getSettings().setJavaScriptEnabled(true); wv.addJavascriptInterface(js, "JSErrorInfo"); } private void setupListeners() { if (mButtonGen != null) { mButtonGen.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Start inderterminate progress bar ProgressBar progress = (ProgressBar) findViewById(R.id.progress); if (progress != null) { progress.setVisibility(View.VISIBLE); progress.setIndeterminate(true); } // Gray generate button (to avoid user repeasting it) mButtonGen.setEnabled(false); mAbortReport = false; try { Thread t = new Thread(new ReportGenerator(), "ReportGenerator"); t.start(); } catch (Throwable t) { // We can possibly get a VerifyError from Dalvik here // if the thread can't link (e.g. because it's using // an unsupported API.). Normally we wouldn't care but // we don't want the error reporter to crash itself. Toast.makeText(ErrorReporterUI.this, "Failed to generate report: " + t.toString(), Toast.LENGTH_LONG).show(); } } }); } if (mButtonPrev != null) { mButtonPrev.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (!mIsException) selectPage(1); } }); } if (mButtonNext != null) { mButtonNext.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectPage(2); } }); } if (mRadioGroup != null) { mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { updateButtons(); } }); } if (mUserText != null) { mUserText.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // pass } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // pass } public void afterTextChanged(Editable s) { updateButtons(); } }); } } private void setupHandler() { mHandler = new Handler(new Callback() { public boolean handleMessage(Message msg) { if (msg.what == MSG_REPORT_COMPLETE) { try { // Get the report associated with the message String report = (String) msg.obj; // Stop inderterminate progress bar ProgressBar progress = (ProgressBar) findViewById(R.id.progress); if (progress != null) { progress.setIndeterminate(false); progress.setVisibility(View.GONE); } if (report != null) { TimerifficApp ta = TimerifficApp.getInstance(getApplicationContext()); CoreStrings str = ta.getCore().getCoreStrings(); // Prepare mailto and subject. String to = str.format(Strings.ERR_UI_MAILTO, mAppName).trim(); to += "@"; to += str.get(Strings.ERR_UI_DOMTO).replace("/", "."); to = to.replaceAll("[ _]", "").toLowerCase(); StringBuilder sb = new StringBuilder(); sb.append('[').append(mAppName.trim()).append("] "); sb.append(getReportType().trim()); sb.append(" [").append(ta.getIssueId()); PrefsStorage ps = ta.getPrefsStorage(); if (ps.endReadAsync()) { sb.append('-').append(ps.getInt("iss_id_count", -1)); } sb.append(']'); String subject = sb.toString(); // Generate the intent to send an email Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_EMAIL, new String[] { to }); i.putExtra(Intent.EXTRA_SUBJECT, subject); i.putExtra(Intent.EXTRA_TEXT, report); i.setType("message/rfc822"); try { startActivity(i); } catch (ActivityNotFoundException e) { // This is likely to happen if there's no mail app. Toast.makeText(getApplicationContext(), R.string.errorreport_nomailapp, Toast.LENGTH_LONG).show(); Log.d(TAG, "No email/gmail app found", e); } catch (Exception e) { // This is unlikely to happen. Toast.makeText(getApplicationContext(), "Send email activity failed: " + e.toString(), Toast.LENGTH_LONG).show(); Log.d(TAG, "Send email activity failed", e); } // Finish this activity. finish(); } } finally { // We're not supposed to get there since there's a finish // above. So maybe something failed and we should let the // user retry, so in any case, ungray generate button. if (mButtonGen != null) { mButtonGen.setEnabled(true); } } } return false; } }); } private void updateButtons() { if (mButtonNext != null && mUserText != null && mRadioGroup != null) { mButtonNext.setEnabled( mRadioGroup.getCheckedRadioButtonId() != -1 && mUserText.getText().length() > 0); } } private void selectPage(int i) { if (i < 0 || i > 2) return; // Page 1: // - scrollview "user_frame" // - button "next" (enabled if radio choice + text not empty) // - hide prev, gen, web // // Page 2: // - show gen, web // - hide prev if mIsException, otherwise show // - hide user_frame, next int visPage1 = i == 1 ? View.VISIBLE : View.GONE; int visPage2 = i == 2 ? View.VISIBLE : View.GONE; mButtonPrev.setVisibility(mIsException ? View.GONE : visPage2); mButtonNext.setVisibility(visPage1); mButtonGen.setVisibility(visPage2); mUserFrame.setVisibility(visPage1); mWebView.setVisibility(visPage2); } /** Returns a non-translated string for report type. */ private String getReportType() { if (mIsException) { return "Exception Report (Force Close)"; } int id = mRadioGroup == null ? -1 : mRadioGroup.getCheckedRadioButtonId(); if (id == R.id.radio_err) { return "User Error Report"; } else if (id == R.id.radio_fr) { return "User Feature Request"; } return "Unknown Report Type"; } /** * Generates the error report, with the following sections: * - Request user to enter some information (translated, rest is not) * - Device information (nothing user specific) * - Profile list summary * - Recent Exceptions * - Recent actions * - Recent logcat */ private class ReportGenerator implements Runnable { public void run() { Context c = ErrorReporterUI.this.getApplicationContext(); PrefsValues pv = new PrefsValues(c); StringBuilder sb = new StringBuilder(); addHeader(sb, c); addUserFeedback(sb); addTopInfo(sb); addIssueId(sb); addAndroidBuildInfo(sb); if (!mAbortReport) addProfiles(sb, c); if (!mAbortReport) addLastExceptions(sb, pv); if (!mAbortReport) addLastActions(sb, pv); if (!mAbortReport) addLogcat(sb); // -- Report complete // We're done with the report. Ping back the activity using // a message to get back to the UI thread. if (!mAbortReport) { Message msg = mHandler.obtainMessage(MSG_REPORT_COMPLETE, sb.toString()); mHandler.sendMessage(msg); } } private void addHeader(StringBuilder sb, Context c) { try { String s = c.getString(R.string.errorreport_emailheader); s = s.replaceAll(Pattern.quote("$APP"), mAppName); sb.append(s.trim().replace('/', '\n')).append("\n"); } catch (Exception ignore) { } } private void addIssueId(StringBuilder sb) { Application app = getApplication(); if (app instanceof TimerifficApp) { TimerifficApp ta = (TimerifficApp) app; sb.append("\n## Issue Id: ").append(ta.getIssueId()); PrefsStorage ps = ta.getPrefsStorage(); if (ps.endReadAsync()) { int count = ps.getInt("iss_id_count", 0); count += 1; sb.append(" - ").append(count); ps.putInt("iss_id_count", count); ps.flushSync(getApplicationContext()); } } } private void addUserFeedback(StringBuilder sb) { sb.append("\n## Report Type: ").append(getReportType()); if (!mIsException) { sb.append("\n\n## User Comments:\n"); if (mUserText != null) sb.append(mUserText.getText()); sb.append("\n"); } } private void addTopInfo(StringBuilder sb) { sb.append(String.format("\n## App: %s %s\n", mAppName, mAppVersion)); sb.append(String.format("## Locale: %s\n", Locale.getDefault().toString())); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"); String date = df.format(new Date(System.currentTimeMillis())); sb.append(String.format("## Log Date: %s\n", date)); } private void addAndroidBuildInfo(StringBuilder sb) { sb.append("\n## Android Device ##\n\n"); try { // Build.MANUFACTURER is only available starting at API 4 String manufacturer = "--"; try { Field f = Build.class.getField("MANUFACTURER"); manufacturer = (String) f.get(null /*static*/); } catch (Exception ignore) { } sb.append(String.format("Device : %s (%s %s)\n", Build.MODEL, manufacturer, Build.DEVICE)); sb.append(String.format("Android: %s (API %s)\n", Build.VERSION.RELEASE, Build.VERSION.SDK)); sb.append(String.format("Build : %s\n", Build.FINGERPRINT)); } catch (Exception ignore) { } } private void addLastExceptions(StringBuilder sb, PrefsValues prefs) { sb.append("\n## Recent Exceptions ##\n\n"); String s = prefs.getLastExceptions(); if (s == null) { sb.append("None\n"); } else { sb.append(s); } } private void addLastActions(StringBuilder sb, PrefsValues prefs) { sb.append("\n## Recent Actions ##\n\n"); String s = prefs.getLastActions(); if (s == null) { sb.append("None\n"); } else { sb.append(s); } } private void addProfiles(StringBuilder sb, Context c) { sb.append("\n## Profiles Summary ##\n\n"); try { ProfilesDB profilesDb = new ProfilesDB(); try { profilesDb.onCreate(c); String[] p = profilesDb.getProfilesDump(); for (String s : p) { sb.append(s); } } finally { profilesDb.onDestroy(); } } catch (Exception ignore) { // ignore } } private void addLogcat(StringBuilder sb) { sb.append(String.format("\n## %s Logcat ##\n\n", mAppName)); BackupWrapper backupWrapper = new BackupWrapper(getApplicationContext()); String sTimerifficBackupAgent_TAG = backupWrapper.getTAG_TimerifficBackupAgent(); if (sTimerifficBackupAgent_TAG == null) { sTimerifficBackupAgent_TAG = ""; } else { sTimerifficBackupAgent_TAG += ":D"; } String[] cmd = new String[] { "logcat", "-d", // dump log and exits // actions package // app package ApplySettings.TAG + ":D", UpdateReceiver.TAG + ":D", UpdateService.TAG + ":D", AppId.TAG + ":D", BackupWrapper.TAG + ":D", sTimerifficBackupAgent_TAG, // error package ExceptionHandler.TAG + ":D", // prefs package // profiles package BaseHolder.TAG + ":D", ProfileHeaderHolder.TAG + ":D", ProfilesDB.TAG + ":D", TimedActionHolder.TAG + ":D", ProfilesUiImpl.TAG + ":D", // serial package SerialReader.TAG + ":D", // settings package AirplaneSetting.TAG + ":D", ApnDroidSetting.TAG + ":D", BluetoothSetting.TAG + ":D", BrightnessSetting.TAG + ":D", DataSetting.TAG + ":D", RingerSetting.TAG + ":D", SettingFactory.TAG + ":D", SyncSetting.TAG + ":D", VibrateSetting.TAG + ":D", VolumeSetting.TAG + ":D", WifiSetting.TAG + ":D", // utils package AgentWrapper.TAG + ":D", SettingsHelper.TAG + ":D", VolumeChange.TAG + ":D", ApplyVolumeReceiver.TAG + ":D", // ui package ChangeBrightnessUI.TAG + ":D", EditActionUI.TAG + ":D", EditProfileUI.TAG + ":D", ErrorReporterUI.TAG + ":D", IntroUI.TAG + ":D", "FlurryAgent:W", //-- too verbose --"*:I", // all other tags in info mode or better "*:S", // silence all tags we don't want }; try { Process p = Runtime.getRuntime().exec(cmd); InputStreamReader isr = null; BufferedReader br = null; try { InputStream is = p.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line = null; // Make sure this doesn't take forever. // We cut after 30 seconds which is already very long. long maxMs = System.currentTimeMillis() + 30*1000; int count = 0; while (!mAbortReport && (line = br.readLine()) != null) { sb.append(line).append("\n"); // check time limit once in a while count++; if (count > 50) { if (System.currentTimeMillis() > maxMs) { // This may or may not work. // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4485742 p.destroy(); break; } count = 0; } } } finally { if (br != null) { br.close(); } if (isr != null) { isr.close(); } } } catch (IOException e) { Log.d(TAG, "Logcat exec failed", e); } catch (Throwable ignore) { } } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.graphics.Paint.FontMetrics; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import com.rdrrlabs.example.timer1app.base.R; //----------------------------------------------- /** */ public class GlobalStatus extends View { private Bitmap mAccentLeft; private Matrix mAccentRightMatrix; private Paint mPaintLast; private Paint mPaintNext; private Paint mPaintTimestamp; private Paint mPaintDesc; private float mYLast; private float mYNext; private float mYNextDesc; private float mYLastDesc; private int mXLastNext; private int mXTsDesc; private String mTextLast; private String mTextNext; private String mTextLastTs; private String mTextLastDesc; private String mTextNextTs; private String mTextNextDesc; private Paint mDummyPaint; private Runnable mVisibilityChangedCallback; public GlobalStatus(Context context, AttributeSet attrs) { super(context, attrs); mAccentLeft = getResBitmap(R.drawable.globalstatus_accent_lines_left); // Fix to make GLE happy mDummyPaint = new Paint(); int textFlags = Paint.ANTI_ALIAS_FLAG + Paint.SUBPIXEL_TEXT_FLAG; mPaintLast = new Paint(textFlags); mPaintLast.setColor(0xFF70D000); mPaintLast.setTextSize(convertDipToPixel(16)); mPaintNext = new Paint(textFlags); mPaintNext.setColor(0xFF392394); mPaintNext.setTextSize(convertDipToPixel(16)); mPaintTimestamp = new Paint(textFlags); mPaintTimestamp.setColor(0xFFCCCCCC); mPaintTimestamp.setTextSize(convertDipToPixel(12)); mPaintDesc = new Paint(textFlags); mPaintDesc.setColor(0xFF181818); mPaintDesc.setTextSize(convertDipToPixel(12)); FontMetrics fmLast = mPaintLast.getFontMetrics(); FontMetrics fmTs = mPaintTimestamp.getFontMetrics(); mYLast = -1 * fmLast.top; mYLastDesc = mYLast + fmTs.bottom - fmTs.top; mYNext = mYLast - fmLast.ascent + fmTs.descent; mYNextDesc = mYNext + fmTs.bottom - fmTs.top; mTextLast = context.getString(R.string.globalstatus_last); mTextNext = context.getString(R.string.globalstatus_next); // use width from global toggle anim to align text Bitmap logoAnim = getResBitmap(R.drawable.globaltoggle_frame1); mXLastNext = logoAnim.getWidth(); mXTsDesc = mXLastNext + 5 + (int) (Math.max(mPaintLast.measureText(mTextLast), mPaintNext.measureText(mTextNext))); } /** Convert the dips to pixels */ private float convertDipToPixel(float dip) { final float scale = getContext().getResources().getDisplayMetrics().density; return dip * scale; } public void setTextLastTs(String textLastTs) { mTextLastTs = textLastTs; } public void setTextLastDesc(String lastDesc) { mTextLastDesc = lastDesc; } public void setTextNextTs(String textNextTs) { mTextNextTs = textNextTs; } public void setTextNextDesc(String nextDesc) { mTextNextDesc = nextDesc; } private Bitmap getResBitmap(int bmpResId) { Drawable d = getResources().getDrawable(bmpResId); int w = d.getIntrinsicWidth(); int h = d.getIntrinsicHeight(); Bitmap bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888); Canvas c = new Canvas(bmp); d.setBounds(0, 0, w - 1, h - 1); d.draw(c); return bmp; } @Override protected int getSuggestedMinimumHeight() { return mAccentLeft.getHeight(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { heightMeasureSpec = MeasureSpec.makeMeasureSpec(getSuggestedMinimumHeight(), MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mAccentRightMatrix = new Matrix(); mAccentRightMatrix.preTranslate(w, 0); mAccentRightMatrix.preScale(-1, 1); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); try { canvas.drawBitmap(mAccentLeft, 0, 0, mDummyPaint); canvas.drawBitmap(mAccentLeft, mAccentRightMatrix, mDummyPaint); canvas.drawText(mTextLast, mXLastNext, mYLast, mPaintLast); canvas.drawText(mTextNext, mXLastNext, mYNext, mPaintNext); if (mTextLastTs != null && mTextLastTs.length() > 0) { canvas.drawText(mTextLastTs, mXTsDesc, mYLast, mPaintTimestamp); } if (mTextLastDesc != null && mTextLastDesc.length() > 0) { canvas.drawText(mTextLastDesc, mXTsDesc, mYLastDesc, mPaintDesc); } if (mTextNextTs != null && mTextNextTs.length() > 0) { canvas.drawText(mTextNextTs, mXTsDesc, mYNext, mPaintTimestamp); } if (mTextNextDesc != null && mTextNextDesc.length() > 0) { canvas.drawText(mTextNextDesc, mXTsDesc, mYNextDesc, mPaintDesc); } } catch (UnsupportedOperationException e) { // Ignore, for GLE } } @Override protected void onWindowVisibilityChanged(int visibility) { if (mVisibilityChangedCallback != null && visibility == View.VISIBLE) { mVisibilityChangedCallback.run(); } super.onWindowVisibilityChanged(visibility); } public void setWindowVisibilityChangedCallback(Runnable visibilityChangedCallback) { mVisibilityChangedCallback = visibilityChangedCallback; } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import android.app.Application; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ProgressBar; import android.widget.CompoundButton.OnCheckedChangeListener; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.app.TimerifficApp; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.utils.AgentWrapper; /** * Screen with the introduction text. */ public class IntroUI extends ExceptionHandlerUI { private static final boolean DEBUG = true; public static final String TAG = IntroUI.class.getSimpleName(); public static final String EXTRA_NO_CONTROLS = "no-controls"; private AgentWrapper mAgentWrapper; private class JSTimerifficVersion { private String mVersion; private String mIntroFile; public JSTimerifficVersion(String introFile) { mIntroFile = introFile; } public String longVersion() { if (mVersion == null) { PackageManager pm = getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); mVersion = pi.versionName; if (mVersion == null) { mVersion = ""; } else { // Remove anything after the first space int pos = mVersion.indexOf(' '); if (pos > 0 && pos < mVersion.length() - 1) { mVersion = mVersion.substring(0, pos); } } } catch (NameNotFoundException e) { mVersion = ""; // failed, ignored } } return mVersion; } public String shortVersion() { String v = longVersion(); if (v != null) { v = v.substring(0, v.lastIndexOf('.')); } return v; } @SuppressWarnings("unused") public String introFile() { StringBuilder sb = new StringBuilder(mIntroFile); sb.append(" (").append(Locale.getDefault().toString()).append(')'); Application app = getApplication(); if (app instanceof TimerifficApp) { sb.append(" [").append(((TimerifficApp) app).getIssueId()).append(']'); } return sb.toString(); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intro); String introFile = selectFile("intro"); JSTimerifficVersion jsVersion = new JSTimerifficVersion(introFile); String title = getString(R.string.intro_title, jsVersion.shortVersion()); setTitle(title); final WebView wv = (WebView) findViewById(R.id.web); if (wv == null) { if (DEBUG) Log.d(TAG, "Missing web view"); finish(); } // Make the webview transparent (for background gradient) wv.setBackgroundColor(0x00000000); // Inject a JS method to set the version wv.getSettings().setJavaScriptEnabled(true); wv.addJavascriptInterface(jsVersion, "JSTimerifficVersion"); loadFile(wv, introFile); setupProgressBar(wv); setupWebViewClient(wv); setupButtons(); } @Override protected void onResume() { super.onResume(); mAgentWrapper = new AgentWrapper(); mAgentWrapper.start(this); mAgentWrapper.event(AgentWrapper.Event.OpenIntroUI); } @Override protected void onPause() { super.onPause(); mAgentWrapper.stop(this); } private String selectFile(String baseName) { String file; // Compute which file we want to display, i.e. try to select // one that matches baseName-LocaleCountryName.html or default // to intro.html Locale lo = Locale.getDefault(); String lang = lo.getLanguage(); String country = lo.getCountry(); if (lang != null && lang.length() > 2) { // There's a bug in the SDK "Locale Setup" app in Android 1.5/1.6 // where it sets the full locale such as "en_US" in the languageCode // field of the Locale instead of splitting it correctly. So we do it // here. int pos = lang.indexOf('_'); if (pos > 0 && pos < lang.length() - 1) { country = lang.substring(pos + 1); lang = lang.substring(0, pos); } } if (lang != null && lang.length() == 2) { AssetManager am = getResources().getAssets(); // Try with both language and country, e.g. -en-US, -zh-CN if (country != null && country.length() == 2) { file = baseName + "-" + lang.toLowerCase() + "-" + country.toUpperCase() + ".html"; if (checkFileExists(am, file)) { if (DEBUG) Log.d(TAG, String.format("Locale(%s,%s) => %s", lang, country, file)); return file; } } // Try to fall back on just language, e.g. -zh, -fr file = baseName + "-" + lang.toLowerCase() + ".html"; if (checkFileExists(am, file)) { if (DEBUG) Log.d(TAG, String.format("Locale(%s) => %s", lang, file)); return file; } } if (!"en".equals(lang)) { if (DEBUG) Log.d(TAG, String.format("Language not found for %s-%s (Locale %s)", lang, country, lo.toString())); } // This one just has to exist or we'll crash n' burn on the 101. return baseName + ".html"; } private boolean checkFileExists(AssetManager am, String filename) { InputStream is = null; try { is = am.open(filename); return is != null; } catch (IOException e) { // pass } finally { if (is != null) { try { is.close(); } catch (IOException e) { // pass } } } return false; } private void loadFile(final WebView wv, String file) { wv.loadUrl("file:///android_asset/" + file); wv.setFocusable(true); wv.setFocusableInTouchMode(true); wv.requestFocus(); } private void setupProgressBar(final WebView wv) { final ProgressBar progress = (ProgressBar) findViewById(R.id.progress); if (progress != null) { wv.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { progress.setProgress(newProgress); progress.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE); } }); } } private void setupWebViewClient(final WebView wv) { wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.endsWith("/#new")) { wv.loadUrl("javascript:location.href=\"#new\""); return true; } else if (url.endsWith("/#known")) { wv.loadUrl("javascript:location.href=\"#known\""); return true; } else { // For URLs that are not ours, including market: URLs // just invoke the default view activity (e.g. Browser // or Market app) Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); try { startActivity(intent); } catch (ActivityNotFoundException e) { // ignore. just means this device has no Market or // Browser app... ignore it. } return true; } } }); } private void setupButtons() { boolean hideControls = false; Intent i = getIntent(); if (i != null) { Bundle e = i.getExtras(); if (e != null) hideControls = e.getBoolean(EXTRA_NO_CONTROLS); } CheckBox dismiss = (CheckBox) findViewById(R.id.dismiss); if (dismiss != null) { if (hideControls) { dismiss.setVisibility(View.GONE); } else { final PrefsValues pv = new PrefsValues(this); dismiss.setChecked(pv.isIntroDismissed()); dismiss.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { pv.setIntroDismissed(isChecked); } }); } } Button cont = (Button) findViewById(R.id.cont); if (cont != null) { if (hideControls) { cont.setVisibility(View.GONE); } else { cont.setOnClickListener(new OnClickListener() { public void onClick(View v) { // close activity finish(); } }); } } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.Preference.OnPreferenceChangeListener; import android.view.WindowManager; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; /** * Displays preferences */ public class PrefsUI extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Have the system blur any windows behind this one. getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); setTitle(R.string.prefs_title); addPreferencesFromResource(R.xml.prefs); Preference useDataTogglePref = findPreference("use_data_toggle"); if (useDataTogglePref != null) { useDataTogglePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { SettingFactory.getInstance().forgetSetting(Columns.ACTION_DATA); return true; } }); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public interface IActivityDelegate<T> { public void onCreate(Bundle savedInstanceState); public void onResume(); public void onPause(); public void onStop(); public void onRestoreInstanceState(Bundle savedInstanceState); public void onSaveInstanceState(Bundle outState); public void onDestroy(); public void onActivityResult(int requestCode, int resultCode, Intent data); public Dialog onCreateDialog(int id); public boolean onContextItemSelected(MenuItem item); public void onCreateOptionsMenu(Menu menu); public boolean onOptionsItemSelected(MenuItem item); }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnDismissListener; import android.database.Cursor; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.util.SparseArray; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.CheckBox; import android.widget.ScrollView; import android.widget.TextView; import android.widget.TimePicker; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.PrefBase; import com.rdrrlabs.example.timer1app.core.actions.PrefEnum; import com.rdrrlabs.example.timer1app.core.actions.PrefPercent; import com.rdrrlabs.example.timer1app.core.actions.PrefPercentDialog; import com.rdrrlabs.example.timer1app.core.actions.TimedActionUtils; import com.rdrrlabs.example.timer1app.core.profiles1.Columns; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; import com.rdrrlabs.example.timer1app.core.utils.AgentWrapper; import com.rdrrlabs.example.timer1app.core.utils.SettingsHelper; public class EditActionUI extends ExceptionHandlerUI { private static boolean DEBUG = true; public static final String TAG = EditActionUI.class.getSimpleName(); /** Extra long with the action prof_id (not index) to edit. */ public static final String EXTRA_ACTION_ID = "action_id"; /*package*/ static final int DIALOG_EDIT_PERCENT = 100; /** Maps dialog ids to their {@link PrefPercent} instance. */ private final SparseArray<PrefPercent> mPercentDialogMap = new SparseArray<PrefPercent>(); private long mActionId; private TimePicker mTimePicker; private SettingsHelper mSettingsHelper; private AgentWrapper mAgentWrapper; private PrefEnum mPrefRingerMode; private PrefEnum mPrefRingerVibrate; private PrefPercent mPrefRingerVolume; private PrefPercent mPrefNotifVolume; private PrefPercent mPrefMediaVolume; private PrefPercent mPrefAlarmVolume; private PrefPercent mPrefSystemVolume; private PrefPercent mPrefVoiceVolume; private PrefPercent mPrefBrightness; private Object mPrefAirplane; private Object mPrefWifi; private Object mPrefBluetooth; private Object mPrefApnDroid; private Object mPrefData; /** * Day checkboxes, in the same index order than {@link Columns#MONDAY_BIT_INDEX} * to {@link Columns#SUNDAY_BIT_INDEX}. */ private CheckBox[] mCheckDays; private View mCurrentContextMenuView; private int mRestoreHourMinValue = -1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_action); setTitle(R.string.editaction_title); Intent intent = getIntent(); mActionId = intent.getExtras().getLong(EXTRA_ACTION_ID); if (DEBUG) Log.d(TAG, String.format("edit prof_id: %08x", mActionId)); if (mActionId == 0) { Log.e(TAG, "action id not found in intent."); finish(); return; } mSettingsHelper = new SettingsHelper(this); SettingFactory factory = SettingFactory.getInstance(); // get profiles db helper ProfilesDB profilesDb = new ProfilesDB(); profilesDb.onCreate(this); // get cursor String prof_id_select = String.format("%s=%d", Columns.PROFILE_ID, mActionId); Cursor c = profilesDb.query( -1, // id // projection, a.k.a. the list of columns to retrieve from the db new String[] { Columns.PROFILE_ID, Columns.HOUR_MIN, Columns.DAYS, Columns.ACTIONS }, prof_id_select, // selection null, // selectionArgs null // sortOrder ); try { if (!c.moveToFirst()) { Log.w(TAG, "cursor is empty: " + prof_id_select); finish(); return; } // get column indexes int hourMinColIndex = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int daysColIndex = c.getColumnIndexOrThrow(Columns.DAYS); int actionsColIndex = c.getColumnIndexOrThrow(Columns.ACTIONS); String actions_str = c.getString(actionsColIndex); if (DEBUG) Log.d(TAG, String.format("Edit Action=%s", actions_str)); String[] actions = actions_str != null ? actions_str.split(",") : null; // get UI widgets mTimePicker = (TimePicker) findViewById(R.id.timePicker); mPrefRingerMode = new PrefEnum(this, R.id.ringerModeButton, SettingsHelper.RingerMode.values(), actions, Columns.ACTION_RINGER, getString(R.string.editaction_ringer)); mPrefRingerMode.setEnabled(mSettingsHelper.canControlAudio(), getString(R.string.setting_not_supported)); mPrefRingerVibrate = new PrefEnum(this, R.id.ringerVibButton, SettingsHelper.VibrateRingerMode.values(), actions, Columns.ACTION_VIBRATE, getString(R.string.editaction_vibrate)); mPrefRingerVibrate.setEnabled(mSettingsHelper.canControlAudio(), getString(R.string.setting_not_supported)); mPrefRingerVolume = (PrefPercent) factory.getSetting(Columns.ACTION_RING_VOLUME).createUi(this, actions); int dialogId = DIALOG_EDIT_PERCENT; mPercentDialogMap.put(mPrefRingerVolume.setDialogId(++dialogId), mPrefRingerVolume); mPrefNotifVolume = (PrefPercent) factory.getSetting(Columns.ACTION_NOTIF_VOLUME).createUi(this, actions); mPercentDialogMap.put(mPrefNotifVolume.setDialogId(++dialogId), mPrefNotifVolume); mPrefMediaVolume = (PrefPercent) factory.getSetting(Columns.ACTION_MEDIA_VOLUME).createUi(this, actions); mPercentDialogMap.put(mPrefMediaVolume.setDialogId(++dialogId), mPrefMediaVolume); mPrefAlarmVolume = (PrefPercent) factory.getSetting(Columns.ACTION_ALARM_VOLUME).createUi(this, actions); mPercentDialogMap.put(mPrefAlarmVolume.setDialogId(++dialogId), mPrefAlarmVolume); mPrefSystemVolume = (PrefPercent) factory.getSetting(Columns.ACTION_SYSTEM_VOLUME).createUi(this, actions); mPercentDialogMap.put(mPrefSystemVolume.setDialogId(++dialogId), mPrefSystemVolume); mPrefVoiceVolume = (PrefPercent) factory.getSetting(Columns.ACTION_VOICE_CALL_VOLUME).createUi(this, actions); mPercentDialogMap.put(mPrefVoiceVolume.setDialogId(++dialogId), mPrefVoiceVolume); mPrefBrightness = (PrefPercent) factory.getSetting(Columns.ACTION_BRIGHTNESS).createUi(this, actions); mPercentDialogMap.put(mPrefBrightness.setDialogId(++dialogId), mPrefBrightness); mPrefBluetooth = factory.getSetting(Columns.ACTION_BLUETOOTH).createUi(this, actions); mPrefApnDroid = factory.getSetting(Columns.ACTION_APN_DROID).createUi(this, actions); mPrefData = factory.getSetting(Columns.ACTION_DATA).createUi(this, actions); mPrefWifi = factory.getSetting(Columns.ACTION_WIFI).createUi(this, actions); mPrefAirplane = factory.getSetting(Columns.ACTION_AIRPLANE).createUi(this, actions); mCheckDays = new CheckBox[] { (CheckBox) findViewById(R.id.dayMon), (CheckBox) findViewById(R.id.dayTue), (CheckBox) findViewById(R.id.dayWed), (CheckBox) findViewById(R.id.dayThu), (CheckBox) findViewById(R.id.dayFri), (CheckBox) findViewById(R.id.daySat), (CheckBox) findViewById(R.id.daySun) }; TextView[] labelDays = new TextView[] { (TextView) findViewById(R.id.labelDayMon), (TextView) findViewById(R.id.labelDayTue), (TextView) findViewById(R.id.labelDayWed), (TextView) findViewById(R.id.labelDayThu), (TextView) findViewById(R.id.labelDayFri), (TextView) findViewById(R.id.labelDaySat), (TextView) findViewById(R.id.labelDaySun) }; // fill in UI from cursor data // Update the time picker. // BUG WORKAROUND: when updating the timePicker here in onCreate, the timePicker // might override some values when it redisplays in onRestoreInstanceState so // we'll update there instead. mRestoreHourMinValue = c.getInt(hourMinColIndex); setTimePickerValue(mTimePicker, mRestoreHourMinValue); // Update days checked int days = c.getInt(daysColIndex); for (int i = Columns.MONDAY_BIT_INDEX; i <= Columns.SUNDAY_BIT_INDEX; i++) { mCheckDays[i].setChecked((days & (1<<i)) != 0); } String[] dayNames = TimedActionUtils.getDaysNames(); for (int i = 0; i < dayNames.length; i++) { labelDays[i].setText(dayNames[i]); } mPrefRingerMode.requestFocus(); ScrollView sv = (ScrollView) findViewById(R.id.scroller); sv.scrollTo(0, 0); } finally { c.close(); profilesDb.onDestroy(); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Bug workaround. See mRestoreHourMinValue in onCreate. if (mRestoreHourMinValue >= 0) { setTimePickerValue(mTimePicker, mRestoreHourMinValue); } } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); mCurrentContextMenuView = null; Object tag = view.getTag(); if (tag instanceof PrefBase) { ((PrefBase) tag).onCreateContextMenu(menu); mCurrentContextMenuView = view; } } @Override public boolean onContextItemSelected(MenuItem item) { if (mCurrentContextMenuView instanceof View) { Object tag = mCurrentContextMenuView.getTag(); if (tag instanceof PrefBase) { ((PrefBase) tag).onContextItemSelected(item); } } return super.onContextItemSelected(item); } @Override public void onContextMenuClosed(Menu menu) { super.onContextMenuClosed(menu); mCurrentContextMenuView = null; } @Override protected Dialog onCreateDialog(final int id) { PrefPercent pp = mPercentDialogMap.get(id); if (DEBUG) Log.d(TAG, String.format("Create dialog id=%d, pp=%s", id, pp == null ? "null" : pp.getDialogTitle())); if (pp != null) { PrefPercentDialog d = new PrefPercentDialog(this, pp); // We need to make sure to remove the dialog once it gets dismissed // otherwise the next use of the same dialog might reuse the previous // dialog from another setting! d.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(id); } }); return d; } return super.onCreateDialog(id); } // ----------- @Override protected void onResume() { super.onResume(); mAgentWrapper = new AgentWrapper(); mAgentWrapper.start(this); mAgentWrapper.event(AgentWrapper.Event.OpenTimeActionUI); } @Override protected void onPause() { super.onPause(); ProfilesDB profilesDb = new ProfilesDB(); try { profilesDb.onCreate(this); int hourMin = getTimePickerHourMin(mTimePicker); int days = 0; for (int i = Columns.MONDAY_BIT_INDEX; i <= Columns.SUNDAY_BIT_INDEX; i++) { if (mCheckDays[i].isChecked()) { days |= 1<<i; } } SettingFactory factory = SettingFactory.getInstance(); StringBuilder actions = new StringBuilder(); mPrefRingerMode.collectResult(actions); mPrefRingerVibrate.collectResult(actions); mPrefRingerVolume.collectResult(actions); mPrefNotifVolume.collectResult(actions); mPrefMediaVolume.collectResult(actions); mPrefAlarmVolume.collectResult(actions); mPrefSystemVolume.collectResult(actions); mPrefVoiceVolume.collectResult(actions); factory.getSetting(Columns.ACTION_BRIGHTNESS).collectUiResults(mPrefBrightness, actions); factory.getSetting(Columns.ACTION_BLUETOOTH).collectUiResults(mPrefBluetooth, actions); factory.getSetting(Columns.ACTION_APN_DROID).collectUiResults(mPrefApnDroid, actions); factory.getSetting(Columns.ACTION_DATA).collectUiResults(mPrefData, actions); factory.getSetting(Columns.ACTION_AIRPLANE).collectUiResults(mPrefAirplane, actions); factory.getSetting(Columns.ACTION_WIFI).collectUiResults(mPrefWifi, actions); if (DEBUG) Log.d(TAG, "new actions: " + actions.toString()); String description = TimedActionUtils.computeDescription( this, hourMin, days, actions.toString()); int count = profilesDb.updateTimedAction(mActionId, hourMin, days, actions.toString(), description); if (DEBUG) Log.d(TAG, "written rows: " + Integer.toString(count)); } finally { profilesDb.onDestroy(); } mAgentWrapper.stop(this); } @Override protected void onStop() { super.onStop(); } // ----------- private int getTimePickerHourMin(TimePicker timePicker) { // If the user was manually editing one of the time picker fields, // the internal time picker values might not have been properly // updated yet. Requesting a focus on the time picker forces it // to update by side-effect. timePicker.requestFocus(); int hours = timePicker.getCurrentHour(); int minutes = timePicker.getCurrentMinute(); return hours*60 + minutes; } private void setTimePickerValue(TimePicker timePicker, int hourMin) { if (hourMin < 0) hourMin = 0; if (hourMin >= 24*60) hourMin = 24*60-1; int hours = hourMin / 60; int minutes = hourMin % 60; timePicker.setCurrentHour(hours); timePicker.setCurrentMinute(minutes); timePicker.setIs24HourView(DateFormat.is24HourFormat(this)); } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageButton; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; //----------------------------------------------- /** * The class does... * */ public class GlobalToggle extends ImageButton { private final int[] ACTIVE_STATE = { android.R.attr.state_active, R.attr.state_gt_fast_anim }; private boolean mActive; private PrefsValues mPrefsValues; public GlobalToggle(Context context, AttributeSet attrs) { super(context, attrs); mPrefsValues = new PrefsValues(context); } public void setActive(boolean active) { mActive = active; invalidateDrawable(getDrawable()); } public boolean isActive() { return mActive; } @Override public int[] onCreateDrawableState(int extraSpace) { if (mActive) extraSpace += 2; int[] result = super.onCreateDrawableState(extraSpace); if (mActive) { // Replace second item of our state array by the desired // animation state based on the prefs. switch(mPrefsValues.getGlobalToggleAnim()) { case NO_ANIM: ACTIVE_STATE[1] = R.attr.state_gt_no_anim; break; case SLOW: ACTIVE_STATE[1] = R.attr.state_gt_slow_anim; break; case FAST: ACTIVE_STATE[1] = R.attr.state_gt_fast_anim; break; } result = mergeDrawableStates(result, ACTIVE_STATE); } return result; } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl; /** * Activity redirector which is only present for backward compatibility. * * IMPORTANT: this MUST remain as com.rdrrlabs.example.timer1app.profiles.ProfilesUi1 * otherwise legacy home shortcuts will break. */ public class ProfilesUI1 extends ActivityDelegate<ProfilesUiImpl> { @Override public ProfilesUiImpl createDelegate() { return new ProfilesUiImpl(this); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; import android.app.Activity; import android.os.Bundle; /** * An {@link Activity} base class that uses our {@link ExceptionHandler}. */ public abstract class ExceptionHandlerUI extends Activity { private ExceptionHandler mExceptionHandler; @Override protected void onCreate(Bundle bundle) { mExceptionHandler = new ExceptionHandler(this); super.onCreate(bundle); } @Override protected void onStart() { if (mExceptionHandler == null) { mExceptionHandler = new ExceptionHandler(this); } super.onStart(); } @Override protected void onStop() { super.onStop(); if (mExceptionHandler != null) { mExceptionHandler.detach(); mExceptionHandler = null; } } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IHardwareService; import android.os.Message; import android.os.PowerManager; import android.os.ServiceManager; import android.os.PowerManager.WakeLock; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.util.Log; import android.view.Window; import android.view.WindowManager.LayoutParams; import com.rdrrlabs.example.timer1app.base.R; /** * Changes the global brightness, either setting an actual value. * * This <en>ensures</en> you can't shoot yourself in the foot by never * actually setting the brightness to zero. The minimun used is 10/255 * which matches the code from the hidden PowerManager class. * * This is an ugly hack: * - for pre-Cupcake (sdk 3), uses the IHardwareTest hack. * - for Cupcake, uses the Window brightness mixed with a global setting * that works for some obscure reason (it's actually a bug, which means it * will be fixed.) * * Requires the following permissions: * - android.permission.HARDWARE_TEST for the pre-Cupcake hack * - android.permission.WRITE_SETTINGS to set the global setting */ public class ChangeBrightnessUI extends ExceptionHandlerUI { /* * If you're curious the hack for 1.6 the following: * * - Starting with 1.6 each app can change its own screen brightness. * This was made for flashlight apps and is a public API. * - So I have a fake activity that displays nothing. * - The screen dims & restores because Android switched activities... * you just don't see anything since there's no UI to display. * - Set its brightness to the desired one. * - Write the desired brightness in the public setting preference * (we have the permission to access it.) * - Normally when the fake activity quits, Android restores the brightness * to the default. * - Kill the activity exactly 1 second later... * - And voila, the window manager restores the brightness to the *new* default. */ public static final String TAG = "ChangeBright"; /** Using 0 will actually turn the screen off! */ private static final int BR_MIN = 1; /** Max brightness from the API (c.f. PowerManager source, constant * is not public.) */ private static final int BR_MAX = 255; public static final String INTENT_SET_BRIGHTNESS = "set"; private Handler mHandler; public ChangeBrightnessUI() { mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 42) { ChangeBrightnessUI.this.finish(); } super.handleMessage(msg); } }; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // A bit unfortunate but it seems the brightness change hack // doesn't work on some devices when the screen is turned off. try { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "TFCChangeBrightness"); wl.acquire(1010); // we need 1000 ms below, so randomly choose a bit more here } catch (Exception e) { // Wake lock failed. Still continue. Log.d(TAG, "WakeLock.acquire failed"); } setContentView(R.layout.empty); Intent i = getIntent(); float f = i.getFloatExtra(INTENT_SET_BRIGHTNESS, -1); if (f >= 0) { setCurrentBrightness(f); } Message msg = mHandler.obtainMessage(42); mHandler.sendMessageDelayed(msg, 1000); // this makes it all work } private void setCurrentBrightness(float f) { int v = (int) (BR_MAX * f); if (v < BR_MIN) { // never set backlight too dark v = BR_MIN; f = (float)v / BR_MAX; } Settings.System.putInt(this.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, v); int sdk = -1; try { sdk = Integer.parseInt(Build.VERSION.SDK); } catch (Exception e) { Log.i(TAG, String.format("Failed to parse SDK Version '%s'", Build.VERSION.SDK)); } if (sdk >= 3) { try { Window win = getWindow(); LayoutParams attr = win.getAttributes(); Field field = attr.getClass().getField("screenBrightness"); field.setFloat(attr, f); win.setAttributes(attr); Log.i(TAG, String.format("Changed brightness to %.2f [SDK 3+]", f)); } catch (Throwable t) { Log.e(TAG, String.format("Failed to set brightness to %.2f [SDK 3+]", f), t); } } else { // Older SDKs try { IHardwareService hs = IHardwareService.Stub.asInterface( ServiceManager.getService("hardware")); if (hs != null) { Method m = hs.getClass().getMethod("setScreenBacklight", new Class[] { int.class }); if (m != null) { m.invoke(hs, new Object[] { v }); Log.i(TAG, String.format("Changed brightness to %d [SDK<3]", v)); } } } catch (Throwable t) { Log.e(TAG, String.format("Failed to set brightness to %d [SDK<3]", v), t); } } } /** * Returns screen brightness in range 0..1. */ public static float getCurrentBrightness(Context context) { try { int v = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); return (float)v / BR_MAX; } catch (SettingNotFoundException e) { // If not found, return some acceptable default return 0.75f; } } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.ui; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /** * Activity delegate. */ public abstract class ActivityDelegate<T extends IActivityDelegate<?>> extends Activity { private T mDelegate; abstract public T createDelegate(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDelegate = createDelegate(); mDelegate.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); mDelegate.onResume(); } @Override public void onPause() { super.onPause(); mDelegate.onPause(); } @Override public void onStop() { super.onStop(); mDelegate.onStop(); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mDelegate.onRestoreInstanceState(savedInstanceState); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mDelegate.onSaveInstanceState(outState); } @Override public void onDestroy() { super.onDestroy(); mDelegate.onDestroy(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mDelegate.onActivityResult(requestCode, resultCode, data); } @Override public Dialog onCreateDialog(int id) { return mDelegate.onCreateDialog(id); } @Override public boolean onContextItemSelected(MenuItem item) { boolean b = mDelegate.onContextItemSelected(item); if (!b) b = super.onContextItemSelected(item); return b; } @Override public boolean onCreateOptionsMenu(Menu menu) { mDelegate.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean b = mDelegate.onOptionsItemSelected(item); if (!b) b = super.onOptionsItemSelected(item); return b; } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package android.os; /** Stub just for compiling. */ public class ServiceManager { /** Stub just for compiling. */ public static IBinder getService(String string) { return null; } }
Java
package Controller; import api.ICiServer; import api.ICiClient; import java.math.BigDecimal; import java.rmi.RemoteException; import server.BankManager; /** * De CentraleInstelling klasse implementeer ICiServer (interface). * Dit zijn methode die een bank client kan aanroepen bij centrale instelling via RMI. */ public class CentraleInstelling implements ICiServer { /** * Methode om een transactie aan te vragen en daarbij kijken of vanRekening en tegenRekening correct zijn (geimplementeerd door ICiServer) * @param prefix de bank initialen. * @param key de validatiesleutel van de bank. * @param vanRekening de van-rekening * @param naarRekening de tegen-rekening * @param bedrag het bedrag. * @param comment de beschrijving behorende bij de transactie. * @return bericht met afkeuring/goedkeuring. * @throws RemoteException moet afgevangen worden wanneer er gebruik gemaakt wordt van RMI. */ @Override public synchronized String requestTransaction(String prefix, String key, String vanRekening, String naarRekening, BigDecimal bedrag, String comment) throws RemoteException { if (!BankManager.getInstance().isGeauthentificeerd(prefix, key)) { return "403: Authentication failed"; } String[] tokens = vanRekening.split(" "); if (tokens.length != 2) { return "400: bad request: vanRekening"; } String vanPrefix = tokens[0]; vanRekening = tokens[1]; if (!vanPrefix.equals(prefix)) { return "400: bad request: vanRekening, bank not eligble for this account"; } tokens = naarRekening.split(" "); if (tokens.length != 2) { return "400: bad request: naarRekening"; } String naarPrefix = tokens[0]; naarRekening = tokens[1]; if (!BankManager.getInstance().isGeregistreerd(naarPrefix)) { return "400: bad request: naarRekening, bank does not exist"; } return "200: OK: transaction accepted"; } /** * Methode om een bank als client te zetten bij centrale instelling. * @param prefix de unieke bankinitialen. * @param key de validatiesleutel. * @param clientObj het client object dat geregistreerd wordt bij de centrale instelling. * @return String met daarin bericht of het gelukt is of niet. * @throws RemoteException moet afgevangen worden als er gebruik gemaakt wordt van RMI. */ @Override public synchronized String setClient(String prefix, String key, ICiClient clientObj) throws RemoteException { if (!BankManager.getInstance().isGeauthentificeerd(prefix, key)) { return "403: Authentication failed"; } if (clientObj == null) { return "400: bad request: clientOBj"; } if (BankManager.getInstance().registreerClientBijBank(prefix, clientObj)) { return "200: succes"; } return null; } }
Java
package server; import Model.Bank; import api.ICiClient; import java.util.HashMap; /** * De Bankmanager houdt een lijst van banken bij. */ public class BankManager { private static volatile BankManager instance = null; //rekeningprefix + auth key private HashMap<String, Bank> banken; /** * Constructor voor BankManager met hierin al dummy data opgenomen. */ private BankManager() { this.banken = new HashMap<>(); Bank bank = new Bank("RABO", "testkey"); Bank bank2 = new Bank("FORT", "testkey"); this.banken.put("RABO", bank); this.banken.put("FORT", bank2); } /** * Klasse loader wordt aangeroepen in de getInstance methode binnen BankManager. * En zorgt dat er een nieuwe BankManager opgestart wordt wanneer dit nog niet gedaan is. * Lazy-loaded singleton pattern */ private static class Loader { private static final BankManager instance = new BankManager(); } /** * Methode om BankManager op te vragen. * @return actieve Bankregistry. */ public static BankManager getInstance() { return Loader.instance; } /** * Methode om de bankclient te valideren bij de centrale instelling. * @param prefix de bankinitialen die uniek zijn voor een bank. * @param key de validatiesleutel. * @return true als validatie succesvol is, false als dit niet succesvol is. */ public boolean isGeauthentificeerd(String prefix, String key) { if (prefix != null & !prefix.isEmpty()) { String correctKey; synchronized (banken) { if (banken.containsKey(prefix)) { Bank bank = banken.get(prefix); if (bank.getValidatieKey().equals(key)) { return true; } else { banken.remove(prefix); } } } } return false; } /** * Methode om te kijken of een bepaalde bank al geregistreerd is bij de centrale instelling * @param prefix de eerste letters van een bank die uniek zijn voor een bank. * @return true als bank al bekend is, false als dit niet is. */ public boolean isGeregistreerd(String prefix) { if(this.banken.containsKey(prefix)) { return true; } return false; } /** * Methode om een bankclient te registrern bij de centrale instelling. * @param prefix bankinitialen die uniek zijn voor een bank. * @param clientObj ICiClient object. * @return true als de registratie gelukt is, false als het niet gelukt is. */ public boolean registreerClientBijBank(String prefix, ICiClient clientObj) { if(isGeregistreerd(prefix)) { synchronized (banken) { Bank b = banken.get(prefix); if(b != null) { b.setClientobj(clientObj); return true; } } } return false; } }
Java
package server; import api.ICiServer; import Controller.CentraleInstelling; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.logging.Level; import java.util.logging.Logger; /** * Klasse om de RMI registry op te starten en de remote interfaces te instantieren. */ public class CiServer { private static Registry registry; private CentraleInstelling ci; private static ICiServer ciStub; /** * Constructor van CIserver. De constructor instantieert de securitymanager * mocht deze nog niet bestaan en probeert een RMI registry te starten. Na * starten van het registry wordt startconnectie aangeroepen om de stubs * bekend te maken binnen het RMI registry. * */ public CiServer() { if (System.getSecurityManager() == null) { SecurityManager securM = new SecurityManager(); System.setSecurityManager(securM); } try { LocateRegistry.createRegistry(1100); registry = LocateRegistry.getRegistry(1100); } catch (RemoteException ex) { Logger.getLogger(CiServer.class.getName()).log(Level.SEVERE, null, ex); } startConnectie(); } /** * Deze methode haalt de stub uit de RMI registry. */ public void stopConnectie() { try { registry.unbind("ci"); } catch (NoSuchObjectException ex) { Logger.getLogger(CiServer.class.getName()).log(Level.SEVERE, null, ex); } catch (RemoteException | NotBoundException ex) { Logger.getLogger(CiServer.class.getName()).log(Level.SEVERE, null, ex); } } /** * Deze methode maakt een stub en plaatst deze in de RMI registry. */ public void startConnectie() { try { CentraleInstelling ci = new CentraleInstelling(); ciStub = (ICiServer) UnicastRemoteObject.exportObject(ci, 1100); registry.rebind("ci", ciStub); System.out.println("Centrale Instelling - server gestart"); } catch (RemoteException ex) { System.out.println(ex); Logger.getLogger(CiServer.class.getName()).log(Level.SEVERE, null, ex); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { CiServer ciServer = new CiServer(); } }); } }
Java
package Model; import api.ICiClient; /** * De klasse bank moet bekend zijn bij de centrale instelling. */ public class Bank { private final String prefix; private final String validatieKey; private ICiClient clientobj; /** * Constructor om een nieuwe bank op te zetten bij centrale instelling. * @param prefix unieke bankinitialen. * @param key validatiesleutel van de bank. */ public Bank(String prefix, String key) { this.prefix = prefix; this.validatieKey = key; } /** * Constructor om een nieuwe bank op te zetten bij centrale instelling. * @param prefix unieke bankinitialen. * @param key validatiesleutel van de bank. * @param clientobj bank client object. */ public Bank(String prefix, String key, ICiClient clientobj) { this.prefix = prefix; this.validatieKey = key; this.clientobj = clientobj; } /** * get methode om de bank initialen op te vragen. * @return String bankinitialen. */ public String getPrefix() { return prefix; } /** * get methode om de validatiesleutel op te vragen. * @return String validatiesleutel. */ public String getValidatieKey() { return validatieKey; } /** * Get methode om bank client object op te vragen. * @return ICiClient object. */ public ICiClient getClientobj() { return clientobj; } /** * methode om de client object te setten. * @param clientobj ICiClient object. */ public void setClientobj(ICiClient clientobj) { this.clientobj = clientobj; } }
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 API.Klassen; import java.util.ArrayList; import java.util.Random; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; /** * * @author Roland */ public class KlantTest { public KlantTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test klantnaam */ @Test public void testKlantNaam() { System.out.println("Klantnaam test"); Klant klant = new Klant("Henkie Jansen", "Eindhoven", 1); assertTrue(klant.getKlantnaam() == "Henkie Jansen"); klant = new Klant("Roland", "Veldhoven", 2); assertTrue(klant.getKlantnaam() == "Roland"); klant = new Klant("Ali Adi Lmbdoo Djiboiuay", "Amsterdam", 3); assertTrue(klant.getKlantnaam() == "Ali Adi Lmbdoo Djiboiuay"); } /** * Test klant woonplaats */ @Test public void testKlantWoonplaats() { System.out.println("Klantnaam test"); Klant klant = new Klant("Henkie Jansen", "Eindhoven", 1); assertTrue(klant.getKlantwoonplaats() == "Eindhoven"); klant = new Klant("Roland", "Veldhoven", 2); assertTrue(klant.getKlantwoonplaats() == "Veldhoven"); klant = new Klant("Ali Adi Lmbdoo Djiboiuay", "Amsterdam", 3); assertTrue(klant.getKlantwoonplaats() == "Amsterdam"); } }
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 API.Klassen; import java.math.BigDecimal; import java.util.ArrayList; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Roland */ public class RekeningTest { public RekeningTest() { } @BeforeClass public static void setUpClass() { //start de server } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test rekeningnr * deze hoort elke keer 1 hoger te zijn als de vorige */ @Test public void testRekeningnr() { ArrayList<Rekening> rekeningenLijst = new ArrayList<Rekening>(); System.out.println("rekeningnrtest"); for(int i = 0; i < 100; i++) { Rekening rekening = new Rekening(); rekeningenLijst.add(rekening); } int hulp = rekeningenLijst.get(0).getRekeningnummer(); for (int i = 1; i < 100; i++) { System.out.println(rekeningenLijst.get(i).getRekeningnummer()); assertTrue(rekeningenLijst.get(i).getRekeningnummer() == hulp + i); } } }
Java
import API.Interfaces.ILogin; import API.Klassen.Klant; import API.Klassen.LoginAccount; import API.Klassen.Rekening; import Balie.Controller.ClientImpl; import Balie.GUI.SessieFrame; import Balie.GUI.StartFrame; import Bank.Managers.KlantManager; import Bank.Managers.LoginManager; import Bank.Managers.RekeningManager; import Bank.Server.ServerStarter; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /* * 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 Roland */ public class LoginTest { private ClientImpl clientcontroller; private Boolean check = false; public LoginTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test inloggen juist */ @Test public void testInloggenjuistegegevens() throws RemoteException { check = false; laaddata("Roland" , "test"); assertTrue(check); } /** * Test inloggen fout wachtwoord */ @Test public void testInloggenfoutwachtwoord() throws RemoteException { check = false; laaddata("Roland" , "wachtwoord"); assertTrue(!check); } /** * Test inloggen foute gebruikersnaam */ @Test public void testInloggenfoutenaam() throws RemoteException { check = false; laaddata("Nope" , "test"); assertTrue(!check); } /** * Test inloggen niets ingevuld */ @Test public void testInloggennietsingevuld() throws RemoteException { check = false; laaddata("" , ""); assertTrue(!check); } /** * Test inloggen enkel naam ingevuld */ @Test public void testInloggennaamingevuld() throws RemoteException { check = false; laaddata("Roland" , ""); assertTrue(!check); } /** * Test inloggen enkel wachtwoord ingevuld */ @Test public void testInloggenwachtwoordingevuld() throws RemoteException { check = false; laaddata("" , "test"); assertTrue(!check); } /** * Test inloggen upper/lowercase sensitive */ @Test public void testInloggenuppercase() throws RemoteException { check = false; laaddata("roland" , "test"); assertTrue(!check); } public void laaddata(String nm, String ww) throws RemoteException { //start de server ServerStarter starter = new ServerStarter(); //laad de testgegevens LoginAccount loginKlant = new LoginAccount("Roland", "test", 1, 1000); LoginManager lm = LoginManager.getInstance(); lm.addLogin(loginKlant); String naam = nm; String wachtwoord = ww; try { // check of passwoord bij gebruikersnaam hoort //indien correct, start een sessieframe op String bankServerURL = "rmi://localhost/login"; String sessieId = null; ILogin loginInterface; loginInterface = (ILogin) Naming.lookup(bankServerURL); sessieId = loginInterface.startSessie(naam, wachtwoord); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); return; } catch (NotBoundException ex) { Logger.getLogger(StartFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(StartFrame.class.getName()).log(Level.SEVERE, null, ex); } //indien geen error start clientcontroller = new ClientImpl(naam, wachtwoord); check = true; } }
Java
package Balie.Controller; import API.*; import API.Model.SessieExpiredException; import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.HashMap; /** * Deze klasse implementeert IClient en maakt het zo mogelijk dat de server * methoden kan aanroepen bij deze klasse. Verder dient deze klasse ook om de * RMI connectie van client naar bank te zetten en dient het als controller voor * de gui. */ public class ClientImpl implements IClient { private static volatile ClientImpl instance; private static HashMap<Integer, ArrayList<IObserver>> obs = new HashMap(); private final String bankServerURL = "127.0.0.1"; private String sessieId; private IAuth loginInterface; private ITransactieHandler transHandler; /** * Constructor voor de clientcontroller die aangeroepen wordt zodra de klant * van uit de GUI gaat inloggen. In de constructor wordt de registry * opgezocht van de bank. * * @throws java.rmi.RemoteException * @throws NotBoundException wanneer de bankserver offline is wordt deze * exception gegooid. */ public ClientImpl() throws RemoteException, NotBoundException { UnicastRemoteObject.exportObject(this, 0); instance = this; setAuthentificatieConnectie(); setTransactieConnectie(); } /** * Methode die vanuit de bankserver aangeroepen wordt wanneer de client 10 * mins inactief was. * * @throws SessieExpiredException wanneer klant en systeem tegelijk clientobject uitloggen mag dit niet fout gaan, * vandaar dat deze exceptie ook afgevangen moet worden. * @throws java.rmi.RemoteException Deze exceptie moet afgevangen worden wanneer gebruik gemaakt wordt van RMI. */ @Override public synchronized void uitloggen() throws SessieExpiredException, RemoteException { this.loginInterface.stopSessie(sessieId); UnicastRemoteObject.unexportObject(this, true); System.out.println("Client Stopped"); } /** * Methode om een observable te zetten. Deze wordt aangeroepen vanuit de * bankserver. * * @param o het IObservable object. * @throws RemoteException wanneer er problemen zijn met RMI wordt deze * exceptie gegooid. */ @Override public synchronized void setObservable(IObservable o) throws RemoteException { if (obs.containsKey(o.getObservableId())) { ArrayList<IObserver> observers = obs.get(o.getObservableId()); if (observers != null) { for (IObserver ob : observers) { ob.update(o, ""); } } } } /** * Deze methode wordt vanuit de GUI aangeroepen om zo een observer toe te * voegen aan een observable object. Wordt oa gebruikt voor rekeningpanel in * gui. * * @param ob het observer object * @param o het observable object */ public synchronized void addObserver(IObserver ob, IObservable o) { //Nog check inbouwen of IObserver al eerder geregistreerd is. ArrayList<IObserver> obsList = new ArrayList<>(); obsList.add(ob); obs.put(o.getObservableId(), obsList); } /** * Deze methode wordt vanuit de constructor aangeroepen. De connectie tussen * balie en bank wordt hier gezet zodat de klant geauthentificeerd kan * worden. * * @throws NotBoundException. Deze exceptie zal gegooid worden wanneer de * bankserver offline is. */ private synchronized void setAuthentificatieConnectie() throws NotBoundException, RemoteException { Registry registry = LocateRegistry.getRegistry(this.bankServerURL, 0); loginInterface = (IAuth) registry.lookup("auth"); } /** * Deze methoden worden vanuit de GUI aangeroepen om gegevens op te kunnen * halen via deze connectie. Waneer de return null is, wordt er een * IllegalArgumentException gegooid. * * @return IAuth object. */ public synchronized IAuth getAuthificatieConnectie() { return this.loginInterface; } /** * Methode om de connectie voor de transacties op te zetten. Deze methode * wordt in de constructor aangeroepen. Transacties hebben een aparte * connectie omdat dit overzichtelijker is. */ private synchronized void setTransactieConnectie() throws NotBoundException, RemoteException { Registry registry = LocateRegistry.getRegistry(bankServerURL, 1099); transHandler = (ITransactieHandler) registry.lookup("transactie"); } /** * Vanuit de GUI kan de bestaande transactieconnectie opgehaald worden. * * @return ITransactieHandler object. */ public synchronized ITransactieHandler getTransactieConnectie() { return this.transHandler; } /** * * @param gebruikersnaam gebruikersnaam van de klant * @param wachtwoord wachtwoord van de klant. * @return sessieID * @throws IllegalArgumentException wordt gegooid wanneer gegevens onjuist * zijn. * @throws SessieExpiredException wanneer de klant 10 mins inactief is * geweest. * @throws RemoteException moet afgevangen worden voor RMI connectieproblemen */ public synchronized String getSessieIDvanInloggen(String gebruikersnaam, String wachtwoord) throws IllegalArgumentException, SessieExpiredException, RemoteException { sessieId = loginInterface.startSessie(gebruikersnaam, wachtwoord); loginInterface.registreerClientObject(sessieId, this); return this.sessieId; } /** * Methode om nieuwe klant te registreren bij bankserver en meteen een * sessie te starten. * * @param klantnaam Naam van de klant. * @param woonplaats Woonplaats van de klant. * @param gebruikersnaam Gebruikersnaam van de klant. * @param wachtwoord Wachtwoord van de klant. * @return sessieID sessieID van de klant. * @throws SessieExpiredException Wwanneer sessie verlopen is wordt deze * exceptie gegooid. * @throws RemoteException moet afgevangen worden voor RMI connectie problemen */ public synchronized String registrerenNieuweKlant(String klantnaam, String woonplaats, String gebruikersnaam, String wachtwoord) throws IllegalArgumentException, SessieExpiredException, RemoteException { if (loginInterface.registreerNieuweKlant(klantnaam, woonplaats, gebruikersnaam, wachtwoord)) { return "Registratie voltooid \nU kunt nu inloggen"; } return "Registratie mislukt \nProbeer het nogmaals."; } }
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 Balie.Controller; import java.util.HashMap; /** * Simpele klasse om banken en de connectiestrings te kunnen bijhouden. * Idealiter zou dit ingelezen worden via een los bestand. * * @author Ieme */ public class Banken { private HashMap<String, String> banken; private String bankUrl; /** * Constructor die wat dummy test data inlaad */ public Banken() { banken = new HashMap<>(); banken.put("Fortis", "127.0.0.1"); banken.put("Rabobank", "127.0.0.1"); } /** * Methode om alle banknamen te verkrijgen. * @return String array met banknamen */ public String[] getBanknames() { String[] bankenNames = new String[banken.size()]; for (int i = 0; i < banken.size(); i++) { bankenNames[i] = banken.keySet().toArray()[i].toString(); } return bankenNames; } /** * Methode om de url (string) te verkrijgen bij een banknaam. Bestaat de bank niet wordt er null geretourneerd. * @param bankName naam van de bank * @return bankurl of null wanneer bank niet voorkomt. */ public String getUrl(String bankName) { if (bankName != null) { return banken.get(bankName); } return null; } }
Java
package Balie.Controller; import java.util.ArrayList; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceRef; import nl.rainbowsheep.aex.AEX; import nl.rainbowsheep.aex.AEXService; import nl.rainbowsheep.aex.Fonds; /** * Heel simpel voorbeeld om de koersen op te vragen van de AEX webservice. */ public class AEXfondsen { @WebServiceRef(wsdlLocation = "http://localhost:9009/AEX/AEX?WSDL") private static AEXService service; private String fondseninfo; /** * Lege constructor * @throws WebServiceException */ public AEXfondsen() { } public String getFondsenInfo() throws WebServiceException { service = new AEXService(); AEX aex = service.getAEXPort(); ArrayList<Fonds> fondsen = (ArrayList<Fonds>) aex.getFondsen(); StringBuilder sb = new StringBuilder(); for (Fonds f : fondsen) { sb.append(f.getNaam()).append(" ").append(f.getKoers()).append(" ").append(f.isGestegen()).append(" ").append(f.getProcentgewijzigd()).append("% "); } this.fondseninfo = sb.toString(); return this.fondseninfo; } }
Java
package Balie.gui; import API.Model.Transactie; import java.math.RoundingMode; import java.text.DateFormat; import java.util.ArrayList; import java.util.GregorianCalendar; import javax.swing.table.DefaultTableModel; /** * Transactiepanel is opgenomen in SessieFrame en toont transactiegegevens van de klant. * */ public class TransactiePanel extends javax.swing.JPanel { private ArrayList<Transactie> transacties; private String eigenRekeningNr; /** * Creates new form TransactiePanel */ public TransactiePanel() { initComponents(); this.transacties = new ArrayList<>(); } /** Methode om eigen rekeningnummer te zetten om deze juist te tonen in transactieoverzicht. * * @param eigenRekeningNr eigen rekeningnummer van de ingelogde klant. */ public void setEigenRekeningNr(String eigenRekeningNr) { this.eigenRekeningNr = eigenRekeningNr; } /** Methode om nieuwe transactielijst in te laden en deze te tonen. * * @param transacties lijst van transacties. */ public void setTransacties(ArrayList<Transactie> transacties) { this.transacties = transacties; refrestListView(); } /** * Methode om de tabel te updaten met lijst van transacties. */ private void refrestListView() { String col[] = {"Datum", "Tegenrekening", "Bij/af", "Bedrag", "Status"}; // de 0 argument is het aantal rijen. DefaultTableModel tableModel = new DefaultTableModel(col, 0); String rekening; String transRichting; for (int i = 0; i < transacties.size(); i++) { Transactie trans = transacties.get(i); GregorianCalendar datum = trans.getTransactieInvoerDatum(); if (eigenRekeningNr.equals(trans.getEigenbankrekening())) { transRichting = "Af"; rekening = trans.getTegenrekening(); } else { transRichting = "Bij"; rekening = trans.getEigenbankrekening(); } String bedrag = trans.getBedrag().setScale(2, RoundingMode.HALF_EVEN).toString(); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); String datumStr = df.format(datum.getTime()); Object[] data = {datumStr, rekening, transRichting, bedrag, trans.getStatus()}; tableModel.addRow(data); } jTable1.setModel(tableModel); tableModel.fireTableDataChanged(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setOpaque(false); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTable1.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Datum", "Begunstigde", "Bij/af", "Bedrag" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Short.class, java.lang.Double.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.setOpaque(false); jTable1.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(jTable1); if (jTable1.getColumnModel().getColumnCount() > 0) { jTable1.getColumnModel().getColumn(0).setResizable(false); jTable1.getColumnModel().getColumn(0).setHeaderValue("Datum"); jTable1.getColumnModel().getColumn(1).setResizable(false); jTable1.getColumnModel().getColumn(1).setHeaderValue("Begunstigde"); jTable1.getColumnModel().getColumn(2).setResizable(false); jTable1.getColumnModel().getColumn(2).setPreferredWidth(50); jTable1.getColumnModel().getColumn(2).setHeaderValue("Bij/af"); jTable1.getColumnModel().getColumn(3).setResizable(false); jTable1.getColumnModel().getColumn(3).setHeaderValue("Bedrag"); } add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 370, 260)); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables }
Java
package Balie.gui; import API.Model.Klant; import API.Model.LoginAccount; /** De klantpanel is opgenomen in sessieframe om klantgegevens te tonen. * */ public class KlantPanel extends javax.swing.JPanel { /** * Creates new form KlantPanel */ public KlantPanel() { initComponents(); } /** * Klantgegevens worden opgehaald in getoond in het klantpanel. * @param klant klant object. * @param login loginaccount object. */ public void setGegevens(Klant klant, LoginAccount login) { jtfKlantNummer.setText(String.valueOf(klant.getKlantNr())); jtfKlantnaam.setText(klant.getKlantnaam()); jtfWoonplaats.setText(klant.getKlantwoonplaats()); jtfGebruikersnaam.setText(login.getLoginNaam()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jtfKlantNummer = new javax.swing.JTextField(); jtfGebruikersnaam = new javax.swing.JTextField(); jtfKlantnaam = new javax.swing.JTextField(); jtfWoonplaats = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jtfKlantNummer.setEditable(false); jtfKlantNummer.setBackground(new java.awt.Color(238, 238, 238)); jtfKlantNummer.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfKlantNummer.setForeground(new java.awt.Color(102, 102, 102)); jtfKlantNummer.setBorder(null); jtfKlantNummer.setOpaque(false); add(jtfKlantNummer, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 28, 350, 15)); jtfGebruikersnaam.setEditable(false); jtfGebruikersnaam.setBackground(new java.awt.Color(238, 238, 238)); jtfGebruikersnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfGebruikersnaam.setForeground(new java.awt.Color(102, 102, 102)); jtfGebruikersnaam.setBorder(null); jtfGebruikersnaam.setOpaque(false); add(jtfGebruikersnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 208, 350, 15)); jtfKlantnaam.setEditable(false); jtfKlantnaam.setBackground(new java.awt.Color(238, 238, 238)); jtfKlantnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfKlantnaam.setForeground(new java.awt.Color(102, 102, 102)); jtfKlantnaam.setBorder(null); jtfKlantnaam.setOpaque(false); add(jtfKlantnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 88, 350, 15)); jtfWoonplaats.setEditable(false); jtfWoonplaats.setBackground(new java.awt.Color(238, 238, 238)); jtfWoonplaats.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfWoonplaats.setForeground(new java.awt.Color(102, 102, 102)); jtfWoonplaats.setBorder(null); jtfWoonplaats.setOpaque(false); add(jtfWoonplaats, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 148, 350, 15)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/KlantPanel.gif"))); // NOI18N add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 230)); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JTextField jtfGebruikersnaam; private javax.swing.JTextField jtfKlantNummer; private javax.swing.JTextField jtfKlantnaam; private javax.swing.JTextField jtfWoonplaats; // End of variables declaration//GEN-END:variables }
Java
package Balie.gui; import API.IAuth; import API.IObserver; import API.Model.Rekening; import API.Model.SessieExpiredException; import java.math.BigDecimal; import java.math.RoundingMode; import java.rmi.RemoteException; import java.util.logging.Level; import java.util.logging.Logger; /** * * Panel in Sessieframe die bankrekening gegevens toont. */ public class BankrekeningPanel extends javax.swing.JPanel implements IObserver { /** * Creates new form BankrekeningPanel */ public BankrekeningPanel() { initComponents(); } /** * Methode om de gegevens van de klant in het bankrekeningpanel te zetten. * @param sessieID * @param rekening * @param loginInterface */ public void setGegevens(String sessieID, Rekening rekening, IAuth loginInterface) { this.sessieID = sessieID; this.loginInterface = loginInterface; this.rekening = rekening; } /** * Deze methode zit er in PUUR voor demo doeleinden! */ public void storten() { try { this.loginInterface.stort(sessieID, new BigDecimal(5.00).setScale(2, RoundingMode.HALF_EVEN)); } catch (RemoteException ex) { Logger.getLogger(BankrekeningPanel.class.getName()).log(Level.SEVERE, null, ex); } catch (SessieExpiredException ex) { Logger.getLogger(BankrekeningPanel.class.getName()).log(Level.SEVERE, null, ex); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jtfKredietlimiet = new javax.swing.JTextField(); jtfEigenRekening = new javax.swing.JTextField(); jtfSaldo = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jtfKredietlimiet.setEditable(false); jtfKredietlimiet.setBackground(new java.awt.Color(238, 238, 238)); jtfKredietlimiet.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfKredietlimiet.setForeground(new java.awt.Color(102, 102, 102)); jtfKredietlimiet.setBorder(null); add(jtfKredietlimiet, new org.netbeans.lib.awtextra.AbsoluteConstraints(42, 148, 330, 15)); jtfEigenRekening.setEditable(false); jtfEigenRekening.setBackground(new java.awt.Color(238, 238, 238)); jtfEigenRekening.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfEigenRekening.setForeground(new java.awt.Color(102, 102, 102)); jtfEigenRekening.setBorder(null); add(jtfEigenRekening, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 26, 350, 15)); jtfSaldo.setEditable(false); jtfSaldo.setBackground(new java.awt.Color(238, 238, 238)); jtfSaldo.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfSaldo.setForeground(new java.awt.Color(102, 102, 102)); jtfSaldo.setBorder(null); add(jtfSaldo, new org.netbeans.lib.awtextra.AbsoluteConstraints(42, 87, 330, 15)); jLabel3.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(102, 102, 102)); jLabel3.setText("€"); add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 148, 20, 15)); jLabel2.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(102, 102, 102)); jLabel2.setText("€"); add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 87, 20, 15)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/RekeningPanel.gif"))); // NOI18N add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 170)); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField jtfEigenRekening; private javax.swing.JTextField jtfKredietlimiet; private javax.swing.JTextField jtfSaldo; // End of variables declaration//GEN-END:variables private IAuth loginInterface; private Rekening rekening; private String sessieID; /** * Update de bakrekeningpanel met vernieuwde rekeninggegevens. * @param observable * @param arg * @throws RemoteException */ @Override public void update(Object observable, Object arg) throws RemoteException { rekening = (Rekening) observable; jtfEigenRekening.setText(rekening.toString()); jtfSaldo.setText(rekening.getSaldo().toString()); jtfKredietlimiet.setText(rekening.getKredietlimiet().toString()); } }
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 Balie.gui; import Balie.Controller.AEXfondsen; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import javax.swing.JOptionPane; import javax.xml.ws.WebServiceException; /** * * @author Melis */ public class AEXBannerPanel extends javax.swing.JPanel implements Runnable { protected Thread AEXBannerThread; private String text; private Font font; private int x = 1024; private int y = 25; private long delay; // interval between frames in millisec protected int offset; // distance moved between two frames protected Dimension size; // size of viewing area protected Image image; // off-screen image protected Graphics offScreen; // off-screen graphics /** * Creates new form AEXBannerPanel */ public AEXBannerPanel() { initComponents(); try { setFondsenTekst(); } catch (WebServiceException ex) { JOptionPane.showMessageDialog(this.getRootPane(), "De AEX service is helaas niet beschikbaar \nExcuses voor het ongemak"); StringBuilder sb = new StringBuilder(); sb.append(" AEX service is niet beschikbaar, excuses voor het ongemak"). append(" "). append("© Rainbow Sheep Software 2014"); text =sb.toString(); } font = new Font("Arial Unicode", Font.PLAIN, 14); delay = 20; x = 1024; y = 25; offset = 1; AEXBannerThread = new Thread(this); AEXBannerThread.start(); } public void setFondsenTekst() throws WebServiceException { AEXfondsen f = new AEXfondsen(); text = f.getFondsenInfo(); //Vervang true (als koers is gestegen) in een pijltje naar boven. text = text.replaceAll("true", "\u2191"); //Vervang false (als koers is gedaald) in een pijltje naar beneden. text = text.replaceAll("false", "\u2193"); } @Override public void paintComponent (Graphics g) { // Get de grootte van de viewing area size = this.getSize(); // Maak off-screen image buffer voor eerste keer. if (image == null) { image = createImage (size.width, size.height); offScreen = image.getGraphics(); } // Get font metrics om de lengte van de tekst te bepalen. offScreen.setFont(font); Rectangle2D lengte = font.getStringBounds(text, 0, text.length(), new FontRenderContext(new AffineTransform(), true , true)); // Wijzig de positie van de tekst van vorig scherm x = x - offset; //Wanneer tekst helemaal naar links doorgelopen is //verplaats positie van de banner weer naar de rechter rand. if (x < -lengte.getWidth()) { if(!text.startsWith(" ")) { setFondsenTekst(); } x = size.width; } // set de kleur en vul de achtergrond offScreen.setColor(Color.WHITE); offScreen.fillRect(0, 0, size.width, size.height); // Set de pen kleur and teken de tekst offScreen.setColor(Color.BLACK); offScreen.drawString(text, x, y); //TODO ----------------------------------------- //Zorgen dat kleuren in beeld veranderen nav stijging/daling koers. // Copy the off-screen image to the screen g.drawImage(image, 0, 0, this); } @Override public void update (Graphics g) { paintComponent (g); } @Override public void run () { while (Thread.currentThread() == AEXBannerThread) { repaint (); try { Thread.sleep(delay); } catch (InterruptedException e) { System.out.println ("Exception: " + e.getMessage()); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { setMaximumSize(null); setMinimumSize(new java.awt.Dimension(1024, 40)); setPreferredSize(new java.awt.Dimension(1024, 40)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1024, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 40, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
Java
package Balie.gui; import API.Model.SessieExpiredException; import Balie.Controller.ClientImpl; import java.awt.Color; import java.rmi.NotBoundException; import java.rmi.RemoteException; import javax.swing.JOptionPane; /** * NieuweKlantPanel wordt in StartFrame aangeroepen * */ public class NieuweKlantPanel extends javax.swing.JPanel { private StartFrame parentFrame; /** * Creates new form NieuweKlantPanel */ public NieuweKlantPanel() { initComponents(); } /** * Wanneer op de juiste manier geregistreerd is, moet het scherm waar deze * panel in opgenomen is, afsluiten. Vandaar de referentie van de parentframe. * @param jframereferentie Het frame waar de panel in opgenomen is. */ public NieuweKlantPanel(StartFrame jframereferentie) { initComponents(); this.parentFrame = jframereferentie; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jtfWachtwoord = new javax.swing.JPasswordField(); jtfGebruikersnaam = new javax.swing.JTextField(); jtfWoonplaats = new javax.swing.JTextField(); jtfKlantnaam = new javax.swing.JTextField(); btnRegistreren = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setOpaque(false); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 0, 0)); jLabel4.setText("*"); add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(131, 190, 20, -1)); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 0, 0)); jLabel3.setText("*"); add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(119, 0, 20, -1)); jLabel2.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 0)); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Let op! U maakt een nieuwe rekening aan."); add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 254, 350, -1)); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 0, 0)); jLabel5.setText("*"); add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(123, 60, 20, -1)); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 0, 0)); jLabel6.setText("*"); add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(161, 125, 20, -1)); jtfWachtwoord.setBorder(null); jtfWachtwoord.setOpaque(false); add(jtfWachtwoord, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 214, 330, 30)); jtfGebruikersnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfGebruikersnaam.setBorder(null); jtfGebruikersnaam.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jtfGebruikersnaamMouseClicked(evt); } }); add(jtfGebruikersnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, 330, 30)); jtfWoonplaats.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfWoonplaats.setBorder(null); add(jtfWoonplaats, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 88, 330, 30)); jtfKlantnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfKlantnaam.setBorder(null); add(jtfKlantnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 24, 330, 30)); btnRegistreren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/RegistreerButton.gif"))); // NOI18N btnRegistreren.setBorder(null); btnRegistreren.setBorderPainted(false); btnRegistreren.setFocusPainted(false); btnRegistreren.setMargin(new java.awt.Insets(0, 0, 0, 0)); btnRegistreren.setOpaque(false); btnRegistreren.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/RegistreerButtonClicked.gif"))); // NOI18N btnRegistreren.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegistrerenActionPerformed(evt); } }); add(btnRegistreren, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 290, 150, 40)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/NieuweKlantPanel.gif"))); // NOI18N add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, -1)); }// </editor-fold>//GEN-END:initComponents /** * Wanneer op de registratie button geklikt wordt, worden alle gegevens van de klant naar de server verstuurd. * @param evt */ private void btnRegistrerenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrerenActionPerformed ClientImpl clientcontroller; try { clientcontroller = new ClientImpl(); String registratieInformatie = clientcontroller.registrerenNieuweKlant(jtfKlantnaam.getText(), jtfWoonplaats.getText(), jtfGebruikersnaam.getText(), jtfWachtwoord.getText()); //Toon de melding aan gebruiker of het gelukt is of niet. JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), registratieInformatie); // maak alle velden leeg in het scherm wanneer registratie voltooid is. if (registratieInformatie.contains("Registratie voltooid")) { verversVelden(); } } catch (SessieExpiredException | NullPointerException ex) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), ex.getMessage()); } catch (IllegalArgumentException ea) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), ea.getMessage()); jtfGebruikersnaam.setForeground(Color.red); } catch (NotBoundException ex) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), "De server is momenteel offline \nExcuses voor het ongemak"); } catch (RemoteException ex) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), "Er zijn momenteel connectie problemen \nProbeert u het later nog eens"); } }//GEN-LAST:event_btnRegistrerenActionPerformed private void jtfGebruikersnaamMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtfGebruikersnaamMouseClicked jtfGebruikersnaam.setForeground(Color.black); }//GEN-LAST:event_jtfGebruikersnaamMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnRegistreren; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JTextField jtfGebruikersnaam; private javax.swing.JTextField jtfKlantnaam; private javax.swing.JPasswordField jtfWachtwoord; private javax.swing.JTextField jtfWoonplaats; // End of variables declaration//GEN-END:variables /** * Methode die alle velden leegmaakt en de gebruikersnaam die ingevuld is bij registratie klaarzet in het inlogpanel. */ private void verversVelden() { this.parentFrame.setGebruikersnaamNaRegistratie(jtfGebruikersnaam.getText()); this.jtfKlantnaam.setText(""); this.jtfWoonplaats.setText(""); this.jtfGebruikersnaam.setText(""); this.jtfWachtwoord.setText(""); this.parentFrame.SetInlogtabActief(); } }
Java
package Balie.gui; import API.Model.SessieExpiredException; import Balie.Controller.Banken; import Balie.Controller.ClientImpl; import java.rmi.NotBoundException; import java.rmi.RemoteException; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * Inlogpanel is onerdeel van het startFrame en overerft van JPanel. */ public class InlogPanel extends javax.swing.JPanel { private Banken banken; private String bankname; /** * Creates new form NewJPanel Er moet in dit geval een parameterloze * constructor voor inlogpanel aanwezig zijn, daar anders de GUI designer * van netbeans foutmeldingen gaat geven. */ public InlogPanel() { initComponents(); } /** * Creates new form NewJPanel * * @param jframereferentie */ public InlogPanel(JFrame jframereferentie) { banken = new Banken(); String[] banknames = banken.getBanknames(); bankname = banknames[0]; initComponents(); this.parentFrame = jframereferentie; fillCboBanken(banknames); } private void fillCboBanken(String[] bankNames) { this.jcboBanken.removeAllItems(); for (int i = 0; i < bankNames.length; i++) { this.jcboBanken.addItem(bankNames[i]); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel5 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtfGebruiker = new javax.swing.JTextField(); jtfWachtwoord = new javax.swing.JPasswordField(); jcboBanken = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); btnInloggen = new javax.swing.JButton(); setBackground(new java.awt.Color(255, 255, 255)); setOpaque(false); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 0, 0)); jLabel5.setText("*"); add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(136, 136, 20, -1)); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 0, 0)); jLabel4.setText("*"); add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(166, 58, 20, -1)); jtfGebruiker.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfGebruiker.setBorder(null); add(jtfGebruiker, new org.netbeans.lib.awtextra.AbsoluteConstraints(32, 84, 340, 30)); jtfWachtwoord.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfWachtwoord.setBorder(null); add(jtfWachtwoord, new org.netbeans.lib.awtextra.AbsoluteConstraints(32, 162, 340, 30)); jcboBanken.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N jcboBanken.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcboBankenActionPerformed(evt); } }); add(jcboBanken, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 240, 110, 30)); jLabel2.setBackground(new java.awt.Color(138, 138, 138)); jLabel2.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N jLabel2.setForeground(new java.awt.Color(138, 138, 138)); jLabel2.setText("Kies uw bank"); add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 220, 120, 20)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/InlogPanel.gif"))); // NOI18N add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 270)); btnInloggen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogButton.gif"))); // NOI18N btnInloggen.setBorder(null); btnInloggen.setBorderPainted(false); btnInloggen.setFocusPainted(false); btnInloggen.setMargin(new java.awt.Insets(0, 0, 0, 0)); btnInloggen.setOpaque(false); btnInloggen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogButtonClicked.gif"))); // NOI18N btnInloggen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnInloggenActionPerformed(evt); } }); add(btnInloggen, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 290, 150, 40)); }// </editor-fold>//GEN-END:initComponents /** * Wanneer op inlogbutton geklikt wordt, wordt een connectie vanuit de client opgestart en vindt er authorisatie plaats. * @param evt */ private void btnInloggenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInloggenActionPerformed String bankUrl = banken.getUrl(bankname); try { ClientImpl clientcontroller = new ClientImpl(); String sessieID = clientcontroller.getSessieIDvanInloggen(jtfGebruiker.getText(), jtfWachtwoord.getText()); SessieFrame sessieFrame; sessieFrame = new SessieFrame(sessieID, clientcontroller); sessieFrame.setVisible(true); this.parentFrame.dispose(); } catch (RemoteException ex) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), "Er zijn momenteel connectie problemen \nProbeert u het later nog eens"); } catch (IllegalArgumentException | SessieExpiredException ex) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), ex.getMessage()); } catch (NotBoundException ex) { JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), "De server is momenteel offline \nExcuses voor het ongemak"); } }//GEN-LAST:event_btnInloggenActionPerformed private void jcboBankenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboBankenActionPerformed if (banken != null & jcboBanken.getSelectedItem() != null) { bankname = jcboBanken.getSelectedItem().toString(); } }//GEN-LAST:event_jcboBankenActionPerformed public void setGebruikersnaamNaRegistratie(String gebruikersnaam) { this.jtfGebruiker.setText(gebruikersnaam); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnInloggen; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JComboBox jcboBanken; private javax.swing.JTextField jtfGebruiker; private javax.swing.JPasswordField jtfWachtwoord; // End of variables declaration//GEN-END:variables private JFrame parentFrame; }
Java
package Balie.gui; import API.IAuth; import API.ITransactieHandler; import API.Model.SessieExpiredException; import Balie.Controller.ClientImpl; import java.awt.Point; import java.math.BigDecimal; import java.rmi.RemoteException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * NieuwTransactieDialog wordt geinstantieerd vanuit startframe wanneer op button Nieuwe Transactie geklikt wordt */ public class NieuwTransactieDialog extends javax.swing.JDialog { private ClientImpl clientcontroller; private String sessieID; /** * Creates new form NieuwTransactieDialog * * @param parent Parentframe * @param modal */ public NieuwTransactieDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setLocation(new Point(500, 200)); } /** * * @param parent * @param modal * @param clientController * @param sessieID */ public NieuwTransactieDialog(java.awt.Frame parent, boolean modal, ClientImpl clientController, String sessieID) { super(parent, modal); initComponents(); setLocation(new Point(500, 200)); this.sessieID = sessieID; this.clientcontroller = clientController; IAuth auth = this.clientcontroller.getAuthificatieConnectie(); try { jtfVanRekening.setText(auth.getRekening(sessieID).toString()); } catch (RemoteException | SessieExpiredException ex) { JOptionPane.showMessageDialog(rootPane, ex.toString()); this.dispose(); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jtfVanRekening = new javax.swing.JTextField(); jtfSaldo = new javax.swing.JTextField(); jtfSaldoCenten = new javax.swing.JTextField(); jtfNaarRekening = new javax.swing.JTextField(); btnAnnuleren = new javax.swing.JButton(); btnVerzenden = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jtaOmschrijving = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Rainbow Sheep Bank"); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jtfVanRekening.setEditable(false); jtfVanRekening.setBackground(new java.awt.Color(238, 238, 238)); jtfVanRekening.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfVanRekening.setHorizontalAlignment(javax.swing.JTextField.LEFT); jtfVanRekening.setBorder(null); getContentPane().add(jtfVanRekening, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 170, 330, 20)); jtfSaldo.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfSaldo.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jtfSaldo.setText("0"); jtfSaldo.setBorder(null); jtfSaldo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jtfSaldoMouseClicked(evt); } }); getContentPane().add(jtfSaldo, new org.netbeans.lib.awtextra.AbsoluteConstraints(299, 235, 200, 30)); jtfSaldoCenten.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfSaldoCenten.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jtfSaldoCenten.setText("00"); jtfSaldoCenten.setBorder(null); jtfSaldoCenten.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jtfSaldoCentenMouseClicked(evt); } }); getContentPane().add(jtfSaldoCenten, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 235, 30, 30)); jtfNaarRekening.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtfNaarRekening.setHorizontalAlignment(javax.swing.JTextField.RIGHT); jtfNaarRekening.setBorder(null); getContentPane().add(jtfNaarRekening, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 297, 340, 30)); btnAnnuleren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/AnnulerenButton.gif"))); // NOI18N btnAnnuleren.setBorder(null); btnAnnuleren.setBorderPainted(false); btnAnnuleren.setContentAreaFilled(false); btnAnnuleren.setFocusPainted(false); btnAnnuleren.setMargin(new java.awt.Insets(0, 0, 0, 0)); btnAnnuleren.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/AnnulerenButtonClicked.gif"))); // NOI18N btnAnnuleren.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/AnnulerenButtonClicked.gif"))); // NOI18N btnAnnuleren.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAnnulerenActionPerformed(evt); } }); getContentPane().add(btnAnnuleren, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 480, 150, 40)); btnVerzenden.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/VerzendenButton.gif"))); // NOI18N btnVerzenden.setBorder(null); btnVerzenden.setBorderPainted(false); btnVerzenden.setContentAreaFilled(false); btnVerzenden.setFocusPainted(false); btnVerzenden.setMargin(new java.awt.Insets(0, 0, 0, 0)); btnVerzenden.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/VerzendenButtonClicked.gif"))); // NOI18N btnVerzenden.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/VerzendenButtonClicked.gif"))); // NOI18N btnVerzenden.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVerzendenActionPerformed(evt); } }); getContentPane().add(btnVerzenden, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 480, 150, 40)); jScrollPane1.setBorder(null); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane1.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jScrollPane1.setMaximumSize(new java.awt.Dimension(340, 60)); jtaOmschrijving.setColumns(20); jtaOmschrijving.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N jtaOmschrijving.setLineWrap(true); jtaOmschrijving.setRows(5); jtaOmschrijving.setBorder(null); jtaOmschrijving.setMaximumSize(new java.awt.Dimension(280, 115)); jScrollPane1.setViewportView(jtaOmschrijving); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 370, 340, 60)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/NieuweTransactieFrame.gif"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, 600)); pack(); }// </editor-fold>//GEN-END:initComponents private void btnVerzendenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerzendenActionPerformed //vul velden van saldo met 0 als deze leeg zijn. if (this.jtfSaldo.getText().equals("")) { this.jtfSaldo.setText("0"); } if (this.jtfSaldoCenten.getText().equals("")) { this.jtfSaldoCenten.setText("00"); } int saldo = -1; int saldoCenten = -1; String rekeningnR = null; BigDecimal transactieBedrag = new BigDecimal(0); //haal tekst uit velden op en zet deze om in integers als het mogelijk is, //vangt letters en andere niet-numerieke karakters af try { saldo = Integer.parseInt(this.jtfSaldo.getText()); saldoCenten = Integer.parseInt(this.jtfSaldoCenten.getText()); rekeningnR = this.jtfNaarRekening.getText(); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(rootPane, "Het bedrag is niet correct ingevuld"); return; } //Geef melding naar gebruiker als het aantal decimalen meer dan 2 is. //Nullen die ervoor geplaatst worden, worden niet meegenomen. if (saldoCenten > 99) { JOptionPane.showMessageDialog(rootPane, "Het transactiebedrag kan niet meer dan 2 decimalen bevatten"); return; } //Geeft melding naar gebruiker als een van de twee saldo velden een negatief bedrag bevat if (saldoCenten < 0 || saldo < 0) { JOptionPane.showMessageDialog(rootPane, "Het transactiebedrag kan geen negatieve getallen bevatten"); return; } //vervolgens wordt de saldo getallen omgezet in een big decimal. float saldoCentenf = saldoCenten; saldoCentenf = saldoCentenf / 100; float saldof = saldo + saldoCentenf; transactieBedrag = new BigDecimal(saldof); //check of het saldo groter is dan 0,00 euro. if(transactieBedrag.compareTo(new BigDecimal(0)) != 1) { JOptionPane.showMessageDialog(rootPane, "Transactie bedrag moet groter zijn dan € 0,00"); return; } //Wanneer aan alle checks voldaan is mbt saldo velden wordt request naar server gestuurd ITransactieHandler transHandeler; try { transHandeler = clientcontroller.getTransactieConnectie(); transHandeler.requestTransaction(sessieID, rekeningnR, transactieBedrag, this.jtaOmschrijving.getText()); //melding dat transactie verwerkt wordt JOptionPane.showMessageDialog(rootPane, "Transactie wordt verwerkt"); this.dispose(); } catch (SessieExpiredException | IllegalArgumentException | NullPointerException ex) { JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } catch (RemoteException ex) { JOptionPane.showMessageDialog(rootPane, "Er is een connectie probleem opgetreden, excuses voor het ongemak"); } }//GEN-LAST:event_btnVerzendenActionPerformed private void btnAnnulerenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnnulerenActionPerformed this.dispose(); }//GEN-LAST:event_btnAnnulerenActionPerformed private void jtfSaldoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtfSaldoMouseClicked jtfSaldo.setText(""); }//GEN-LAST:event_jtfSaldoMouseClicked private void jtfSaldoCentenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtfSaldoCentenMouseClicked jtfSaldoCenten.setText(""); }//GEN-LAST:event_jtfSaldoCentenMouseClicked // /** // * @param args the command line arguments // */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // // /* Create and display the dialog */ // java.awt.EventQueue.invokeLater(new Runnable() { // @Override // public void run() { // NieuwTransactieDialog dialog = new NieuwTransactieDialog(new javax.swing.JFrame(), true); // dialog.addWindowListener(new java.awt.event.WindowAdapter() { // @Override // public void windowClosing(java.awt.event.WindowEvent e) { // System.exit(0); // } // }); // dialog.setVisible(true); // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAnnuleren; private javax.swing.JButton btnVerzenden; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jtaOmschrijving; private javax.swing.JTextField jtfNaarRekening; private javax.swing.JTextField jtfSaldo; private javax.swing.JTextField jtfSaldoCenten; private javax.swing.JTextField jtfVanRekening; // End of variables declaration//GEN-END:variables }
Java
package Balie.gui; import API.Model.*; import API.*; import Balie.Controller.ClientImpl; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.rmi.RemoteException; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.Timer; /** * SessieFrame wordt geinstantieerd zodra klant zich correct heeft ingelogd middels het startFrame. */ public class SessieFrame extends javax.swing.JFrame { private IAuth auth; private String sessieID; private ClientImpl clientController; private ITransactieHandler transHandler; private Timer timer; /** * Creates new form SessieFrame * @param sessieID de sessieId van clientobj * @param clientcontroller de controller */ public SessieFrame(String sessieID, ClientImpl clientcontroller) { try { initComponents(); setLocation(new Point(400, 100)); this.clientController = clientcontroller; this.sessieID = sessieID; if (System.getSecurityManager() == null) { SecurityManager securM = new SecurityManager(); System.setSecurityManager(securM); } // haal klantgegevens op via connectie auth = clientcontroller.getAuthificatieConnectie(); Rekening rekening = auth.getRekening(sessieID); Rekening r = (Rekening) rekening; //zet welkomtekst in header met daarin klantnaam. lblWelkom.setText("Welkom " + auth.getKlant(sessieID).getKlantnaam()); //vul gegevens van bankrekeningpanel bankrekeningPanel.setGegevens(sessieID, rekening, auth); Klant klant = auth.getKlant(sessieID); LoginAccount login = auth.getLoginAccount(sessieID); //vul gegevens van klantpanel klantPanel.setGegevens(klant, login); IObservable o = (IObservable) rekening; //voeg bankrekeningpanel als observer toe. clientcontroller.addObserver(bankrekeningPanel, o); //update bankrekeningpanel met nieuwe gegevens Rekening bankrekeningPanel.update(r, null); //haal transacties op via connectie transHandler = clientcontroller.getTransactieConnectie(); transactiePanel2.setEigenRekeningNr(login.getRekeningNr()); ArrayList<Transactie> transacties; transacties = transHandler.getTransacties(sessieID, null, null); transactiePanel2.setTransacties(transacties); //start timer om om de 5000 msec een nieuwe lijst van transacties op te vragen (callback) timer = new Timer(5000, taskPerformer); timer.start(); } catch (RemoteException ex) { toonRMIExceptie(); } catch (SessieExpiredException ex) { toonSessieExceptie(ex.toString()); } } /** * Om de 5000 msec wordt deze methode aangeroepen, hierin wordt een nieuwe lijst * van transacties terug gegeven en in de gui geladen. */ ActionListener taskPerformer = new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ArrayList<Transactie> transacties; try { transacties = transHandler.getTransacties(sessieID, null, null); transactiePanel2.setTransacties(transacties); } catch (RemoteException ex) { toonRMIExceptie(); } catch (SessieExpiredException ex) { toonSessieExceptie(ex.toString()); } } }; /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnUitloggen = new javax.swing.JButton(); btnNieuweTransactie = new javax.swing.JButton(); btnMakeMeRich = new javax.swing.JButton(); bankrekeningPanel = new Balie.gui.BankrekeningPanel(); transactiePanel2 = new Balie.gui.TransactiePanel(); klantPanel = new Balie.gui.KlantPanel(); lblWelkom = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); aEXBannerPanel1 = new Balie.gui.AEXBannerPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Rainbow Sheep Bank"); setMaximumSize(new java.awt.Dimension(1024, 840)); setMinimumSize(new java.awt.Dimension(1024, 840)); setPreferredSize(new java.awt.Dimension(1024, 840)); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnUitloggen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/UitlogButton.gif"))); // NOI18N btnUitloggen.setBorder(null); btnUitloggen.setBorderPainted(false); btnUitloggen.setContentAreaFilled(false); btnUitloggen.setFocusPainted(false); btnUitloggen.setMargin(new java.awt.Insets(0, 0, 0, 0)); btnUitloggen.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/UitlogButtonClicked.gif"))); // NOI18N btnUitloggen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/UitlogButtonClicked.gif"))); // NOI18N btnUitloggen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUitloggenActionPerformed(evt); } }); getContentPane().add(btnUitloggen, new org.netbeans.lib.awtextra.AbsoluteConstraints(840, 60, 150, 40)); btnNieuweTransactie.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/TransactieButton.gif"))); // NOI18N btnNieuweTransactie.setBorder(null); btnNieuweTransactie.setBorderPainted(false); btnNieuweTransactie.setContentAreaFilled(false); btnNieuweTransactie.setFocusPainted(false); btnNieuweTransactie.setMargin(new java.awt.Insets(0, 0, 0, 0)); btnNieuweTransactie.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/TransactieButtonClicked.gif"))); // NOI18N btnNieuweTransactie.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/TransactieButtonClicked.gif"))); // NOI18N btnNieuweTransactie.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNieuweTransactieActionPerformed(evt); } }); getContentPane().add(btnNieuweTransactie, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 524, 150, 40)); btnMakeMeRich.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/BtnMakeMeRich.gif"))); // NOI18N btnMakeMeRich.setBorder(null); btnMakeMeRich.setBorderPainted(false); btnMakeMeRich.setContentAreaFilled(false); btnMakeMeRich.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION); btnMakeMeRich.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/BtnMakeMeRich_Selected.gif"))); // NOI18N btnMakeMeRich.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnMakeMeRichActionPerformed(evt); } }); getContentPane().add(btnMakeMeRich, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 670, -1, -1)); bankrekeningPanel.setOpaque(false); getContentPane().add(bankrekeningPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 214, -1, -1)); getContentPane().add(transactiePanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 220, -1, 270)); getContentPane().add(klantPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 506, -1, -1)); lblWelkom.setFont(new java.awt.Font("Calibri", 1, 48)); // NOI18N lblWelkom.setText("Welkom"); getContentPane().add(lblWelkom, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 58, 690, 40)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/SessieFrame_Background.gif"))); // NOI18N jLabel1.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 770)); jTextField1.setText("jTextField1"); getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 60, -1, -1)); javax.swing.GroupLayout aEXBannerPanel1Layout = new javax.swing.GroupLayout(aEXBannerPanel1); aEXBannerPanel1.setLayout(aEXBannerPanel1Layout); aEXBannerPanel1Layout.setHorizontalGroup( aEXBannerPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 1024, Short.MAX_VALUE) ); aEXBannerPanel1Layout.setVerticalGroup( aEXBannerPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 40, Short.MAX_VALUE) ); getContentPane().add(aEXBannerPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 770, -1, -1)); getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents private void btnUitloggenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUitloggenActionPerformed try { timer.stop(); clientController.uitloggen(); } catch (SessieExpiredException ex) { toonSessieExceptie(ex.toString()); } catch (RemoteException ex) { toonRMIExceptie(); } StartFrame startframe = new StartFrame(); startframe.setVisible(true); this.dispose(); }//GEN-LAST:event_btnUitloggenActionPerformed /** * Eventhandler wanneer de gebruiker een nieuwe transactie wilt maken. Er * wordt een nieuw jdialog scherm opgestart. * * @param evt actionevent */ private void btnNieuweTransactieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNieuweTransactieActionPerformed try { Rekening rekening = auth.getRekening(sessieID); NieuwTransactieDialog transactieDialog = new NieuwTransactieDialog(this, true, clientController, sessieID); transactieDialog.setVisible(true); } catch (RemoteException ex) { toonRMIExceptie(); } catch (SessieExpiredException ea) { toonSessieExceptie(ea.toString()); } }//GEN-LAST:event_btnNieuweTransactieActionPerformed /** * Eventhandler die aangeroepen wordt wanneer het frame afgesloten wordt. De * verbinding tussen client en server moet verbroken worden. * * @param evt windowevent */ private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing try { this.timer.stop(); clientController.uitloggen(); } catch (SessieExpiredException ex) { toonSessieExceptie(ex.toString()); } catch (RemoteException ex) { toonRMIExceptie(); } }//GEN-LAST:event_formWindowClosing /** * Wanneer op de make me rich buton wordt geklikt wordt geld op de rekening gestort * Alleen voor demo doeleinden geimplementeerd. * @param evt */ private void btnMakeMeRichActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMakeMeRichActionPerformed this.bankrekeningPanel.storten(); }//GEN-LAST:event_btnMakeMeRichActionPerformed /** * RemoteException wordt in de gui op dezelfde wijze afgevangen, vandaar een aparte methode. */ private void toonRMIExceptie() { timer.stop(); JOptionPane.showMessageDialog(rootPane, "Er is helaas een connectie probleem opgetreden \nU wordt uitgelogd."); SessieFrame.this.dispose(); StartFrame sf = new StartFrame(); sf.setVisible(true); } /** * SessieExpiredException wordt in de gui op dezelfde wijze afgevangen, vandaar een aparte methode. * @param bericht de foutmelding */ private void toonSessieExceptie(String bericht) { timer.stop(); JOptionPane.showMessageDialog(rootPane, bericht); SessieFrame.this.dispose(); StartFrame sf = new StartFrame(); sf.setVisible(true); } // Variables declaration - do not modify//GEN-BEGIN:variables private Balie.gui.AEXBannerPanel aEXBannerPanel1; private Balie.gui.BankrekeningPanel bankrekeningPanel; private javax.swing.JButton btnMakeMeRich; private javax.swing.JButton btnNieuweTransactie; private javax.swing.JButton btnUitloggen; private javax.swing.JLabel jLabel1; private javax.swing.JTextField jTextField1; private Balie.gui.KlantPanel klantPanel; private javax.swing.JLabel lblWelkom; private Balie.gui.TransactiePanel transactiePanel2; // End of variables declaration//GEN-END:variables }
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 Balie.gui; import java.awt.Point; /** * * @author Melis */ public class StartFrame extends javax.swing.JFrame { /** * Creates new form NewJFrame */ public StartFrame() { initComponents(); setLocation(new Point(400, 100)); nieuweKlantPanel1.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { inlogPanel1 = new Balie.gui.InlogPanel(this); nieuweKlantPanel1 = new Balie.gui.NieuweKlantPanel(this); tabNieuweKlant = new javax.swing.JButton(); tabInloggen = new javax.swing.JButton(); jlbl_Background = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Rainbow Sheep Bank"); setMinimumSize(new java.awt.Dimension(1024, 768)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); getContentPane().add(inlogPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 260, -1, -1)); getContentPane().add(nieuweKlantPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 260, -1, -1)); tabNieuweKlant.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabInactive.gif"))); // NOI18N tabNieuweKlant.setBorder(null); tabNieuweKlant.setBorderPainted(false); tabNieuweKlant.setContentAreaFilled(false); tabNieuweKlant.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N tabNieuweKlant.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N tabNieuweKlant.setMargin(new java.awt.Insets(0, 0, 0, 0)); tabNieuweKlant.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabHover.gif"))); // NOI18N tabNieuweKlant.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N tabNieuweKlant.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N tabNieuweKlant.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tabNieuweKlantActionPerformed(evt); } }); getContentPane().add(tabNieuweKlant, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 187, -1, -1)); tabInloggen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabInactive.gif"))); // NOI18N tabInloggen.setBorder(null); tabInloggen.setBorderPainted(false); tabInloggen.setContentAreaFilled(false); tabInloggen.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabActive.gif"))); // NOI18N tabInloggen.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabActive.gif"))); // NOI18N tabInloggen.setEnabled(false); tabInloggen.setMargin(new java.awt.Insets(0, 0, 0, 0)); tabInloggen.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabHover.gif"))); // NOI18N tabInloggen.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabActive.gif"))); // NOI18N tabInloggen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tabInloggenActionPerformed(evt); } }); getContentPane().add(tabInloggen, new org.netbeans.lib.awtextra.AbsoluteConstraints(304, 187, -1, -1)); jlbl_Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/BackgroundStartFrame.gif"))); // NOI18N jlbl_Background.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION); jlbl_Background.setOpaque(false); getContentPane().add(jlbl_Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void tabNieuweKlantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabNieuweKlantActionPerformed setRegistratietabActief(); }//GEN-LAST:event_tabNieuweKlantActionPerformed /** * wanneer op de tab inloggen geklikt wordt, wordt de inlogtab actief gezet. * @param evt */ private void tabInloggenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabInloggenActionPerformed SetInlogtabActief(); }//GEN-LAST:event_tabInloggenActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } new StartFrame().setVisible(true); } }); } /** * Methode om in een childpanel van dit frame, een textfield te vullen met een gebruikersnaam die bij registratie ingevoerd is. * @param gebruikersnaam gebruikersnaam van nieuwe klant. */ public void setGebruikersnaamNaRegistratie(String gebruikersnaam) { this.inlogPanel1.setGebruikersnaamNaRegistratie(gebruikersnaam); } // Variables declaration - do not modify//GEN-BEGIN:variables private Balie.gui.InlogPanel inlogPanel1; private javax.swing.JLabel jlbl_Background; private Balie.gui.NieuweKlantPanel nieuweKlantPanel1; private javax.swing.JButton tabInloggen; private javax.swing.JButton tabNieuweKlant; // End of variables declaration//GEN-END:variables /** * Deze methode moet voor Registratiepanel beschikbaar zijn, zodat wanneer een klant succesvol geregistreerd is, * Er binnen de gui direct overgschakeld kan worden naar de inlogtab. */ public void SetInlogtabActief() { tabInloggen.setEnabled(false); tabNieuweKlant.setEnabled(true); inlogPanel1.setVisible(true); nieuweKlantPanel1.setVisible(false); } /** * Deze methode staat op private want geen enkel andere klasse hoeft deze methode te benaderen. * Wanneer op registratietab geklikt wordt, wordt deze methode aangeroepen. */ private void setRegistratietabActief() { tabInloggen.setEnabled(true); tabNieuweKlant.setEnabled(false); inlogPanel1.setVisible(false); nieuweKlantPanel1.setVisible(true); } }
Java
package nl.rainbowsheep.aex; import java.util.Random; /** * Model klasse voor een AEX Fonds. De naam en de koers worden hier in bijgehouden. */ public class Fonds { private double koers; private final String naam; private boolean gestegen; private double procentgewijzigd; //1000 = gelijk aan 100 procent. /** * Constructor waarbij de naam en de initiele koers moeten worden opgegeven. * @param naam Naam van het fonds * @param koers huidige koers van het fonds. */ public Fonds(String naam, double koers) { this.naam = naam; this.koers = koers; this.gestegen = true; this.procentgewijzigd = 0; } /** * Methode om de naam van de koers op te vragen. * @return naam van de koers */ public String getNaam() { return naam; } /** * Methode om de naam te zetten. * Zonder deze methode is getNaam niet beschikbaar via de webservice, wordt dan ook niet geimplementeerd! * @param naam naam van de koers */ public void setNaam(String naam) { } /** * Retourneert de huidige koers van het Fonds */ public double getKoers() { return koers; } /** * Methode om de koers van het Fonds te zetten. * @param koers huidige koers waarde. */ public void setKoers(double koers) { if (this.koers > koers) { this.gestegen = false; } else { this.gestegen = true; } this.koers = koers; } /** * get methode om op te vragen hoeveel procent de koers is gewijzigd tov laatste koers. * @return double percentage. */ public double getProcentgewijzigd() { return procentgewijzigd; } /** * Zonder deze methode is getProcentgewijzigd niet beschikbaar via de webservice, wordt dan ook niet geimplementeerd! * @param procentgewijzigd het percentage dat koers afwijkt tov vorige koers. */ public void setProcentgewijzigd(double procentgewijzigd) { } /** * een get methode om op te vragen of koers gestegen is. * @return true als koers is gestegen tov vorige koers, false als koers is gedaald tov vorige koers. */ public boolean isGestegen() { return gestegen; } /** * Zonder deze methode is isGestegen niet beschikbaar via de webservice, wordt dan ook niet geimplementeerd! * @param gestegen true als koers gestegen is, false als koers niet gestegen is. */ public void setGestegen(boolean gestegen) { } /**Methode om nieuwe koers te berekenen. * Koers kan maximaal 5% verschillen van oorspronkelijke koers. * */ public void NieuweKoersberekenen() { double nieuwekoers; double verschil = Math.random(); //Alles boven de 0,5 betekent een stijging van de koers. if (verschil > 0.5) { verschil = (verschil-0.5)/10; nieuwekoers = this.koers + (verschil * this.koers); } //alles onder de 0,5 betekent een daling van de koers. else { verschil = verschil/10; nieuwekoers = this.koers - (verschil * this.koers); } this.procentgewijzigd = maakGetalEenDecimaal(verschil*100); nieuwekoers = maakGetalEenDecimaal(nieuwekoers); this.setKoers(nieuwekoers); } /** * Methode om van een getal met meerdere cijfers achter de komma * te beperken tot 1 cijfer achter de komma. * @param num het getal met meerdere cijfers achter de komma * @return getal met 1 decimaal. */ public static double maakGetalEenDecimaal(double num) { double result = num * 100; result = Math.round(result); result = result / 100; return result; } }
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 nl.rainbowsheep.aex; import java.util.Collection; import javax.jws.WebService; import manager.FondsManager; /** * Webservice klasse om de fondsen beschikbaar te stellen via een SOAP api. * @author Ieme */ @WebService public class AEX { /** * Methode om alle fondsen op te vragen * @return Collection van alle fondsen (List) */ public Collection<Fonds> getFondsen() { return (Collection) FondsManager.getInstance().getFondsen(); } // /** // * Methode om de koers van een fonds op te vragen gegeven de fondsnaam // * @param fondsNaam de naam van het fonds // * @return koers wanneer fonds is gevonden, anders null. (fondsmanager returns null) // */ // public double getKoers(@WebParam(name = "fondsNaam") String fondsNaam) { // return FondsManager.getInstance().getFonds(fondsNaam).getKoers(); // } }
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 nl.rainbowsheep.aex; import javax.xml.ws.Endpoint; import manager.DummyFondsen; /** * Klasse om de webservice te kunnen testen. * @author Ieme */ public class Server { public static void main(String[] args) { DummyFondsen dummy = new DummyFondsen(); Endpoint.publish("http://localhost:9009/AEX/AEX", new AEX()); } }
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 manager; import nl.rainbowsheep.aex.Fonds; /** * Klasse om even wat dummy gegevens te laden. * @author Ieme */ public class DummyFondsen { public DummyFondsen() { addKoersen(); } private void addKoersen() { FondsManager fm = FondsManager.getInstance(); fm.addFonds(new Fonds("Aegon", 6.38)); fm.addFonds(new Fonds("Ahold", 13.45)); fm.addFonds(new Fonds("Akzo Nobel", 54.98)); fm.addFonds(new Fonds("ArcelorMittal", 10.90)); fm.addFonds(new Fonds("ASML", 67.34)); fm.addFonds(new Fonds("Boskalis", 42.60)); fm.addFonds(new Fonds("Corio", 37.43)); fm.addFonds(new Fonds("Delta Lloyd Groep", 18.68)); fm.addFonds(new Fonds("DSM", 51.75)); fm.addFonds(new Fonds("Fugro", 44.98)); fm.addFonds(new Fonds("Gemalto", 81.86)); fm.addFonds(new Fonds("Heineken", 53.35)); fm.addFonds(new Fonds("ING Groep", 10.40)); fm.addFonds(new Fonds("KPN", 2.75)); fm.addFonds(new Fonds("OCI", 27.89)); fm.addFonds(new Fonds("Philips", 22.86)); fm.addFonds(new Fonds("Rainbow Sheep", 0.32)); fm.addFonds(new Fonds("Randstad", 40.94)); fm.addFonds(new Fonds("Reed Elsevier", 16.79)); fm.addFonds(new Fonds("Royal Dutch Shell", 29.84)); fm.addFonds(new Fonds("SBM Offshore", 11.92)); fm.addFonds(new Fonds("TNT Express", 6.52)); fm.addFonds(new Fonds("Unibail-Rodamco", 208.15)); fm.addFonds(new Fonds("Unilever", 32.37)); fm.addFonds(new Fonds("Wolters Kluwer", 22.08)); fm.addFonds(new Fonds("Ziggo", 33.47)); } }
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 manager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import javax.swing.Timer; import nl.rainbowsheep.aex.Fonds; /** * Klasse om fondsen beschikbaar te stellen via een webservice. * @author Ieme */ public class FondsManager { private HashMap<String, Fonds> fondsen; private Timer timer; /** * Lazy loaded singleton pattern. */ private static class Loader { private static final FondsManager instance = new FondsManager(); } /** * Constructor voor FondManager */ private FondsManager() { this.fondsen = new HashMap<>(); BerekenNieuweKoersenTimer(); timer.start(); } /** * FondManager wordt eenmalig opgestart en met deze methode kan de huidige * FondManager opgevraagd worden. * * @return Actieve FondManager object */ public static FondsManager getInstance() { return Loader.instance; } /** * Methode om een fonds toe te voegen aan de fondsmanager, * @param fonds */ public synchronized void addFonds(Fonds fonds) { if (!this.fondsen.containsKey(fonds.getNaam())) { fondsen.put(fonds.getNaam(), fonds); } } /** * methode om alle fondsen op te vragen. * @return ArrayList met alle fondsen */ public synchronized ArrayList<Fonds> getFondsen() { ArrayList<Fonds> fondsenList = new ArrayList(); for (Fonds f : fondsen.values()) { fondsenList.add(f); } return fondsenList; } /** * Methode om 1 fonds op te vragen aan de hand van de naam. * @param fondsNaam naam van op te vragen fonds * @return fonds wanneer gevonden, anders null. */ public synchronized Fonds getFonds(String fondsNaam) { if (fondsNaam != null) { return fondsen.get(fondsNaam); } return null; } private synchronized void setWillekeurigeKoersen() { for (Fonds f : this.fondsen.values()) { f.NieuweKoersberekenen(); } } private void BerekenNieuweKoersenTimer() { timer = new Timer(6000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setWillekeurigeKoersen(); } }); } }
Java
package API; /** * IObservable klasse is om een een observer-observable patroon in te bouwen. * De klasse die dit implementeert is de observable. */ public interface IObservable { /** * voegt een observer object toe * @param observer IObserver object. */ void addObserver(IObserver observer); /** * Methode om ID van een observable op te vragen. * @return integer ID van observable. */ public int getObservableId(); }
Java
package API; import API.Model.TransactieType; import API.Model.SessieExpiredException; import API.Model.TransactieStatus; import API.Model.Transactie; import java.math.BigDecimal; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.GregorianCalendar; /** * Interface tussen client en bank. Client kan verschillende transacties ophalen bij de bank middels het gebruik van deze interface. */ public interface ITransactieHandler extends IObserver { /** * Hiermee wordt een nieuwe transactie aangevraagd. * @param sessieId sessieID van een actieve sessie * @param recipientRekeningnummer rekeningnummer van de ontvanger * @param bedrag het over te maken bedrag * @param comment beschrijving die bij de transactie ingevuld is * @return Transactie object * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. * @throws IllegalArgumentException wordt gegooid wanneer tegenrekeningnr hetzelfde is als het van-rekeningnummer */ public Transactie requestTransaction(String sessieId, String recipientRekeningnummer, BigDecimal bedrag, String comment) throws RemoteException, SessieExpiredException, IllegalArgumentException; /** * Methode om bestaande transactie op te zoeken tussen gegeven datums. * De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie! * @param sessieId sessieId van een actieve sessie * @param vanafDatum Datum vanaf we transactie opzoeken * @param totDatum Datum tot we transacties opzoeken. Null = heden. * @return ArrayList met transactie objects. * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum) throws RemoteException, SessieExpiredException; /** * Methode om bestaande transactie op te zoeken tussen gegeven datums. * De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie! * @param sessieId sessieId van een actieve sessie * @param vanafDatum Datum vanaf we transactie opzoeken * @param totDatum Datum tot we transacties opzoeken. mag null zijn. * @param status status van de transacties. type TransactieStatus * @return ArrayList met transactie objects. * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status) throws RemoteException, SessieExpiredException; /** * Methode om bestaande transactie op te zoeken tussen gegeven datums. * De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie! * @param sessieId sessieId van een actieve sessie * @param vanafDatum Datum vanaf we transactie opzoeken * @param totDatum Datum tot we transacties opzoeken. mag null zijn. * @param type type van de transactie als TransactieType. (debet of credit t.o.v. de aanvrager) * @return ArrayList met transactie objects. * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieType type) throws RemoteException, SessieExpiredException; /** * Methode om bestaande transactie op te zoeken tussen gegeven datums. * De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie! * @param sessieId sessieId van een actieve sessie * @param vanafDatum Datum vanaf we transactie opzoeken * @param totDatum Datum tot we transacties opzoeken. mag null zijn. * @param status status van de transacties. type TransactieStatus * @param type type van de transactie als TransactieType. (debet of credit t.o.v. de aanvrager) * @return ArrayList met transactie objects. * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status, TransactieType type) throws RemoteException, SessieExpiredException; }
Java
package API; import API.Model.SessieExpiredException; import java.rmi.Remote; import java.rmi.RemoteException; /** * Deze interface wordt geinstantieerd aan de client zijde. * * Zodoende kan de server methodes van de client aanroepen. De server kan de * client remote "uitloggen" en kan de client laten weten dat het saldo van de * rekening is gewijzigd. * */ public interface IClient extends Remote { /** * Methode om de client te melden dat de sessie is verlopen en dat hij uitgelogd wordt. * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. * @throws SessieExpiredException */ public void uitloggen() throws RemoteException, SessieExpiredException; /** * Methode om een observable te zetten bij de client. * @param ob observable object. * @throws RemoteException Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. */ public void setObservable(IObservable ob) throws RemoteException; }
Java
package API; import java.rmi.Remote; import java.rmi.RemoteException; /** * Interface voor Observer-observable patroon. Ipv overerving worden interfaces geimplementeerd. */ public interface IObserver extends Remote { /** * Methode om aan het object die een ander object observeert, een update te geven van een nieuw object. * @param observable Een object dat observable object * @param arg Het geupdate object dat door de observable gebruikt wordt. * @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden. */ void update(Object observable, Object arg) throws RemoteException; }
Java
package API; import API.Model.Klant; import API.Model.LoginAccount; import API.Model.Rekening; import API.Model.SessieExpiredException; import java.math.BigDecimal; import java.rmi.RemoteException; /** * Interface waarmee client een sessie kan starten en een client haar basis * gegevens kan opvragen Tevens verantwoordelijk voor bijhouden * clientRMIobjecten * */ public interface IAuth extends IObserver { /** * Deze methode is alleen bedoeld voor DEMO doeleinden. * @param sessieId sessieID van client. * @param bedrag Het bedrag. * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public void stort(String sessieId, BigDecimal bedrag) throws RemoteException, SessieExpiredException; /** * Starten van een sessie. Mits succesvol wordt er een sessieId terug * gegeven, anders null * * @param username client username om in te loggen * @param password client password om in te loggen * @return String sessieId of null * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. */ public String startSessie(String username, String password) throws RemoteException, IllegalArgumentException; /** * Hiermee kan een ClientObj geregistreert worden bij de server. Zodoende * kan de server remote calls maken bij de client. * * @param sessieId sessieId van actieve sessie * @param clientObj IClient object om remote calls uit te voeren bij de * client. * @throws RemoteException wordt gegooid wanneer de sessie van de klant verlopen is. * @throws SessieExpiredException wordt gegooid wanneer er RMI problemen zijn. */ public void registreerClientObject(String sessieId, IClient clientObj) throws RemoteException, SessieExpiredException; /** * Hiermee kan een bestaande sessie worden beeindigd. Returned true als het * gelukt is, anders false. * * @param sessionId sessieId van bestaande sessie * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public void stopSessie(String sessionId) throws RemoteException, SessieExpiredException; /** * Methode om wachtwoord aan te passen. * * @param sessionId sessieId van bestaande sessie * @param username username van de client. * @param password nieuwe password van de client. * @return true wanneer succesvol. * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public boolean resetWachtwoord(String sessionId, String username, String password) throws RemoteException, SessieExpiredException; /** * Methode om klant object (gegevens) van een actieve sessie te verkrijgen * * @param sessionId sessieID van actieve sessie * @return Klant object. * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public Klant getKlant(String sessionId) throws RemoteException, SessieExpiredException; /** * Methode om rekening object bij een actieve sessie te verkrijgen. * * @param sessionId sessieId van actieve sessie * @return Rekening object bij actieve sessie. * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public Rekening getRekening(String sessionId) throws RemoteException, SessieExpiredException; /** * Methode om loginaccount object bij een actieve sessie op te vragen. * @param sessionId sessieId van actieve sessie * @return LoginAccount object bij actieve sessie. * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. * @throws SessieExpiredException wordt gegooid wanneer de sessie van de klant verlopen is. */ public LoginAccount getLoginAccount(String sessionId) throws RemoteException, SessieExpiredException; /** * Methode om een nieuwe klant + loginaccount + rekening aan te maken. * @param klantnaam naam van de klant. * @param woonplaats woonplaats van de klant. * @param gebruikersnaam gebruikersnaam van de klant. * @param wachtwoord wachtwoord van de klant. * @return true als het gelukt is om een nieuwe klant te registreren, false als het niet gelukt is. * @throws RemoteException wordt gegooid wanneer er RMI problemen zijn. */ public boolean registreerNieuweKlant(String klantnaam, String woonplaats, String gebruikersnaam, String wachtwoord) throws NullPointerException, IllegalArgumentException, RemoteException; }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package API.Model; /** * Custom exceptie klasse voor een verlopen sessie die overerft van exception. */ public class SessieExpiredException extends Exception { /** * Constructor voor SessieExpiredException zonder parameters */ public SessieExpiredException() { } /** * Constructor voor SessieExpiredException * @param message een bericht */ public SessieExpiredException(String message) { super(message); } /** * Constructor voor SessieExpiredException * @param cause Throwable object */ public SessieExpiredException(Throwable cause) { super(cause); } /** * Constructor voor SessieExpiredException * @param message een bericht * @param cause Throwable object */ public SessieExpiredException(String message, Throwable cause) { super(message, cause); } }
Java
package API.Model; /** * Enum klasse voor de statussen van een transactie. */ public enum TransactieStatus { /** Wanneer een transactie verwerkt is door de bank krijgt het de status voltooid. */ VOLTOOID, /** Wanneer een transactie nog niet verwerkt is door de bank krijgt het de status openstaand, * alleen tijdens deze status kan de transactie geannuleerd worden. */ OPENSTAAND, /** Wanneer een transactie tijdig geannuleerd wordt, zal het niet door de bank worden * verwerkt. */ GEANNULEERD, /** Wanneer een transactie niet verwerkt kon worden door de bank omdat er iets mis is gegaan * (bijvoorbeeld de connectie met de centrale instantie) wordt de transactie tijdelijk uitgesteld. */ UITGESTELD, /** * Wanneer een transactie geaccepteerd is door centrale instelling. */ GEACCEPTEERD, /** Wanneer de bank de transactie probeerde te verwerken, maar er geen bestaande tegenrekeningnummer * was, zal de transactie geweigerd worden. */ GEWEIGERD; }
Java
package API.Model; import java.math.BigDecimal; import java.util.GregorianCalendar; import java.util.Locale; /** * De klasse transatie is verantwoordelijk voor het registreren van een * overboeking. Hierbij is het bedrag van belang, en het rekeningnummer waar het * vanaf geschreven moet worden en de tegenrekening waarbij het bedrag * bijgeboekt moet worden. */ public class Transactie extends BaseObservable { //transient zodat het tijdens het serializeren niet wordt opgeslagen (niet meegestuurd over RMI). //volatile zodat het automatisch gesynchronizeerd wordt en nextTransactieId blijft altijd beschikbaar. //volatile variablen kunnen niet locked raken. private transient static volatile int nextTransactieId; private final int transactieId; private final String eigenbankrekening; private final String tegenrekening; private final String commentaar; private final BigDecimal bedrag; private final GregorianCalendar transactieInvoerDatum; private TransactieStatus status; /** * De constructor van Transactie. Hierin wordt als transactieInvoerDatum de * datum van vandaag gepakt. De status van de transactie staat op OPENSTAAND * bij het aanmaken van een nieuwe transactie. * * @param eigenbankrekening de rekening waarvan het bedrag afgeschreven moet * worden. * @param tegenrekening de rekening waar het bedrag bij geschreven moet * worden. * @param bedrag het bedrag wat overgemaakt wordt. * @param comment bij elke overboeking kan er commentaar of een * betalingskenmerk ingevuld worden. */ public Transactie(String eigenbankrekening, String tegenrekening, BigDecimal bedrag, String comment) { this.eigenbankrekening = eigenbankrekening; this.tegenrekening = tegenrekening; this.bedrag = bedrag; this.commentaar = comment; this.status = TransactieStatus.OPENSTAAND; this.transactieInvoerDatum = new GregorianCalendar(Locale.GERMANY); this.transactieId = nextTransactieId; Transactie.nextTransactieId++; } /** * De status van een transactie kan veranderen in loop van tijd. * * @param status de status die de transactie moet krijgen. */ public void setStatus(TransactieStatus status) { this.status = status; this.setChanged(); this.notifyObservers(); } /** * Een get-methode voor het transactieID. * * @return Het transactieID. */ public int getTransactieId() { return transactieId; } /** * Een get-methode voor de rekening waarvan het bedrag afgeschren moet * worden. * * @return de rekening waar het bedrag van afgeschreven wordt. */ public String getEigenbankrekening() { return eigenbankrekening; } /** * Een get-methode voor de rekening waar het bedrag bij geschreven moet * worden. * * @return de tegenrekening */ public String getTegenrekening() { return tegenrekening; } /** * Een get-methode voor het bedrag * * @return het bedrag */ public BigDecimal getBedrag() { return bedrag; } /** * Een get-methode voor de transactiestatus * * @return de transactiestatus */ public TransactieStatus getStatus() { return status; } /** * Een get-methode voor de datum dat de transactie ingevoerd is. * * @return de datum dat de transactie ingevoerd is. */ public GregorianCalendar getTransactieInvoerDatum() { return transactieInvoerDatum; } /** * Bij een transactie kan commentaar toegevoegd worden. * @return de commentaar / beschrijving die toegevoegd is bij transactie. */ public String getCommentaar() { return commentaar; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package API.Model; import java.math.BigDecimal; import java.math.RoundingMode; /** * De klasse Rekening heeft als verantwoordelijkheid om rekeninggegevens. zoals * het saldo en kredietlimiet bij te houden. */ public class Rekening extends BaseObservable { private final String rekeningnummer; private BigDecimal saldo = new BigDecimal(0.00); private final BigDecimal kredietlimiet = new BigDecimal(100.00); //transient zodat het tijdens het serializeren niet wordt opgeslagen (niet meegestuurd over RMI) private transient static volatile int nextrekeningnummer = 1000; /** * Deze constructor maakt een nieuw rekeningnummer. Bij een nieuwe Rekening * is het saldo altijd 0 en het kredietlimiet is 100. * @param bankinitialen De 4 letters die identiek zijn voor een bank, waarmee een rekening begint. */ public Rekening(String bankinitialen) { super(); this.rekeningnummer = bankinitialen + nextrekeningnummer; nextrekeningnummer++; } /** * Een get-methode voor het rekeningnummer. * @return het rekeningnummer. */ public synchronized String getRekeningnummer() { return rekeningnummer; } /** * Een get-methode voor het saldo. * @return het saldo. */ public synchronized BigDecimal getSaldo() { return saldo.setScale(2, RoundingMode.HALF_EVEN); } /** * Een get-methode voor het kredietlimiet. * * @return het kredietlimiet. */ public synchronized BigDecimal getKredietlimiet() { return kredietlimiet.setScale(2, RoundingMode.HALF_EVEN); } /** * Een methode die gebruikt wordt om een bedrag op te nemen van een rekening (wordt gebruikt aangesproken door het uitvoeren van een Transactie). * @param bedrag het op te nemen bedrag * @return true als het bedrag afgeschreven is, false als het niet afgeschreven kon worden. */ public synchronized boolean neemOp(BigDecimal bedrag) { if (bedrag.compareTo(new BigDecimal(0)) == 1) { BigDecimal saldoTotaal = new BigDecimal(0.00); saldoTotaal = saldoTotaal.add(this.saldo); saldoTotaal = saldoTotaal.add(this.kredietlimiet); if (saldoTotaal.compareTo(bedrag) == 1 | saldoTotaal.compareTo(bedrag)== 0) { this.saldo = this.saldo.subtract(bedrag); setChanged(); notifyObservers(); return true; } } return false; } /** * methode om geld op een rekening te storten (aangeroepen bij het uitvoeren van een transactie). * @param bedrag het te storten bedrag */ public synchronized void stort(BigDecimal bedrag) { if (bedrag.compareTo(new BigDecimal(0)) == 1) { this.saldo = this.saldo.add(bedrag); } setChanged(); notifyObservers(); } /** * Een toString methode voor Rekening die de toString methode van Object * overschrijft. * @return het rekeningnummer. */ @Override public String toString() { return this.rekeningnummer; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof Rekening)) { return false; } Rekening r = (Rekening) obj; return rekeningnummer.equals(r.getRekeningnummer()); } }
Java
package API.Model; import API.IObservable; import API.IObserver; import java.io.Serializable; import java.rmi.RemoteException; import java.util.Observable; import java.util.Observer; /** * Base klasse voor observer/observable mechanisme. De observer klasses zijn * naast observers tevens Remote objecten, hierdoor is dubbele overerving * vereist. Om dit mogelijk te maken gebruiken we IObserver en IObservable. * Observable model klasse kunnen van deze klasse overerven om dubbele code te * vermijden. * */ public class BaseObservable extends Observable implements IObservable, Serializable { //transient zodat het niet geserialiseerd wordt meegestuurd. private transient static volatile int nextObservableId = 0; private final int observableId; /** * Nested klasse zodat de implementatie van observer/observable niet * opnieuw hoeft te worden geimplementeerd. */ private class WrappedObserver implements Observer, Serializable { private IObserver ro = null; public WrappedObserver(IObserver ro) { this.ro = ro; } @Override public void update(Observable o, Object arg) { try { ro.update(o, arg); } catch (RemoteException e) { System.out.println("Remote exception removing observer:" + this); o.deleteObserver(this); } } } /** * Methode om Iobserver te wrappen in een "echte" observer * @param o Iobserver */ @Override public synchronized void addObserver(IObserver o) { WrappedObserver mo = new WrappedObserver(o); addObserver(mo); } /** * Contructor voor observable. Zet gelijk het observableid. */ public BaseObservable() { this.observableId = nextObservableId; nextObservableId++; } /** * Get methode voor observablie ID * @return het observable ID */ @Override public int getObservableId() { return this.observableId; } }
Java
package API.Model; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * De verantwoordelijkheid van de Klasse klant, is het bijhouden van de naam en * woonplaats van de klant. De combinatie van naam, woonplaats en loginaccount * moeten uniek zijn wil de klant zich registreren bij een bank. */ public class Klant extends BaseObservable { private static Pattern karakterPattern; private static Pattern plaatsPattern; private final int klantNr; private String klantnaam; private String klantwoonplaats; //nog uit te breiden met postcode etc. private transient static volatile int nextklantnummer = 1; /** * De constructor voor Klant. * * @param klantnaam de naam van de klant. * @param klantwoonplaats de woonplaats van de klant. */ public Klant(String klantnaam, String klantwoonplaats) { //wanneer klant zijn gegevens heeft ingevoerd zonder hoofdletter(s) // zal de eerste letter een hoofdletter moeten zijn. this.klantnaam = capitaliseerWoord(klantnaam); this.klantwoonplaats = capitaliseerWoord(klantwoonplaats); this.klantNr = nextklantnummer; nextklantnummer++; } /** * Wanneer een klant een naamswijziging doorgeeft kan dat met onderstaande * methode verwerkt worden. * * @param klantnaam de nieuwe naam van de klant. */ public void setKlantnaam(String klantnaam) { this.klantnaam = klantnaam; } /** * Wanneer een klant een nieuwe woonplaats doorgeeft, kan dat met * onderstaande methode worden verwerkt. * * @param klantwoonplaats de nieuwe woonplaats van de klant. */ public void setKlantwoonplaats(String klantwoonplaats) { this.klantwoonplaats = klantwoonplaats; } /** * Een get-methode voor de klantnaam. * * @return de naam van de klant. */ public String getKlantnaam() { return klantnaam; } /** * Een get-methode voor de woonplaats van de klant. * * @return de woonplaats van de klant. */ public String getKlantwoonplaats() { return klantwoonplaats; } /** * Een get-methode voor het klantnummer van de klant. * * @return het klantnummer van de klant. */ public int getKlantNr() { return klantNr; } /** * Methode om te zorgen dat bepaalde gegevens van de klant altijd starten * met een hoofdletter en de rest kleine letters. * * @param string de tekst die omgezet moet worden. * @return de tekst die omgezet is. */ private String capitaliseerWoord(String string) { String[] token = string.split(" "); StringBuilder stringbuilder = new StringBuilder(); for (int i = 0; i < token.length; ++i) { String naam = token[i].toLowerCase(); naam = naam.substring(0, 1).toUpperCase() + naam.substring(1); stringbuilder.append(naam).append(" "); } //laatste spatie er uit halen die automatisch toegevoegd wordt aan de stringbuilder. return stringbuilder.toString().substring(0, stringbuilder.length() - 1); } /** * Een toString methode voor Klant die de toString methode van Object * overschrijft. * * @return de naam van de klant. */ @Override public String toString() { return this.klantnaam; } /** * Methode om te controleren of een string alleen uit letters bestaat. * * @param toCompare String om te controleren * @return true wanneer voldoet, anders false */ public static boolean isAlphabetical(String toCompare) { if (karakterPattern == null) { karakterPattern = Pattern.compile("[a-zA-Z]+"); } Matcher matcher = karakterPattern.matcher(toCompare); return matcher.matches(); } /** * Methode om te controleren of een string een plaatsnaam bevat. Nederlandse plaatsnamen mogen gebruik maken van verschillende karakters als - of '. * Deze methode controleert op karakters en composities van alle plaatsnamen uit onderstaande lijst: * http://nl.wikipedia.org/wiki/Lijst_van_Nederlandse_plaatsen * * @param toCompare De te vergelijken string. * @return True wannneer de string voldoet aan de eisen van een plaatsnaam, anders false */ public static boolean isPlaatsnaam(String toCompare) { if (plaatsPattern == null) { plaatsPattern = Pattern.compile("^(([2][e][[:space:]]|['][ts][-[:space:]]))?[ëéÉËa-zA-Z]{2,}((\\s|[-](\\s)?)[ëéÉËa-zA-Z]{2,})*$"); } Matcher matcher = plaatsPattern.matcher(toCompare); return matcher.matches(); //"^(([2][e][[:space:]]|['][ts][-[:space:]]))?[ëéÉËa-zA-Z]{2,}((\\s|[-](\\s)?)[ëéÉËa-zA-Z]{2,})*$" } }
Java
package API.Model; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * De verantwoordelijkheid van de klasse LoginAccount is het bijhouden van een * inlognaam en een wachtwoord. Een inlognaam mag niet vaker voorkomen bij een * bank (een wachtwoord wel). */ public class LoginAccount extends BaseObservable { private String loginnaam; private transient String loginwachtwoord; private final int klantNr; private final String rekeningNr; private static Pattern karakterPattern; /** * De constructor van LoginAccount * * @param loginnaam de loginnaam van de klant * @param loginwachtwoord het loginwachtwoord van de klant * @param klantNr klantnummer van de klant. * @param rekeningNr rekeningnummer van de klant. */ public LoginAccount(String loginnaam, String loginwachtwoord, int klantNr, String rekeningNr) { this.loginnaam = loginnaam; this.loginwachtwoord = loginwachtwoord; this.klantNr = klantNr; this.rekeningNr = rekeningNr; } /** * Een get-methode voor de loginnaam * * @return de loginnaam */ public String getLoginNaam() { return this.loginnaam; } /** * Een get methode om klantnummer op te vragen. * * @return het klantnummer */ public int getKlantNr() { return klantNr; } /** * Een get methode om wachtwoord te verkrijgen bij loginaccount * * @return het wachtwoord. */ public String getLoginwachtwoord() { return loginwachtwoord; } /** * Een get methode voor het rekeningnummer die gekoppeld is aan het * loginaccount * * @return het rekeningnummer */ public String getRekeningNr() { return rekeningNr; } /** * Wanneer een klant bij het inloggen zijn wachtwoord is vergeten, moet het * mogelijk zijn (of worden) om het wachtwoord te wijzigen. * * @param nieuwwachtwoord het nieuwe wachtwoord */ public void setWachtwoord(String nieuwwachtwoord) { this.loginwachtwoord = nieuwwachtwoord; } /** * Een toString methode voor LoginAccount die de toString methode van Object * overschrijft. * * @return de loginnaam. */ @Override public String toString() { return this.loginnaam; } /** * Methode om te controleren of de gebruikersnaam voldoet aan de * voorwaarden. Gebruikersnaam mag letters en cijfers bevatten * * @param toCompare String om te controleren * @return true wanneer voldoet, anders false */ public static boolean isAlphanumeric(String toCompare) { if (karakterPattern == null) { karakterPattern = Pattern.compile("\\w+"); } Matcher matcher = karakterPattern.matcher(toCompare); return matcher.matches(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package API.Model; /** * Gebruiken om transacties op te zoeken. * */ public enum TransactieType { /** Wanneer er geld op een rekening gestort wordt, zal dit debet zijn. */ DEBET, /** Wanneer er geld van een bankrekening afgehaald wordt, zal dit credit zijn. */ CREDIT, /** Wanneer er geld van een bankrekening wordt gehaald of wordt gestort. */ ALLE; }
Java
package api; import java.math.BigDecimal; import java.rmi.Remote; import java.rmi.RemoteException; /** * Remote interface waarmee de banken kunnen communiceren met de centrale instelling. * Via deze interface kan er bijv. een cross-bank transactie worden aangevraagd. */ public interface ICiServer extends Remote { /** * Methode om ICiClient bekend te maken bij de centrale instelling. * @param prefix rekeningnummer prefix van bank * @param key authentificatie sleutel * @param clientObj ICiClient van bank * @return String waarde met status codes. * @throws RemoteException */ public String setClient(String prefix, String key, ICiClient clientObj) throws RemoteException; /** * Methode om een cross-bank transactie aan te vragen. * @param prefix rekeningnummer prefix van aanvragende bank * @param key authenticatiesleutel * @param vanRekening Rekeningnummer van de aanvrager. * @param naarRekening Tegenrekening * @param bedrag het over te maken bedrag * @param comment Commentaar bij de transactie * @return String waarde met status codes. * @throws RemoteException * @throws IllegalArgumentException */ public String requestTransaction(String prefix, String key, String vanRekening, String naarRekening, BigDecimal bedrag, String comment) throws RemoteException, IllegalArgumentException; }
Java
package api; import java.math.BigDecimal; import java.rmi.Remote; import java.rmi.RemoteException; /** * Client interface voor banken. Hiermee kan de centrale instelling communiceren met de betreffende bank. */ public interface ICiClient extends Remote { /** * Methode waarmee de centrale instelling een transactie aan kan vragen bij een bank. Benodigd voor cross-bank transacties * Dit is verder niet uitgewerkt. Hier missen bijv. nog verschillende referenties van de verschillende banken. * @param vanRekening Aanvragende rekening * @param naarRekening Tegen rekening * @param bedrag bedrag van de transacti e * @param comment opmerkingen e.d. geplaatst bij de transactie. * @return String retourneert een bericht om aan te geven of dit gelukt is. * @throws RemoteException */ public String transactionRequested(String vanRekening, String naarRekening, BigDecimal bedrag, String comment) throws RemoteException; }
Java
package CiClient; import api.ICiClient; import java.math.BigDecimal; import java.rmi.RemoteException; /** * Klasse binnen bank die als client voor centrale instelling dient. * Deze klasse implementeert ICiClient en kan berichten sturen naar de centrale instelling. */ public class CiClient implements ICiClient { /** * * @param vanRekening * @param naarRekening * @param bedrag * @param comment * @return * @throws RemoteException */ @Override public String transactionRequested(String vanRekening, String naarRekening, BigDecimal bedrag, String comment) throws RemoteException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
Java
package CiClient; import api.ICiServer; import java.math.BigDecimal; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; /** * Klasse om de bankclient te verbinden met Centrale Instelling. */ public class CiConnector { private final String ciServerURL = "127.0.0.1"; private static String prefix; private static String key; private static ICiServer ciStub; private static Registry registry; /** * Constructor voor CiConnector die een aanroep doet naar setRegistry(). * @throws RemoteException moet afgevangen worden als er gebruik gemaakt wordt van RMI * @throws NotBoundException moet afgevangen worden wanneer centrale instelling offline is. */ public CiConnector() throws RemoteException, NotBoundException { setRegistry(); } /** * Constructor met 2 overloads * @param prefix unieke bankinitialen van de bank. * @param key validatiesleutel van de bank * @throws RemoteException moet afgevangen worden als er gebruik gemaakt wordt van RMI * @throws NotBoundException moet afgevangen worden wanneer centrale instelling offline is. */ public CiConnector(String prefix, String key) throws RemoteException, NotBoundException { this.prefix = prefix; this.key = key; setRegistry(); } /** * Methode die de registry zet. In deze methode wordt een referentie op gevraagd bij RMI Registry op de gespecificeerde host en port. * @throws RemoteException moet afgevangen worden als er gebruik gemaakt wordt van RMI */ private synchronized void setRegistry() throws RemoteException { if (registry == null) { if (System.getSecurityManager() == null) { SecurityManager securM = new SecurityManager(); System.setSecurityManager(securM); } registry = LocateRegistry.getRegistry(this.ciServerURL, 1100); } } /** * Methode die de stub van centrale instelling opzoekt. * Daarbij wordt de remote referentie die gebonden is aan de gespecificeerde naam in de registry opgevraagd. * @throws NotBoundException moet afgevangen worden wanneer centrale instelling offline is. * @throws RemoteException moet afgevangen worden als er gebruik gemaakt wordt van RMI */ private synchronized void lookupCiStub() throws NotBoundException, RemoteException { if (ciStub == null) { ciStub = (ICiServer) registry.lookup("ci"); } } /** * * @param vanRekening * @param naarRekening * @param bedrag * @param comment * @return * @throws RemoteException * @throws NotBoundException */ public synchronized String requestTransaction(String vanRekening, String naarRekening, BigDecimal bedrag, String comment) throws RemoteException, NotBoundException { lookupCiStub(); if (ciStub != null) { return ciStub.requestTransaction(prefix, key, vanRekening, naarRekening, bedrag, comment); } return null; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package managers; import API.Model.Klant; import java.util.HashMap; /** * De klantmanager klasse houdt een hashmap waar klanten te zoeken zijn op * klantnr */ public class KlantManager { private HashMap<Integer, Klant> klanten; //klantNr, KlantObject /** * */ private static class Loader { private static final KlantManager instance = new KlantManager(); } /** * Constructor voor klantmanager */ private KlantManager() { this.klanten = new HashMap<>(); } /** * Klantmanager wordt eenmalig opgestart en met deze methode kan de huidige klantmanager opgevraagd worden. * @return Actieve KlantManager object */ public static KlantManager getInstance() { return Loader.instance; } /** * deze methode voegt een klant toe aan de klantmanager * @param klant Klant object * @return true indien het toevoegen gelukt is, anders false */ public boolean addKlant(Klant klant) { synchronized (this.klanten) { if (this.klanten.get(klant.getKlantNr()) == null) { this.klanten.put(klant.getKlantNr(), klant); return true; } } return false; } /** * deze methode stuurt de klant terug met het gekozen klantnr * @param klantNr het klantnr van de klant * @return gekozen klant */ public Klant getKlant(int klantNr) { synchronized (this.klanten) { return this.klanten.get(klantNr); } } /** * Methode die kijkt of een klant al bekend is in het systeem wanneer * hij/zij zich registreert. Dan kan het bestaande klantnummer meegegeven * worden. * * @param naam * @param woonplaats * @return */ public int getBestaandeKlantNummer(String naam, String woonplaats) { String klantnaam = capitaliseerWoord(naam); String klantwoonplaats = capitaliseerWoord(woonplaats); for (Klant klant : this.klanten.values()) { if (klant.getKlantnaam().equals(klantnaam) && klant.getKlantwoonplaats().equals(klantwoonplaats)) { return klant.getKlantNr(); } } return 0; } /** * deze functie zet de eerste letter van een string in hoofdletter en de * rest van de string in kleine letters. * * @param string de string die aangepast moet worden * @return string */ private String capitaliseerWoord(String string) { String[] token = string.split(" "); StringBuilder stringbuilder = new StringBuilder(); for (int i = 0; i < token.length; ++i) { String naam = token[i].toLowerCase(); naam = naam.substring(0, 1).toUpperCase() + naam.substring(1); stringbuilder.append(naam).append(" "); } //laatste spatie er uit halen die automatisch toegevoegd wordt aan de stringbuilder. return stringbuilder.toString().substring(0, stringbuilder.length() - 1); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package managers; import java.util.TimerTask; /** * SessieTask om een sessie te kunnen beindigen na inactiviteit. Kan gebruikt * worden i.c.m. java.util.Timer. * */ public class SessieTask extends TimerTask { /** * constructor voor SessieTask. */ public SessieTask() { } /** * Run methode voor Sessietask waarin gekeken wordt of er sessie verlopen zijn binnen * de SessieManager. */ @Override public void run() { SessieManager sm = SessieManager.getInstance(); sm.expireCheck(); } }
Java
package managers; import API.IClient; import API.Model.LoginAccount; import controller.Sessie; import API.Model.SessieExpiredException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.logging.Level; import java.util.logging.Logger; /** * de SessieManager klasse houdt een hashmap bij waarin alle sessies worden bijgehouden. * Deze zijn te zoeken op SessieID. */ public class SessieManager { //Hashmap zodat we met O(1) op sessieId kunnen zoeken. //zoeken op Sessie referentie is gelijk aan ArrayList O(n); private HashMap<String, Sessie> sessies; private Timer timer; private long timerInterval = 1000; private SessieTask sessieTask; /** * Methode om een loginaccount bij een sessie op te vragen zonder dat de laatste activiteit geupdate wordt. * Vanuit de gui wordt er elke keer een callback gedaan om de transactielijst te verversen. Hierbij mag de * lastActivity niet veranderd worden bij de betreffende sessie. * @param sessieId SessieID behorende bij client die zijn loginaccount opvraagd. * @return LoginAccount object * @throws SessieExpiredException moet afgevangen worden om te kijken of sessie verlopen is. */ public LoginAccount getAccountFromSessieNoActivityChange(String sessieId) throws SessieExpiredException { synchronized (sessies) { if (sessieId != null) { Sessie sessie = sessies.get(sessieId); if (sessie != null) { return sessie.getLoginNoActivityChange(); } else { throw new SessieExpiredException("Sessie verlopen"); } } } return null; } /** * Klasse loader wordt aangeroepen in de getInstance methode binnen SessieManager. * En zorgt dat er een nieuwe SessieManager opgestart wordt wanneer dit nog niet gedaan is. * Lazy-loaded singleton pattern */ private static class Loader { private static final SessieManager instance = new SessieManager(); } /** * Private constructor voor SessieManager die alleen in klasse Loader wordt aangeroepen. * */ private SessieManager() { this.sessies = new HashMap<>(); scheduleExpireCheck(); } /** * Methode om SessieManager op te vragen. * @return actieve SessieManager. */ public static SessieManager getInstance() { return Loader.instance; } /** * voegt een sessie toe aan de SessieManager * @param sessie de toe te voegen sessie * @return true indien de sessie is toegevoegd, anders false */ public boolean addSessie(Sessie sessie) { if (sessie != null) { synchronized (this.sessies) { if (this.sessies.get(sessie.getSessieId()) == null) { this.sessies.put(sessie.getSessieId(), sessie); return true; } } } return false; } /** * stuurt sessie terug met het opgegeven sessieId * @param sessieId sessieId van de terug te sturen sessie * @return sessie indien deze in de SessieManager voorkomt, anders null */ private Sessie getSessie(String sessieId) { synchronized (sessies) { if (sessieId != null) { Sessie sessie = sessies.get(sessieId); return sessie; } } return null; } /** * stuurt een loginaccount terug waarbij de sessie het opgegeven sessieId heeft * @param sessieId het sessieId van de sessie * @return loginaccount van het gekozen sessieId indien deze is gevonden, anders null * @throws SessieExpiredException moet afgevangen worden om te kijken of sessie verlopen is. */ public LoginAccount getAccountFromSessie(String sessieId) throws SessieExpiredException { synchronized (sessies) { if (sessieId != null) { Sessie sessie = sessies.get(sessieId); if (sessie != null) { return sessie.getLogin(); } else { throw new SessieExpiredException("Sessie verlopen"); } } } return null; } /** * Methode die zorgt dat sessietask om de zoveel tijd wordt uitgevoerd. */ private void scheduleExpireCheck() { try { if (timer != null) { timer.cancel(); } } catch (IllegalStateException e) { } finally { timer = new Timer(); sessieTask = new SessieTask(); timer.schedule(sessieTask, timerInterval); } } /** * Methode die kijkt of sessies 10 minuten ongebruikt zijn, logt ze dan uit. */ public void expireCheck() { java.util.Date date = new java.util.Date(); synchronized (this.sessies) { for (Map.Entry pair : this.sessies.entrySet()) { Sessie sessie = (Sessie) pair.getValue(); long verschil = date.getTime() - sessie.getLastActivity().getTime(); //Check of tijd toeneemt bij een sessieID wanneer daarbij geen activiteit heeft plaatsgevonden. //System.out.println("Sessie ID: " + sessie.getSessieId() + " Verschil: " + verschil ); if (verschil > 600000) { IClient clientOb = sessie.getClient(); try { clientOb.uitloggen(); } catch (RemoteException ex) { Logger.getLogger(SessieManager.class.getName()).log(Level.SEVERE, null, ex); } catch (SessieExpiredException ex) { Logger.getLogger(SessieManager.class.getName()).log(Level.SEVERE, null, ex); } finally { this.sessies.remove(sessie.getSessieId()); } } } } scheduleExpireCheck(); } /** * Methode om clientobject aan een sessieID te koppelen. * @param sessieId sessieID van clientobject. * @param clientObject behorende bij het sessieID. * @throws SessieExpiredException moet afgevangen worden om te kijken of de sessie verlopen is. */ public void bindClientObjecToSessie(String sessieId, IClient clientObject) throws SessieExpiredException { synchronized (this.sessies) { Sessie sessie = this.sessies.get(sessieId); if (sessie != null) { sessie.setClient(clientObject); } else { throw new SessieExpiredException("Sessie verlopen"); } } } /** * Methode om IClient op te vragen. * @param sessieId die gekoppeld is aan de gevraagde IClient object. * @return IClient object. * @throws SessieExpiredException moet afgevangen worden om te kijken of de sessie verlopen is. */ public synchronized IClient getClient(String sessieId) throws SessieExpiredException { if (sessieId != null && sessies.get(sessieId) != null) { Sessie sessie = sessies.get(sessieId); return sessie.getClient(); } return null; } /** * Methode die de sessie verwijderd. * @param sessieId sessieId van de te verwijderen Sessie */ public void stopSessie(String sessieId) { if (sessieId != null || sessieId.isEmpty()) { synchronized (sessies) { if (sessies.containsKey(sessieId)) { sessies.remove(sessieId); } } } } }
Java
package managers; import API.Model.Rekening; import java.util.HashMap; /** * de RekeningManager klasse houdt een hashmap met rekeningen waarbij op * rekeningnummer gezocht kan worden. */ public class RekeningManager { private HashMap<String, Rekening> rekeningen; private String bankinitialen; /** * Klasse loader wordt aangeroepen in de getInstance methode binnen SessieManager. * En zorgt dat er een nieuwe SessieManager opgestart wordt wanneer dit nog niet gedaan is. * Lazy-loaded singleton pattern */ private static class Loader { final static RekeningManager instance = new RekeningManager(); } /** * Constructor voor Rekeningmanager */ private RekeningManager() { this.rekeningen = new HashMap<>(); } /** * Methode om actieve rekeningmanager op te vragen. * * @return RekeningManager object. */ public static RekeningManager getInstance() { return Loader.instance; } /** * voegt een rekening toe aan de rekeningmanager * * @param rekening de toe te voegen rekening * @return true indien de rekening is toegevoegd, anders false */ public boolean addRekening(Rekening rekening) { if (rekening != null) { synchronized (this.rekeningen) { if (this.rekeningen.get(rekening.getRekeningnummer()) == null) { this.rekeningen.put(rekening.getRekeningnummer(), rekening); return true; } } } return false; } /** * stuurt rekeningobject terug met gekozen rekeningnr * * @param rekeningNr het rekeningnummer van het terug te sturen * rekeningobject. * @return gekozen Rekening */ public Rekening getRekening(String rekeningNr) { synchronized (this.rekeningen) { return this.rekeningen.get(rekeningNr); } } /** * Methode om bij een bank elk rekeningnummer te starten met de initialen van de betreffende bank. * @param banknaam naam van de bank. */ public void setBankInitialen(String banknaam) { String banknaamHoofdletters = banknaam.toUpperCase(); StringBuilder sb = new StringBuilder(); for (int i=0; i < 4; i++) { sb.append(banknaamHoofdletters.charAt(i)); } this.bankinitialen = sb.toString(); } /** * Get methode om bankinitialen op te vragen om deze in een rekening te zetten. * @return */ public String getBankInitialen() { return this.bankinitialen; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package managers; import API.Model.LoginAccount; import java.util.HashMap; /** * De loginmanager klasse houdt een hashmap bij waarin loginaccounts te vinden zijn op loginnr */ public class LoginManager { private HashMap<String, LoginAccount> logins; //loginNr, loginObject; /** * Deze klasse wordt aangeroepen in de getInstance methode binnen LoginManager. * Dit is een vorm van Good Practice. */ private static class Loader { private static final LoginManager instance = new LoginManager(); } /** * private constructor voor LoginManager die alleen in Loader klasse wordt aangeroepen. */ private LoginManager() { this.logins = new HashMap<>(); } /** * Methode om de instantie van LoginManager op te vragen. * @return Actieve LoginManager object */ public static LoginManager getInstance() { return Loader.instance; } /** * voegt een loginaccount toe aan de loginmanager * @param login het toe te voegen loginaccount * @return true indien het toevoegen is gelukt, false indien dit niet is gelukt. */ public boolean addLogin(LoginAccount login) { if (login != null) { synchronized (this.logins) { if (this.logins.get(login.getLoginNaam()) == null) { this.logins.put(login.getLoginNaam(), login); return true; } } } return false; } /** * deze methode stuurt het loginaccount terug indien het opgegeven naam * en wachtwoord correct zijn. * Indien de loginnaam niet bestaat of het wachtwoord niet klopt zal dit * door middel van een exception door worden gegeven. * @param loginNaam de loginnaam van het op te vragen loginaccount * @param password het wachtwoord van het op te vragen loginaccount * @return LoginAccount indien naam en wachtwoord correct * @throws IllegalArgumentException */ public LoginAccount getLoginAccount(String loginNaam, String password) throws IllegalArgumentException { synchronized (this.logins) { LoginAccount login = this.logins.get(loginNaam); if (login == null) { throw new IllegalArgumentException("Onbekende gebruikersnaam"); } if (login.getLoginwachtwoord().equals(password)) { return login; } else { throw new IllegalArgumentException("Foutief wachtwoord"); } } } /** * checkt indien de opgegeven loginNaam al bestaat. * @param loginNaam de te checken naam van het inlogaccount * @return false indien de loginnaam niet bestaat */ public boolean bestaatLoginNaam(String loginNaam) { synchronized(this.logins) { LoginAccount login = this.logins.get(loginNaam); if (login == null) { return false; } else { throw new IllegalArgumentException("Loginnaam is al in gebruik"); } } } }
Java
package managers; import API.Model.Rekening; import API.Model.Transactie; import API.Model.TransactieStatus; import API.Model.TransactieType; import CiClient.CiConnector; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Klasse TransactieManager wordt eenmalig geinstantieerd en houdt een lijst bij van alle transacties. */ public class TransactieManager { private static volatile TransactieManager instance = null; private HashMap<Integer, Transactie> transacties; private CiConnector ciConnector; /** * Klasse loader wordt aangeroepen in de getInstance methode binnen TransactieManager. * En zorgt dat er een nieuwe SessieManager opgestart wordt wanneer dit nog niet gedaan is. * Lazy-loaded singleton pattern */ private static class Loader { private static final TransactieManager instance = new TransactieManager(); } /** * Private constructor voor TransactieManager die alleen in klasse Loader wordt aangeroepen. * */ private TransactieManager() { this.transacties = new HashMap<>(); } /** * Methode om Transactiemanager op te vragen. * @return actieve Transactiemanager. */ public static TransactieManager getInstance() { return Loader.instance; } /** * Methode om een transactie toe te voegen aan de hashmap. * @param trans Transactie object. */ public void addTransactie(Transactie trans) { if (trans != null) { synchronized (transacties) { if (transacties.get(trans.getTransactieId()) == null) { if (trans.getStatus() == TransactieStatus.OPENSTAAND) { Rekening creditRekeningNr = RekeningManager.getInstance().getRekening(trans.getEigenbankrekening()); if (creditRekeningNr == null) { trans.setStatus(TransactieStatus.GEWEIGERD); } } transacties.put(trans.getTransactieId(), trans); executeTransactions(); } }; } } /** * Methode om een transactie uit te voeren (dus te verwerken). */ //uitvoeren van transacties kan beter in aparte threads worden gedaan. Voor nu zo gelaten. private void executeTransactions() { synchronized (transacties) { for (Map.Entry pair : this.transacties.entrySet()) { Transactie trans = (Transactie) pair.getValue(); if (RekeningManager.getInstance().getRekening(trans.getTegenrekening()) == null) { executeForeignBankTransaction(trans); } else { executeTransaction(trans); } } }; } /** * Methode die aangeroepen wordt wanneer een transactie wordt geplaatst waarbij tegenrekeningnummer van een andere bank is. * @param trans Transactie object. */ private void executeForeignBankTransaction(Transactie trans) { if (trans != null) { if (trans.getStatus() == TransactieStatus.OPENSTAAND) { Rekening creditRekeningNr = RekeningManager.getInstance().getRekening(trans.getEigenbankrekening()); if (creditRekeningNr.neemOp(trans.getBedrag())) { if (this.ciConnector == null) { try { this.ciConnector = new CiConnector(); } catch (RemoteException | NotBoundException ex) { creditRekeningNr.stort(trans.getBedrag()); Logger.getLogger(TransactieManager.class.getName()).log(Level.SEVERE, null, ex); } } try { String requestResult = this.ciConnector.requestTransaction(trans.getEigenbankrekening(), trans.getTegenrekening(), trans.getBedrag(), trans.getCommentaar()); System.out.println(requestResult); //requestResult bestaat altijd uit een aantal cijfers en een dubbele punt: //zie CentraleInstelling.java voor de exacte implementatie. String[] resultTokens = requestResult.split(":"); //Wanneer de geretourneerde string start met 200 betekent dat de transactie geaccepteerd is en dat de transactiestatus veranderd. // een andere geretourneerde code betekend dat de transactie niet geaccepteerd is en de status veranderd naar geweigerd. if (resultTokens[0].equals("200")) { trans.setStatus(TransactieStatus.GEACCEPTEERD); } else { trans.setStatus(TransactieStatus.GEWEIGERD); creditRekeningNr.stort(trans.getBedrag()); } } catch (RemoteException | NotBoundException ex) { creditRekeningNr.stort(trans.getBedrag()); Logger.getLogger(TransactieManager.class.getName()).log(Level.SEVERE, null, ex); } } } } } /** * Methode om één transactie uit te voeren. Waarbji van-rekening en tegen-rekening binnen deze bank bekend zijn. * @param trans Transactie */ private void executeTransaction(Transactie trans) { if (trans != null) { if (trans.getStatus() == TransactieStatus.OPENSTAAND) { Rekening creditRekeningNr = RekeningManager.getInstance().getRekening(trans.getEigenbankrekening()); Rekening debitRekeningNr = RekeningManager.getInstance().getRekening(trans.getTegenrekening()); if (debitRekeningNr != null & creditRekeningNr != null) { if (creditRekeningNr.neemOp(trans.getBedrag())) { debitRekeningNr.stort(trans.getBedrag()); trans.setStatus(TransactieStatus.VOLTOOID); } else { trans.setStatus(TransactieStatus.GEWEIGERD); } } else { trans.setStatus(TransactieStatus.GEWEIGERD); } } } } /** * Deze methode wordt gebruikt om transacties op te vragen. * @param creditRknNr van-rekeningnummer * @param debetRknNr tegen-rekeningnummer * @param vanafDatum de startdatum van de transacties die opgehaald worden. * @param totDatum de einddatum van de transacties die opgehaald worden. * @param status de status van de transacties. * @param type de type transactie (credit/debet). * @return Een lijst van transacties. */ public ArrayList<Transactie> getTransacties(String creditRknNr, String debetRknNr, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status, TransactieType type) { ArrayList<Transactie> gezochteTransactie = new ArrayList<>(); GregorianCalendar searchVanafDatum; GregorianCalendar searchTotDatum; if (vanafDatum == null | vanafDatum instanceof GregorianCalendar == false) { searchVanafDatum = new GregorianCalendar(); //geen datum opgegeven is standaard 30 dagen terug. searchVanafDatum.add(Calendar.DAY_OF_MONTH, -30); } else { searchVanafDatum = vanafDatum; } if (totDatum == null | totDatum instanceof GregorianCalendar == false) { searchTotDatum = new GregorianCalendar(); } else { searchTotDatum = totDatum; } synchronized (transacties) { for (Map.Entry pair : this.transacties.entrySet()) { Transactie t = (Transactie) pair.getValue(); if (status == null | status == t.getStatus()) { //nog aanpassen. Dit is een exclusive search i.p.v. inclusive if (t.getTransactieInvoerDatum().before(searchTotDatum) && t.getTransactieInvoerDatum().after(searchVanafDatum)) { //wanneer debetRknr is opgegeven maakt type niet uit. if (debetRknNr != null & creditRknNr.equals(t.getEigenbankrekening())) { gezochteTransactie.add(t); } else { switch (type) { case ALLE: //aanvragen die niet voltooid zijn mogen niet zichtbaar zijn voor de ontvanger. if (t.getStatus() == TransactieStatus.VOLTOOID) { if (creditRknNr.equals(t.getEigenbankrekening()) | creditRknNr.equals(t.getTegenrekening())) { gezochteTransactie.add(t); } } else { if (creditRknNr.equals(t.getEigenbankrekening())) { gezochteTransactie.add(t); } } break; case DEBET: if (creditRknNr.equals(t.getTegenrekening()) & debetRknNr.equals(t.getEigenbankrekening())) { gezochteTransactie.add(t); } break; case CREDIT: if (creditRknNr.equals(t.getEigenbankrekening()) & debetRknNr.equals(t.getTegenrekening())) { gezochteTransactie.add(t); } break; } } } } } } return gezochteTransactie; } }
Java