repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/PreferenceActivity.java
/* * Copyright (c) 2015 Oleksandr Tyshkovets <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.ActionBar; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.preference.PreferenceManager; import android.view.MenuItem; import android.view.View; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.ui.passcode.PasscodeLockActivity; import butterknife.BindView; import butterknife.ButterKnife; /** * Activity for unified preferences */ public class PreferenceActivity extends PasscodeLockActivity implements PreferenceFragmentCompat.OnPreferenceStartFragmentCallback{ public static final String ACTION_MANAGE_BOOKS = "org.gnucash.android.intent.action.MANAGE_BOOKS"; @BindView(R.id.slidingpane_layout) SlidingPaneLayout mSlidingPaneLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); ButterKnife.bind(this); mSlidingPaneLayout.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) { //nothing to see here, move along } @Override public void onPanelOpened(View panel) { ActionBar actionBar = getSupportActionBar(); assert actionBar != null; actionBar.setTitle(R.string.title_settings); } @Override public void onPanelClosed(View panel) { //nothing to see here, move along } }); String action = getIntent().getAction(); if (action != null && action.equals(ACTION_MANAGE_BOOKS)){ loadFragment(new BookManagerFragment()); mSlidingPaneLayout.closePane(); } else { mSlidingPaneLayout.openPane(); loadFragment(new GeneralPreferenceFragment()); } ActionBar actionBar = getSupportActionBar(); assert actionBar != null; actionBar.setTitle(R.string.title_settings); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onPreferenceStartFragment(PreferenceFragmentCompat caller, Preference pref) { String key = pref.getKey(); Fragment fragment = null; try { Class<?> clazz = Class.forName(pref.getFragment()); fragment = (Fragment) clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); //if we do not have a matching class, do nothing return false; } loadFragment(fragment); mSlidingPaneLayout.closePane(); return false; } /** * Load the provided fragment into the right pane, replacing the previous one * @param fragment BaseReportFragment instance */ private void loadFragment(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: android.app.FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(); } else { finish(); } return true; default: return false; } } /** * Returns the shared preferences file for the currently active book. * Should be used instead of {@link PreferenceManager#getDefaultSharedPreferences(Context)} * @return Shared preferences file */ public static SharedPreferences getActiveBookSharedPreferences(){ return getBookSharedPreferences(BooksDbAdapter.getInstance().getActiveBookUID()); } /** * Return the {@link SharedPreferences} for a specific book * @param bookUID GUID of the book * @return Shared preferences */ public static SharedPreferences getBookSharedPreferences(String bookUID){ Context context = GnuCashApplication.getAppContext(); return context.getSharedPreferences(bookUID, Context.MODE_PRIVATE); } @Override public void onBackPressed() { if (mSlidingPaneLayout.isOpen()) super.onBackPressed(); else mSlidingPaneLayout.openPane(); } }
5,992
34.252941
102
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/PreferenceHeadersFragment.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings; import android.os.Bundle; import android.support.v7.preference.PreferenceFragmentCompat; import org.gnucash.android.R; /** * Fragment for displaying preference headers * @author Ngewi Fet <[email protected]> */ public class PreferenceHeadersFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle bundle, String s) { addPreferencesFromResource(R.xml.preference_fragment_headers); } }
1,106
29.75
75
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/TransactionsPreferenceFragment.java
/* * Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.preference.SwitchPreferenceCompat; import org.gnucash.android.R; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.model.Commodity; import org.gnucash.android.ui.settings.dialog.DeleteAllTransactionsConfirmationDialog; import java.util.Currency; import java.util.List; /** * Fragment for displaying transaction preferences * @author Ngewi Fet <[email protected]> * */ public class TransactionsPreferenceFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName(BooksDbAdapter.getInstance().getActiveBookUID()); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.title_transaction_preferences); } @Override public void onCreatePreferences(Bundle bundle, String s) { addPreferencesFromResource(R.xml.fragment_transaction_preferences); } @Override public void onResume() { super.onResume(); SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences(); String defaultTransactionType = sharedPreferences.getString( getString(R.string.key_default_transaction_type), getString(R.string.label_debit)); Preference pref = findPreference(getString(R.string.key_default_transaction_type)); setLocalizedSummary(pref, defaultTransactionType); pref.setOnPreferenceChangeListener(this); pref = findPreference(getString(R.string.key_use_double_entry)); pref.setOnPreferenceChangeListener(this); String keyCompactView = getString(R.string.key_use_compact_list); SwitchPreferenceCompat switchPref = (SwitchPreferenceCompat) findPreference(keyCompactView); switchPref.setChecked(sharedPreferences.getBoolean(keyCompactView, false)); String keySaveBalance = getString(R.string.key_save_opening_balances); switchPref = (SwitchPreferenceCompat) findPreference(keySaveBalance); switchPref.setChecked(sharedPreferences.getBoolean(keySaveBalance, false)); String keyDoubleEntry = getString(R.string.key_use_double_entry); switchPref = (SwitchPreferenceCompat) findPreference(keyDoubleEntry); switchPref.setChecked(sharedPreferences.getBoolean(keyDoubleEntry, true)); Preference preference = findPreference(getString(R.string.key_delete_all_transactions)); preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showDeleteTransactionsDialog(); return true; } }); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.getKey().equals(getString(R.string.key_use_double_entry))){ boolean useDoubleEntry = (Boolean) newValue; setImbalanceAccountsHidden(useDoubleEntry); } else { setLocalizedSummary(preference, newValue.toString()); } return true; } /** * Deletes all transactions in the system */ public void showDeleteTransactionsDialog(){ DeleteAllTransactionsConfirmationDialog deleteTransactionsConfirmationDialog = DeleteAllTransactionsConfirmationDialog.newInstance(); deleteTransactionsConfirmationDialog.show(getActivity().getSupportFragmentManager(), "transaction_settings"); } /** * Hide all imbalance accounts when double-entry mode is disabled * @param useDoubleEntry flag if double entry is enabled or not */ private void setImbalanceAccountsHidden(boolean useDoubleEntry) { String isHidden = useDoubleEntry ? "0" : "1"; AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); List<Commodity> commodities = accountsDbAdapter.getCommoditiesInUse(); for (Commodity commodity : commodities) { String uid = accountsDbAdapter.getImbalanceAccountUID(commodity); if (uid != null){ accountsDbAdapter.updateRecord(uid, DatabaseSchema.AccountEntry.COLUMN_HIDDEN, isHidden); } } } /** * Localizes the label for DEBIT/CREDIT in the settings summary * @param preference Preference whose summary is to be localized * @param value New value for the preference summary */ private void setLocalizedSummary(Preference preference, String value){ String localizedLabel = value.equals("DEBIT") ? getString(R.string.label_debit) : getActivity().getString(R.string.label_credit); preference.setSummary(localizedLabel); } }
5,798
38.719178
131
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/dialog/DeleteAllAccountsConfirmationDialog.java
/* * Copyright (c) 2013 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings.dialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; import org.gnucash.android.R; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity; import org.gnucash.android.util.BackupManager; /** * Confirmation dialog for deleting all accounts from the system. * This class currently only works with HONEYCOMB and above. * * @author Ngewi Fet <[email protected]> */ public class DeleteAllAccountsConfirmationDialog extends DoubleConfirmationDialog { public static DeleteAllAccountsConfirmationDialog newInstance() { DeleteAllAccountsConfirmationDialog frag = new DeleteAllAccountsConfirmationDialog(); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return getDialogBuilder() .setIcon(android.R.drawable.ic_delete) .setTitle(R.string.title_confirm_delete).setMessage(R.string.confirm_delete_all_accounts) .setPositiveButton(R.string.alert_dialog_ok_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Context context = getDialog().getContext(); BackupManager.backupActiveBook(); AccountsDbAdapter.getInstance().deleteAllRecords(); Toast.makeText(context, R.string.toast_all_accounts_deleted, Toast.LENGTH_SHORT).show(); WidgetConfigurationActivity.updateAllWidgets(context); } } ) .create(); } }
2,518
39.629032
120
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/dialog/DeleteAllTransactionsConfirmationDialog.java
/* * Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]> * Copyright (c) 2014 Yongxin Wang <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings.dialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.widget.Toast; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Transaction; import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity; import org.gnucash.android.util.BackupManager; import java.util.ArrayList; import java.util.List; /** * Confirmation dialog for deleting all transactions * * @author ngewif <[email protected]> * @author Yongxin Wang <[email protected]> */ public class DeleteAllTransactionsConfirmationDialog extends DoubleConfirmationDialog { public static DeleteAllTransactionsConfirmationDialog newInstance() { DeleteAllTransactionsConfirmationDialog frag = new DeleteAllTransactionsConfirmationDialog(); return frag; } @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { return getDialogBuilder() .setIcon(android.R.drawable.ic_delete) .setTitle(R.string.title_confirm_delete).setMessage(R.string.msg_delete_all_transactions_confirmation) .setPositiveButton(R.string.alert_dialog_ok_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BackupManager.backupActiveBook(); Context context = getActivity(); AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); List<Transaction> openingBalances = new ArrayList<>(); boolean preserveOpeningBalances = GnuCashApplication.shouldSaveOpeningBalances(false); if (preserveOpeningBalances) { openingBalances = accountsDbAdapter.getAllOpeningBalanceTransactions(); } TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); int count = transactionsDbAdapter.deleteAllNonTemplateTransactions(); Log.i("DeleteDialog", String.format("Deleted %d transactions successfully", count)); if (preserveOpeningBalances) { transactionsDbAdapter.bulkAddRecords(openingBalances, DatabaseAdapter.UpdateMethod.insert); } Toast.makeText(context, R.string.toast_all_transactions_deleted, Toast.LENGTH_SHORT).show(); WidgetConfigurationActivity.updateAllWidgets(getActivity()); } } ).create(); } }
3,893
45.357143
127
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/dialog/DeleteBookConfirmationDialog.java
/* * Copyright (c) 2017 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings.dialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import org.gnucash.android.R; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.ui.common.Refreshable; import org.gnucash.android.util.BackupManager; /** * Confirmation dialog for deleting a book. * * @author Àlex Magaz <[email protected]> */ public class DeleteBookConfirmationDialog extends DoubleConfirmationDialog { @NonNull public static DeleteBookConfirmationDialog newInstance(String bookUID) { DeleteBookConfirmationDialog frag = new DeleteBookConfirmationDialog(); Bundle args = new Bundle(); args.putString("bookUID", bookUID); frag.setArguments(args); return frag; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return getDialogBuilder() .setTitle(R.string.title_confirm_delete_book) .setIcon(R.drawable.ic_close_black_24dp) .setMessage(R.string.msg_all_book_data_will_be_deleted) .setPositiveButton(R.string.btn_delete_book, new DialogInterface.OnClickListener() { @SuppressWarnings("ConstantConditions") @Override public void onClick(DialogInterface dialogInterface, int which) { final String bookUID = getArguments().getString("bookUID"); BackupManager.backupBook(bookUID); BooksDbAdapter.getInstance().deleteBook(bookUID); ((Refreshable) getTargetFragment()).refresh(); } }) .create(); } }
2,449
37.28125
100
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/dialog/DoubleConfirmationDialog.java
/* * Copyright (c) 2017 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.settings.dialog; import android.content.DialogInterface; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.widget.CheckBox; import android.widget.CompoundButton; import org.gnucash.android.R; /** * Confirmation dialog with additional checkbox to confirm the action. * * <p>It's meant to avoid the user confirming irreversible actions by * mistake. The positive button to confirm the action is only enabled * when the checkbox is checked.</p> * * <p>Extend this class and override onCreateDialog to finish setting * up the dialog. See getDialogBuilder().</p> * * @author Àlex Magaz <[email protected]> */ public abstract class DoubleConfirmationDialog extends DialogFragment { /** * Returns the dialog builder with the defaults for a double confirmation * dialog already set up. * * <p>Call it from onCreateDialog to finish setting up the dialog. * At least the following should be set:</p> * * <ul> * <li>The title.</li> * <li>The positive button.</li> * </ul> * * @return AlertDialog.Builder with the defaults for a double confirmation * dialog already set up. */ @NonNull protected AlertDialog.Builder getDialogBuilder() { return new AlertDialog.Builder(getActivity()) .setView(R.layout.dialog_double_confirm) .setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onNegativeButton(); } }); } @Override public void onStart() { super.onStart(); if (getDialog() != null) { ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); setUpConfirmCheckBox(); } } @SuppressWarnings("ConstantConditions") private void setUpConfirmCheckBox() { final AlertDialog dialog = (AlertDialog) getDialog(); CheckBox confirmCheckBox = dialog.findViewById(R.id.checkbox_confirm); confirmCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(b); } }); } /** * Called when the negative button is pressed. * * <p>By default it just dismisses the dialog.</p> */ protected void onNegativeButton() { getDialog().dismiss(); } }
3,408
33.785714
97
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/settings/dialog/OwnCloudDialogFragment.java
package org.gnucash.android.ui.settings.dialog; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.content.ContextCompat; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.Preference; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClientFactory; import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.resources.files.FileUtils; import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation; import com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation; import org.gnucash.android.R; /** * A fragment for adding an ownCloud account. */ public class OwnCloudDialogFragment extends DialogFragment { /** * Dialog positive button. Ok to save and validate the data */ private Button mOkButton; /** * Cancel button */ private Button mCancelButton; /** * ownCloud vars */ private String mOC_server; private String mOC_username; private String mOC_password; private String mOC_dir; private EditText mServer; private EditText mUsername; private EditText mPassword; private EditText mDir; private TextView mServerError; private TextView mUsernameError; private TextView mDirError; private SharedPreferences mPrefs; private Context mContext; private static CheckBoxPreference ocCheckBox; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment OwnCloudDialogFragment. */ public static OwnCloudDialogFragment newInstance(Preference pref) { OwnCloudDialogFragment fragment = new OwnCloudDialogFragment(); ocCheckBox = pref == null ? null : (CheckBoxPreference) pref; return fragment; } public OwnCloudDialogFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, 0); mContext = getActivity(); mPrefs = mContext.getSharedPreferences(getString(R.string.owncloud_pref), Context.MODE_PRIVATE); mOC_server = mPrefs.getString(getString(R.string.key_owncloud_server), getString(R.string.owncloud_server)); mOC_username = mPrefs.getString(getString(R.string.key_owncloud_username), null); mOC_password = mPrefs.getString(getString(R.string.key_owncloud_password), null); mOC_dir = mPrefs.getString(getString(R.string.key_owncloud_dir), getString(R.string.app_name)); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.dialog_owncloud_account, container, false); mServer = (EditText) view.findViewById(R.id.owncloud_hostname); mUsername = (EditText) view.findViewById(R.id.owncloud_username); mPassword = (EditText) view.findViewById(R.id.owncloud_password); mDir = (EditText) view.findViewById(R.id.owncloud_dir); mServer.setText(mOC_server); mDir.setText(mOC_dir); mPassword.setText(mOC_password); // TODO: Remove - debugging only mUsername.setText(mOC_username); mServerError = (TextView) view.findViewById(R.id.owncloud_hostname_invalid); mUsernameError = (TextView) view.findViewById(R.id.owncloud_username_invalid); mDirError = (TextView) view.findViewById(R.id.owncloud_dir_invalid); mServerError.setVisibility(View.GONE); mUsernameError.setVisibility(View.GONE); mDirError.setVisibility(View.GONE); mCancelButton = (Button) view.findViewById(R.id.btn_cancel); mOkButton = (Button) view.findViewById(R.id.btn_save); mOkButton.setText(R.string.btn_test); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setListeners(); } private void saveButton() { if (mDirError.getText().toString().equals(getString(R.string.owncloud_dir_ok)) && mUsernameError.getText().toString().equals(getString(R.string.owncloud_user_ok)) && mServerError.getText().toString().equals(getString(R.string.owncloud_server_ok))) mOkButton.setText(R.string.btn_save); else mOkButton.setText(R.string.btn_test); } private void save() { SharedPreferences.Editor edit = mPrefs.edit(); edit.clear(); edit.putString(getString(R.string.key_owncloud_server), mOC_server); edit.putString(getString(R.string.key_owncloud_username), mOC_username); edit.putString(getString(R.string.key_owncloud_password), mOC_password); edit.putString(getString(R.string.key_owncloud_dir), mOC_dir); edit.putBoolean(getString(R.string.owncloud_sync), true); edit.apply(); if (ocCheckBox != null) ocCheckBox.setChecked(true); dismiss(); } private void checkData() { mServerError.setVisibility(View.GONE); mUsernameError.setVisibility(View.GONE); mDirError.setVisibility(View.GONE); mOC_server = mServer.getText().toString().trim(); mOC_username = mUsername.getText().toString().trim(); mOC_password = mPassword.getText().toString().trim(); mOC_dir = mDir.getText().toString().trim(); Uri serverUri = Uri.parse(mOC_server); OwnCloudClient mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, mContext, true); mClient.setCredentials( OwnCloudCredentialsFactory.newBasicCredentials(mOC_username, mOC_password) ); final Handler mHandler = new Handler(); OnRemoteOperationListener listener = new OnRemoteOperationListener() { @Override public void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result) { if (!result.isSuccess()) { Log.e("OC", result.getLogMessage(), result.getException()); if (caller instanceof GetRemoteStatusOperation) { mServerError.setTextColor(ContextCompat.getColor(getContext(), R.color.debit_red)); mServerError.setText(getString(R.string.owncloud_server_invalid)); mServerError.setVisibility(View.VISIBLE); } else if (caller instanceof GetRemoteUserInfoOperation && mServerError.getText().toString().equals(getString(R.string.owncloud_server_ok))) { mUsernameError.setTextColor(ContextCompat.getColor(getContext(), R.color.debit_red)); mUsernameError.setText(getString(R.string.owncloud_user_invalid)); mUsernameError.setVisibility(View.VISIBLE); } } else { if (caller instanceof GetRemoteStatusOperation) { mServerError.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary)); mServerError.setText(getString(R.string.owncloud_server_ok)); mServerError.setVisibility(View.VISIBLE); } else if (caller instanceof GetRemoteUserInfoOperation) { mUsernameError.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary)); mUsernameError.setText(getString(R.string.owncloud_user_ok)); mUsernameError.setVisibility(View.VISIBLE); } } saveButton(); } }; GetRemoteStatusOperation g = new GetRemoteStatusOperation(mContext); g.execute(mClient, listener, mHandler); GetRemoteUserInfoOperation gu = new GetRemoteUserInfoOperation(); gu.execute(mClient, listener, mHandler); if (FileUtils.isValidPath(mOC_dir, false)) { mDirError.setTextColor(ContextCompat.getColor(getContext(), R.color.theme_primary)); mDirError.setText(getString(R.string.owncloud_dir_ok)); mDirError.setVisibility(View.VISIBLE); } else { mDirError.setTextColor(ContextCompat.getColor(getContext(), R.color.debit_red)); mDirError.setText(getString(R.string.owncloud_dir_invalid)); mDirError.setVisibility(View.VISIBLE); } saveButton(); } /** * Binds click listeners for the dialog buttons */ private void setListeners(){ mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); mOkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If data didn't change if(mOkButton.getText().toString().equals(getString(R.string.btn_save)) && mOC_server.equals(mServer.getText().toString().trim()) && mOC_username.equals(mUsername.getText().toString().trim()) && mOC_password.equals(mPassword.getText().toString().trim()) && mOC_dir.equals(mDir.getText().toString().trim()) ) save(); else checkData(); } }); } }
10,357
39.147287
116
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/OnTransactionClickedListener.java
/* * Copyright (c) 2012 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; /** * Interface for implemented by activities which wish to be notified when * an action has been requested on a transaction (either creation or edit) * This is typically used for Fragment-to-Activity communication * * @author Ngewi Fet <[email protected]> * */ public interface OnTransactionClickedListener { /** * Callback for creating a new transaction * @param accountUID GUID of the account in which to create the new transaction */ public void createNewTransaction(String accountUID); /** * Callback request to edit a transaction * @param transactionUID GUID of the transaction to be edited */ public void editTransaction(String transactionUID); }
1,342
31.756098
80
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/OnTransferFundsListener.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import org.gnucash.android.model.Money; /** * Interface to be implemented by classes which start the transfer funds fragment */ public interface OnTransferFundsListener { /** * Method called after the funds have been converted to the desired currency * @param amount Funds in new currency */ void transferComplete(Money amount); }
1,020
30.90625
81
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/ScheduledActionsActivity.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import org.gnucash.android.R; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.ui.common.BaseDrawerActivity; /** * Activity for displaying scheduled actions * @author Ngewi Fet <[email protected]> */ public class ScheduledActionsActivity extends BaseDrawerActivity { public static final int INDEX_SCHEDULED_TRANSACTIONS = 0; public static final int INDEX_SCHEDULED_EXPORTS = 1; ViewPager mViewPager; @Override public int getContentView() { return R.layout.activity_scheduled_events; } @Override public int getTitleRes() { return R.string.nav_menu_scheduled_actions; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText(R.string.title_scheduled_transactions)); tabLayout.addTab(tabLayout.newTab().setText(R.string.title_scheduled_exports)); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); mViewPager = (ViewPager) findViewById(R.id.pager); //show the simple accounts list PagerAdapter mPagerAdapter = new ScheduledActionsViewPager(getSupportFragmentManager()); mViewPager.setAdapter(mPagerAdapter); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { //nothing to see here, move along } @Override public void onTabReselected(TabLayout.Tab tab) { //nothing to see here, move along } }); } /** * View pager adapter for managing the scheduled action views */ private class ScheduledActionsViewPager extends FragmentStatePagerAdapter { public ScheduledActionsViewPager(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { switch (position){ case INDEX_SCHEDULED_TRANSACTIONS: return getString(R.string.title_scheduled_transactions); case INDEX_SCHEDULED_EXPORTS: return getString(R.string.title_scheduled_exports); default: return super.getPageTitle(position); } } @Override public Fragment getItem(int position) { switch (position){ case INDEX_SCHEDULED_TRANSACTIONS: return ScheduledActionsListFragment.getInstance(ScheduledAction.ActionType.TRANSACTION); case INDEX_SCHEDULED_EXPORTS: return ScheduledActionsListFragment.getInstance(ScheduledAction.ActionType.BACKUP); } return null; } @Override public int getCount() { return 2; } } }
4,228
33.104839
108
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/ScheduledActionsListFragment.java
/* * Copyright (c) 2013 - 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Rect; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.TouchDelegate; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseCursorLoader; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.export.ExportParams; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.model.Transaction; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.util.BackupManager; import java.text.DateFormat; import java.util.Date; import java.util.List; /** * Fragment which displays the scheduled actions in the system * <p>Currently, it handles the display of scheduled transactions and scheduled exports</p> * @author Ngewi Fet <[email protected]> */ public class ScheduledActionsListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { /** * Logging tag */ protected static final String TAG = "ScheduledActionFragment"; private TransactionsDbAdapter mTransactionsDbAdapter; private SimpleCursorAdapter mCursorAdapter; private ActionMode mActionMode = null; /** * Flag which is set when a transaction is selected */ private boolean mInEditMode = false; private ScheduledAction.ActionType mActionType = ScheduledAction.ActionType.TRANSACTION; /** * Callbacks for the menu items in the Context ActionBar (CAB) in action mode */ private ActionMode.Callback mActionModeCallbacks = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.schedxactions_context_menu, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { //nothing to see here, move along return false; } @Override public void onDestroyActionMode(ActionMode mode) { finishEditMode(); } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.context_menu_delete: BackupManager.backupActiveBook(); for (long id : getListView().getCheckedItemIds()) { if (mActionType == ScheduledAction.ActionType.TRANSACTION) { Log.i(TAG, "Cancelling scheduled transaction(s)"); String trnUID = mTransactionsDbAdapter.getUID(id); ScheduledActionDbAdapter scheduledActionDbAdapter = GnuCashApplication.getScheduledEventDbAdapter(); List<ScheduledAction> actions = scheduledActionDbAdapter.getScheduledActionsWithUID(trnUID); if (mTransactionsDbAdapter.deleteRecord(id)) { Toast.makeText(getActivity(), R.string.toast_recurring_transaction_deleted, Toast.LENGTH_SHORT).show(); for (ScheduledAction action : actions) { scheduledActionDbAdapter.deleteRecord(action.getUID()); } } } else if (mActionType == ScheduledAction.ActionType.BACKUP){ Log.i(TAG, "Removing scheduled exports"); ScheduledActionDbAdapter.getInstance().deleteRecord(id); } } mode.finish(); setDefaultStatusBarColor(); getLoaderManager().destroyLoader(0); refreshList(); return true; default: setDefaultStatusBarColor(); return false; } } }; private void setDefaultStatusBarColor() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getActivity().getWindow().setStatusBarColor( ContextCompat.getColor(getContext(), R.color.theme_primary_dark)); } } /** * Returns a new instance of the fragment for displayed the scheduled action * @param actionType Type of scheduled action to be displayed * @return New instance of fragment */ public static Fragment getInstance(ScheduledAction.ActionType actionType){ ScheduledActionsListFragment fragment = new ScheduledActionsListFragment(); fragment.mActionType = actionType; return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); switch (mActionType){ case TRANSACTION: mCursorAdapter = new ScheduledTransactionsCursorAdapter( getActivity().getApplicationContext(), R.layout.list_item_scheduled_trxn, null, new String[] {DatabaseSchema.TransactionEntry.COLUMN_DESCRIPTION}, new int[] {R.id.primary_text}); break; case BACKUP: mCursorAdapter = new ScheduledExportCursorAdapter( getActivity().getApplicationContext(), R.layout.list_item_scheduled_trxn, null, new String[]{}, new int[]{}); break; default: throw new IllegalArgumentException("Unable to display scheduled actions for the specified action type"); } setListAdapter(mCursorAdapter); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_scheduled_events_list, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); setHasOptionsMenu(true); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); ((TextView)getListView().getEmptyView()) .setTextColor(ContextCompat.getColor(getContext(), R.color.theme_accent)); if (mActionType == ScheduledAction.ActionType.TRANSACTION){ ((TextView)getListView().getEmptyView()).setText(R.string.label_no_recurring_transactions); } else if (mActionType == ScheduledAction.ActionType.BACKUP){ ((TextView)getListView().getEmptyView()).setText(R.string.label_no_scheduled_exports_to_display); } } /** * Reload the list of transactions and recompute account balances */ public void refreshList(){ getLoaderManager().restartLoader(0, null, this); } @Override public void onResume() { super.onResume(); refreshList(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mActionType == ScheduledAction.ActionType.BACKUP) inflater.inflate(R.menu.scheduled_export_actions, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.menu_add_scheduled_export: Intent intent = new Intent(getActivity(), FormActivity.class); intent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.EXPORT.name()); startActivityForResult(intent, 0x1); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if (mActionMode != null){ CheckBox checkbox = (CheckBox) v.findViewById(R.id.checkbox); checkbox.setChecked(!checkbox.isChecked()); return; } if (mActionType == ScheduledAction.ActionType.BACKUP) //nothing to do for export actions return; Transaction transaction = mTransactionsDbAdapter.getRecord(id); //this should actually never happen, but has happened once. So perform check for the future if (transaction.getSplits().size() == 0){ Toast.makeText(getActivity(), R.string.toast_transaction_has_no_splits_and_cannot_open, Toast.LENGTH_SHORT).show(); return; } String accountUID = transaction.getSplits().get(0).getAccountUID(); openTransactionForEdit(accountUID, mTransactionsDbAdapter.getUID(id), v.getTag().toString()); } /** * Opens the transaction editor to enable editing of the transaction * @param accountUID GUID of account to which transaction belongs * @param transactionUID GUID of transaction to be edited */ public void openTransactionForEdit(String accountUID, String transactionUID, String scheduledActionUid){ Intent createTransactionIntent = new Intent(getActivity(), FormActivity.class); createTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT); createTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name()); createTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID); createTransactionIntent.putExtra(UxArgument.SELECTED_TRANSACTION_UID, transactionUID); createTransactionIntent.putExtra(UxArgument.SCHEDULED_ACTION_UID, scheduledActionUid); startActivity(createTransactionIntent); } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { Log.d(TAG, "Creating transactions loader"); if (mActionType == ScheduledAction.ActionType.TRANSACTION) return new ScheduledTransactionsCursorLoader(getActivity()); else if (mActionType == ScheduledAction.ActionType.BACKUP){ return new ScheduledExportCursorLoader(getActivity()); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { Log.d(TAG, "Transactions loader finished. Swapping in cursor"); mCursorAdapter.swapCursor(cursor); mCursorAdapter.notifyDataSetChanged(); } @Override public void onLoaderReset(Loader<Cursor> loader) { Log.d(TAG, "Resetting transactions loader"); mCursorAdapter.swapCursor(null); } /** * Finishes the edit mode in the transactions list. * Edit mode is started when at least one transaction is selected */ public void finishEditMode(){ mInEditMode = false; uncheckAllItems(); mActionMode = null; } /** * Sets the title of the Context ActionBar when in action mode. * It sets the number highlighted items */ public void setActionModeTitle(){ int count = getListView().getCheckedItemIds().length; //mSelectedIds.size(); if (count > 0){ mActionMode.setTitle(getResources().getString(R.string.title_selected, count)); } } /** * Unchecks all the checked items in the list */ private void uncheckAllItems() { SparseBooleanArray checkedPositions = getListView().getCheckedItemPositions(); ListView listView = getListView(); for (int i = 0; i < checkedPositions.size(); i++) { int position = checkedPositions.keyAt(i); listView.setItemChecked(position, false); } } /** * Starts action mode and activates the Context ActionBar (CAB) * Action mode is initiated as soon as at least one transaction is selected (highlighted) */ private void startActionMode(){ if (mActionMode != null) { return; } mInEditMode = true; // Start the CAB using the ActionMode.Callback defined above mActionMode = ((AppCompatActivity) getActivity()) .startSupportActionMode(mActionModeCallbacks); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getActivity().getWindow().setStatusBarColor( ContextCompat.getColor(getContext(), android.R.color.darker_gray)); } } /** * Stops action mode and deselects all selected transactions. * This method only has effect if the number of checked items is greater than 0 and {@link #mActionMode} is not null */ private void stopActionMode(){ int checkedCount = getListView().getCheckedItemIds().length; if (checkedCount <= 0 && mActionMode != null) { mActionMode.finish(); setDefaultStatusBarColor(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { refreshList(); super.onActivityResult(requestCode, resultCode, data); } } /** * Extends a simple cursor adapter to bind transaction attributes to views * @author Ngewi Fet <[email protected]> */ protected class ScheduledTransactionsCursorAdapter extends SimpleCursorAdapter { public ScheduledTransactionsCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to, 0); } @Override public View getView(int position, View convertView, ViewGroup parent) { final View view = super.getView(position, convertView, parent); final int itemPosition = position; CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox); //TODO: Revisit this if we ever change the application theme int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android"); checkbox.setButtonDrawable(id); final TextView secondaryText = (TextView) view.findViewById(R.id.secondary_text); checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { getListView().setItemChecked(itemPosition, isChecked); if (isChecked) { startActionMode(); } else { stopActionMode(); } setActionModeTitle(); } }); ListView listView = (ListView) parent; if (mInEditMode && listView.isItemChecked(position)){ view.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.abs__holo_blue_light)); secondaryText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); } else { view.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent)); secondaryText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.secondary_text_light_nodisable)); checkbox.setChecked(false); } final View checkBoxView = checkbox; final View parentView = view; parentView.post(new Runnable() { @Override public void run() { if (isAdded()){ //may be run when fragment has been unbound from activity float extraPadding = getResources().getDimension(R.dimen.edge_padding); final android.graphics.Rect hitRect = new Rect(); checkBoxView.getHitRect(hitRect); hitRect.right += extraPadding; hitRect.bottom += 3*extraPadding; hitRect.top -= extraPadding; hitRect.left -= 2*extraPadding; parentView.setTouchDelegate(new TouchDelegate(hitRect, checkBoxView)); } } }); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); Transaction transaction = mTransactionsDbAdapter.buildModelInstance(cursor); TextView amountTextView = (TextView) view.findViewById(R.id.right_text); if (transaction.getSplits().size() == 2){ if (transaction.getSplits().get(0).isPairOf(transaction.getSplits().get(1))){ amountTextView.setText(transaction.getSplits().get(0).getValue().formattedString()); } } else { amountTextView.setText(getString(R.string.label_split_count, transaction.getSplits().size())); } TextView descriptionTextView = (TextView) view.findViewById(R.id.secondary_text); ScheduledActionDbAdapter scheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance(); String scheduledActionUID = cursor.getString(cursor.getColumnIndexOrThrow("origin_scheduled_action_uid")); //column created from join when fetching scheduled transactions view.setTag(scheduledActionUID); ScheduledAction scheduledAction = scheduledActionDbAdapter.getRecord(scheduledActionUID); long endTime = scheduledAction.getEndTime(); if (endTime > 0 && endTime < System.currentTimeMillis()){ ((TextView)view.findViewById(R.id.primary_text)).setTextColor( ContextCompat.getColor(getContext(), android.R.color.darker_gray)); descriptionTextView.setText(getString(R.string.label_scheduled_action_ended, DateFormat.getInstance().format(new Date(scheduledAction.getLastRunTime())))); } else { descriptionTextView.setText(scheduledAction.getRepeatString()); } } } /** * Extends a simple cursor adapter to bind transaction attributes to views * @author Ngewi Fet <[email protected]> */ protected class ScheduledExportCursorAdapter extends SimpleCursorAdapter { public ScheduledExportCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to, 0); } @Override public View getView(int position, View convertView, ViewGroup parent) { final View view = super.getView(position, convertView, parent); final int itemPosition = position; CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox); //TODO: Revisit this if we ever change the application theme int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android"); checkbox.setButtonDrawable(id); final TextView secondaryText = (TextView) view.findViewById(R.id.secondary_text); checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { getListView().setItemChecked(itemPosition, isChecked); if (isChecked) { startActionMode(); } else { stopActionMode(); } setActionModeTitle(); } }); ListView listView = (ListView) parent; if (mInEditMode && listView.isItemChecked(position)){ view.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.abs__holo_blue_light)); secondaryText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); } else { view.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent)); secondaryText.setTextColor( ContextCompat.getColor(getContext(), android.R.color.secondary_text_light_nodisable)); checkbox.setChecked(false); } final View checkBoxView = checkbox; final View parentView = view; parentView.post(new Runnable() { @Override public void run() { if (isAdded()){ //may be run when fragment has been unbound from activity float extraPadding = getResources().getDimension(R.dimen.edge_padding); final android.graphics.Rect hitRect = new Rect(); checkBoxView.getHitRect(hitRect); hitRect.right += extraPadding; hitRect.bottom += 3*extraPadding; hitRect.top -= extraPadding; hitRect.left -= 2*extraPadding; parentView.setTouchDelegate(new TouchDelegate(hitRect, checkBoxView)); } } }); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); ScheduledActionDbAdapter mScheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance(); ScheduledAction scheduledAction = mScheduledActionDbAdapter.buildModelInstance(cursor); TextView primaryTextView = (TextView) view.findViewById(R.id.primary_text); ExportParams params = ExportParams.parseCsv(scheduledAction.getTag()); String exportDestination = params.getExportTarget().getDescription(); if (params.getExportTarget() == ExportParams.ExportTarget.URI){ exportDestination = exportDestination + " (" + Uri.parse(params.getExportLocation()).getHost() + ")"; } primaryTextView.setText(params.getExportFormat().name() + " " + scheduledAction.getActionType().name().toLowerCase() + " to " + exportDestination); view.findViewById(R.id.right_text).setVisibility(View.GONE); TextView descriptionTextView = (TextView) view.findViewById(R.id.secondary_text); descriptionTextView.setText(scheduledAction.getRepeatString()); long endTime = scheduledAction.getEndTime(); if (endTime > 0 && endTime < System.currentTimeMillis()){ ((TextView)view.findViewById(R.id.primary_text)) .setTextColor(ContextCompat.getColor(getContext(), android.R.color.darker_gray)); descriptionTextView.setText(getString(R.string.label_scheduled_action_ended, DateFormat.getInstance().format(new Date(scheduledAction.getLastRunTime())))); } else { descriptionTextView.setText(scheduledAction.getRepeatString()); } } } /** * {@link DatabaseCursorLoader} for loading recurring transactions asynchronously from the database * @author Ngewi Fet <[email protected]> */ protected static class ScheduledTransactionsCursorLoader extends DatabaseCursorLoader { public ScheduledTransactionsCursorLoader(Context context) { super(context); } @Override public Cursor loadInBackground() { mDatabaseAdapter = TransactionsDbAdapter.getInstance(); Cursor c = ((TransactionsDbAdapter) mDatabaseAdapter).fetchAllScheduledTransactions(); registerContentObserver(c); return c; } } /** * {@link DatabaseCursorLoader} for loading recurring transactions asynchronously from the database * @author Ngewi Fet <[email protected]> */ protected static class ScheduledExportCursorLoader extends DatabaseCursorLoader { public ScheduledExportCursorLoader(Context context) { super(context); } @Override public Cursor loadInBackground() { mDatabaseAdapter = ScheduledActionDbAdapter.getInstance(); Cursor c = mDatabaseAdapter.fetchAllRecords( DatabaseSchema.ScheduledActionEntry.COLUMN_TYPE + "=?", new String[]{ScheduledAction.ActionType.BACKUP.name()}, null); registerContentObserver(c); return c; } } }
27,019
40.826625
182
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/SplitEditorFragment.java
/* * Copyright (c) 2014 - 2016 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.inputmethodservice.KeyboardView; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import net.objecthunter.exp4j.Expression; import net.objecthunter.exp4j.ExpressionBuilder; import org.gnucash.android.R; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.model.AccountType; import org.gnucash.android.model.BaseModel; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.transaction.dialog.TransferFundsDialogFragment; import org.gnucash.android.ui.util.widget.CalculatorEditText; import org.gnucash.android.ui.util.widget.CalculatorKeyboard; import org.gnucash.android.ui.util.widget.TransactionTypeSwitch; import org.gnucash.android.util.QualifiedAccountNameCursorAdapter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Dialog for editing the splits in a transaction * * @author Ngewi Fet <[email protected]> */ public class SplitEditorFragment extends Fragment { @BindView(R.id.split_list_layout) LinearLayout mSplitsLinearLayout; @BindView(R.id.calculator_keyboard) KeyboardView mKeyboardView; @BindView(R.id.imbalance_textview) TextView mImbalanceTextView; private AccountsDbAdapter mAccountsDbAdapter; private Cursor mCursor; private SimpleCursorAdapter mCursorAdapter; private List<View> mSplitItemViewList; private String mAccountUID; private Commodity mCommodity; private BigDecimal mBaseAmount = BigDecimal.ZERO; CalculatorKeyboard mCalculatorKeyboard; BalanceTextWatcher mImbalanceWatcher = new BalanceTextWatcher(); /** * Create and return a new instance of the fragment with the appropriate paramenters * @param args Arguments to be set to the fragment. <br> * See {@link UxArgument#AMOUNT_STRING} and {@link UxArgument#SPLIT_LIST} * @return New instance of SplitEditorFragment */ public static SplitEditorFragment newInstance(Bundle args){ SplitEditorFragment fragment = new SplitEditorFragment(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_split_editor, container, false); ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar(); assert actionBar != null; actionBar.setTitle(R.string.title_split_editor); setHasOptionsMenu(true); mCalculatorKeyboard = new CalculatorKeyboard(getActivity(), mKeyboardView, R.xml.calculator_keyboard); mSplitItemViewList = new ArrayList<>(); //we are editing splits for a new transaction. // But the user may have already created some splits before. Let's check List<Split> splitList = getArguments().getParcelableArrayList(UxArgument.SPLIT_LIST); assert splitList != null; initArgs(); if (!splitList.isEmpty()) { //aha! there are some splits. Let's load those instead loadSplitViews(splitList); mImbalanceWatcher.afterTextChanged(null); } else { final String currencyCode = mAccountsDbAdapter.getAccountCurrencyCode(mAccountUID); Split split = new Split(new Money(mBaseAmount, Commodity.getInstance(currencyCode)), mAccountUID); AccountType accountType = mAccountsDbAdapter.getAccountType(mAccountUID); TransactionType transactionType = Transaction.getTypeForBalance(accountType, mBaseAmount.signum() < 0); split.setType(transactionType); View view = addSplitView(split); view.findViewById(R.id.input_accounts_spinner).setEnabled(false); view.findViewById(R.id.btn_remove_split).setVisibility(View.GONE); TransactionsActivity.displayBalance(mImbalanceTextView, new Money(mBaseAmount.negate(), mCommodity)); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mCalculatorKeyboard = new CalculatorKeyboard(getActivity(), mKeyboardView, R.xml.calculator_keyboard); } private void loadSplitViews(List<Split> splitList) { for (Split split : splitList) { addSplitView(split); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.split_editor_actions, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().setResult(Activity.RESULT_CANCELED); getActivity().finish(); return true; case R.id.menu_save: saveSplits(); return true; case R.id.menu_add_split: addSplitView(null); return true; default: return super.onOptionsItemSelected(item); } } /** * Add a split view and initialize it with <code>split</code> * @param split Split to initialize the contents to * @return Returns the split view which was added */ private View addSplitView(Split split){ LayoutInflater layoutInflater = getActivity().getLayoutInflater(); View splitView = layoutInflater.inflate(R.layout.item_split_entry, mSplitsLinearLayout, false); mSplitsLinearLayout.addView(splitView,0); SplitViewHolder viewHolder = new SplitViewHolder(splitView, split); splitView.setTag(viewHolder); mSplitItemViewList.add(splitView); return splitView; } /** * Extracts arguments passed to the view and initializes necessary adapters and cursors */ private void initArgs() { mAccountsDbAdapter = AccountsDbAdapter.getInstance(); Bundle args = getArguments(); mAccountUID = ((FormActivity) getActivity()).getCurrentAccountUID(); mBaseAmount = new BigDecimal(args.getString(UxArgument.AMOUNT_STRING)); String conditions = "(" + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + " = 0 AND " + DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + " = 0" + ")"; mCursor = mAccountsDbAdapter.fetchAccountsOrderedByFullName(conditions, null); mCommodity = CommoditiesDbAdapter.getInstance().getCommodity(mAccountsDbAdapter.getCurrencyCode(mAccountUID)); } /** * Holds a split item view and binds the items in it */ class SplitViewHolder implements OnTransferFundsListener{ @BindView(R.id.input_split_memo) EditText splitMemoEditText; @BindView(R.id.input_split_amount) CalculatorEditText splitAmountEditText; @BindView(R.id.btn_remove_split) ImageView removeSplitButton; @BindView(R.id.input_accounts_spinner) Spinner accountsSpinner; @BindView(R.id.split_currency_symbol) TextView splitCurrencyTextView; @BindView(R.id.split_uid) TextView splitUidTextView; @BindView(R.id.btn_split_type) TransactionTypeSwitch splitTypeSwitch; View splitView; Money quantity; public SplitViewHolder(View splitView, Split split){ ButterKnife.bind(this, splitView); this.splitView = splitView; if (split != null && !split.getQuantity().equals(split.getValue())) this.quantity = split.getQuantity(); setListeners(split); } @Override public void transferComplete(Money amount) { quantity = amount; } private void setListeners(Split split){ splitAmountEditText.bindListeners(mCalculatorKeyboard); removeSplitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mSplitsLinearLayout.removeView(splitView); mSplitItemViewList.remove(splitView); mImbalanceWatcher.afterTextChanged(null); } }); updateTransferAccountsList(accountsSpinner); splitCurrencyTextView.setText(mCommodity.getSymbol()); splitTypeSwitch.setAmountFormattingListener(splitAmountEditText, splitCurrencyTextView); splitTypeSwitch.setChecked(mBaseAmount.signum() > 0); splitUidTextView.setText(BaseModel.generateUID()); if (split != null) { splitAmountEditText.setCommodity(split.getValue().getCommodity()); splitAmountEditText.setValue(split.getFormattedValue().asBigDecimal()); splitCurrencyTextView.setText(split.getValue().getCommodity().getSymbol()); splitMemoEditText.setText(split.getMemo()); splitUidTextView.setText(split.getUID()); String splitAccountUID = split.getAccountUID(); setSelectedTransferAccount(mAccountsDbAdapter.getID(splitAccountUID), accountsSpinner); splitTypeSwitch.setAccountType(mAccountsDbAdapter.getAccountType(splitAccountUID)); splitTypeSwitch.setChecked(split.getType()); } accountsSpinner.setOnItemSelectedListener(new SplitAccountListener(splitTypeSwitch, this)); splitTypeSwitch.addOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mImbalanceWatcher.afterTextChanged(null); } }); splitAmountEditText.addTextChangedListener(mImbalanceWatcher); } /** * Returns the value of the amount in the splitAmountEditText field without setting the value to the view * <p>If the expression in the view is currently incomplete or invalid, null is returned. * This method is used primarily for computing the imbalance</p> * @return Value in the split item amount field, or {@link BigDecimal#ZERO} if the expression is empty or invalid */ public BigDecimal getAmountValue(){ String amountString = splitAmountEditText.getCleanString(); if (amountString.isEmpty()) return BigDecimal.ZERO; ExpressionBuilder expressionBuilder = new ExpressionBuilder(amountString); Expression expression; try { expression = expressionBuilder.build(); } catch (RuntimeException e) { return BigDecimal.ZERO; } if (expression != null && expression.validate().isValid()) { return new BigDecimal(expression.evaluate()); } else { Log.v(SplitEditorFragment.this.getClass().getSimpleName(), "Incomplete expression for updating imbalance: " + expression); return BigDecimal.ZERO; } } } /** * Updates the spinner to the selected transfer account * @param accountId Database ID of the transfer account */ private void setSelectedTransferAccount(long accountId, final Spinner accountsSpinner){ for (int pos = 0; pos < mCursorAdapter.getCount(); pos++) { if (mCursorAdapter.getItemId(pos) == accountId){ accountsSpinner.setSelection(pos); break; } } } /** * Updates the list of possible transfer accounts. * Only accounts with the same currency can be transferred to */ private void updateTransferAccountsList(Spinner transferAccountSpinner){ mCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), mCursor); transferAccountSpinner.setAdapter(mCursorAdapter); } /** * Check if all the split amounts have valid values that can be saved * @return {@code true} if splits can be saved, {@code false} otherwise */ private boolean canSave(){ for (View splitView : mSplitItemViewList) { SplitViewHolder viewHolder = (SplitViewHolder) splitView.getTag(); viewHolder.splitAmountEditText.evaluate(); if (viewHolder.splitAmountEditText.getError() != null){ return false; } //TODO: also check that multicurrency splits have a conversion amount present } return true; } /** * Save all the splits from the split editor */ private void saveSplits() { if (!canSave()){ Toast.makeText(getActivity(), R.string.toast_error_check_split_amounts, Toast.LENGTH_SHORT).show(); return; } Intent data = new Intent(); data.putParcelableArrayListExtra(UxArgument.SPLIT_LIST, extractSplitsFromView()); getActivity().setResult(Activity.RESULT_OK, data); getActivity().finish(); } /** * Extracts the input from the views and builds {@link org.gnucash.android.model.Split}s to correspond to the input. * @return List of {@link org.gnucash.android.model.Split}s represented in the view */ private ArrayList<Split> extractSplitsFromView(){ ArrayList<Split> splitList = new ArrayList<>(); for (View splitView : mSplitItemViewList) { SplitViewHolder viewHolder = (SplitViewHolder) splitView.getTag(); if (viewHolder.splitAmountEditText.getValue() == null) continue; BigDecimal amountBigDecimal = viewHolder.splitAmountEditText.getValue(); String currencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountUID); Money valueAmount = new Money(amountBigDecimal.abs(), Commodity.getInstance(currencyCode)); String accountUID = mAccountsDbAdapter.getUID(viewHolder.accountsSpinner.getSelectedItemId()); Split split = new Split(valueAmount, accountUID); split.setMemo(viewHolder.splitMemoEditText.getText().toString()); split.setType(viewHolder.splitTypeSwitch.getTransactionType()); split.setUID(viewHolder.splitUidTextView.getText().toString().trim()); if (viewHolder.quantity != null) split.setQuantity(viewHolder.quantity.abs()); splitList.add(split); } return splitList; } /** * Updates the displayed balance of the accounts when the amount of a split is changed */ private class BalanceTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { //nothing to see here, move along } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { //nothing to see here, move along } @Override public void afterTextChanged(Editable editable) { BigDecimal imbalance = BigDecimal.ZERO; for (View splitItem : mSplitItemViewList) { SplitViewHolder viewHolder = (SplitViewHolder) splitItem.getTag(); BigDecimal amount = viewHolder.getAmountValue().abs(); long accountId = viewHolder.accountsSpinner.getSelectedItemId(); boolean hasDebitNormalBalance = AccountsDbAdapter.getInstance() .getAccountType(accountId).hasDebitNormalBalance(); if (viewHolder.splitTypeSwitch.isChecked()) { if (hasDebitNormalBalance) imbalance = imbalance.add(amount); else imbalance = imbalance.subtract(amount); } else { if (hasDebitNormalBalance) imbalance = imbalance.subtract(amount); else imbalance = imbalance.add(amount); } } TransactionsActivity.displayBalance(mImbalanceTextView, new Money(imbalance, mCommodity)); } } /** * Listens to changes in the transfer account and updates the currency symbol, the label of the * transaction type and if neccessary */ private class SplitAccountListener implements AdapterView.OnItemSelectedListener { TransactionTypeSwitch mTypeToggleButton; SplitViewHolder mSplitViewHolder; /** * Flag to know when account spinner callback is due to user interaction or layout of components */ boolean userInteraction = false; public SplitAccountListener(TransactionTypeSwitch typeToggleButton, SplitViewHolder viewHolder){ this.mTypeToggleButton = typeToggleButton; this.mSplitViewHolder = viewHolder; } @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { AccountType accountType = mAccountsDbAdapter.getAccountType(id); mTypeToggleButton.setAccountType(accountType); //refresh the imbalance amount if we change the account mImbalanceWatcher.afterTextChanged(null); String fromCurrencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountUID); String targetCurrencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountsDbAdapter.getUID(id)); if (!userInteraction || fromCurrencyCode.equals(targetCurrencyCode)){ //first call is on layout, subsequent calls will be true and transfer will work as usual userInteraction = true; return; } BigDecimal amountBigD = mSplitViewHolder.splitAmountEditText.getValue(); if (amountBigD == null) return; Money amount = new Money(amountBigD, Commodity.getInstance(fromCurrencyCode)); TransferFundsDialogFragment fragment = TransferFundsDialogFragment.getInstance(amount, targetCurrencyCode, mSplitViewHolder); fragment.show(getFragmentManager(), "tranfer_funds_editor"); } @Override public void onNothingSelected(AdapterView<?> adapterView) { //nothing to see here, move along } } }
20,599
39.873016
121
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/TransactionDetailActivity.java
package org.gnucash.android.ui.transaction; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.TableLayout; import android.widget.TextView; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Money; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.passcode.PasscodeLockActivity; import java.text.DateFormat; import java.util.Date; import java.util.MissingFormatArgumentException; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Activity for displaying transaction information * @author Ngewi Fet <[email protected]> */ public class TransactionDetailActivity extends PasscodeLockActivity { @BindView(R.id.trn_description) TextView mTransactionDescription; @BindView(R.id.trn_time_and_date) TextView mTimeAndDate; @BindView(R.id.trn_recurrence) TextView mRecurrence; @BindView(R.id.trn_notes) TextView mNotes; @BindView(R.id.toolbar) Toolbar mToolBar; @BindView(R.id.transaction_account) TextView mTransactionAccount; @BindView(R.id.balance_debit) TextView mDebitBalance; @BindView(R.id.balance_credit) TextView mCreditBalance; @BindView(R.id.fragment_transaction_details) TableLayout mDetailTableLayout; private String mTransactionUID; private String mAccountUID; private int mDetailTableRows; public static final int REQUEST_EDIT_TRANSACTION = 0x10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_transaction_detail); mTransactionUID = getIntent().getStringExtra(UxArgument.SELECTED_TRANSACTION_UID); mAccountUID = getIntent().getStringExtra(UxArgument.SELECTED_ACCOUNT_UID); if (mTransactionUID == null || mAccountUID == null){ throw new MissingFormatArgumentException("You must specify both the transaction and account GUID"); } ButterKnife.bind(this); setSupportActionBar(mToolBar); ActionBar actionBar = getSupportActionBar(); assert actionBar != null; actionBar.setElevation(0); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp); actionBar.setDisplayShowTitleEnabled(false); bindViews(); int themeColor = AccountsDbAdapter.getActiveAccountColorResource(mAccountUID); actionBar.setBackgroundDrawable(new ColorDrawable(themeColor)); mToolBar.setBackgroundColor(themeColor); if (Build.VERSION.SDK_INT > 20) getWindow().setStatusBarColor(GnuCashApplication.darken(themeColor)); } class SplitAmountViewHolder { @BindView(R.id.split_account_name) TextView accountName; @BindView(R.id.split_debit) TextView splitDebit; @BindView(R.id.split_credit) TextView splitCredit; View itemView; public SplitAmountViewHolder(View view, Split split){ itemView = view; ButterKnife.bind(this, view); AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); accountName.setText(accountsDbAdapter.getAccountFullName(split.getAccountUID())); Money quantity = split.getFormattedQuantity(); TextView balanceView = quantity.isNegative() ? splitDebit : splitCredit; TransactionsActivity.displayBalance(balanceView, quantity); } } /** * Reads the transaction information from the database and binds it to the views */ private void bindViews(){ TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); Transaction transaction = transactionsDbAdapter.getRecord(mTransactionUID); mTransactionDescription.setText(transaction.getDescription()); mTransactionAccount.setText(getString(R.string.label_inside_account_with_name, AccountsDbAdapter.getInstance().getAccountFullName(mAccountUID))); AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); Money accountBalance = accountsDbAdapter.getAccountBalance(mAccountUID, -1, transaction.getTimeMillis()); TextView balanceTextView = accountBalance.isNegative() ? mDebitBalance : mCreditBalance; TransactionsActivity.displayBalance(balanceTextView, accountBalance); mDetailTableRows = mDetailTableLayout.getChildCount(); boolean useDoubleEntry = GnuCashApplication.isDoubleEntryEnabled(); LayoutInflater inflater = LayoutInflater.from(this); int index = 0; for (Split split : transaction.getSplits()) { if (!useDoubleEntry && split.getAccountUID().equals( accountsDbAdapter.getImbalanceAccountUID(split.getValue().getCommodity()))) { //do now show imbalance accounts for single entry use case continue; } View view = inflater.inflate(R.layout.item_split_amount_info, mDetailTableLayout, false); SplitAmountViewHolder viewHolder = new SplitAmountViewHolder(view, split); mDetailTableLayout.addView(viewHolder.itemView, index++); } Date trnDate = new Date(transaction.getTimeMillis()); String timeAndDate = DateFormat.getDateInstance(DateFormat.FULL).format(trnDate); mTimeAndDate.setText(timeAndDate); if (transaction.getScheduledActionUID() != null){ ScheduledAction scheduledAction = ScheduledActionDbAdapter.getInstance().getRecord(transaction.getScheduledActionUID()); mRecurrence.setText(scheduledAction.getRepeatString()); findViewById(R.id.row_trn_recurrence).setVisibility(View.VISIBLE); } else { findViewById(R.id.row_trn_recurrence).setVisibility(View.GONE); } if (transaction.getNote() != null && !transaction.getNote().isEmpty()){ mNotes.setText(transaction.getNote()); findViewById(R.id.row_trn_notes).setVisibility(View.VISIBLE); } else { findViewById(R.id.row_trn_notes).setVisibility(View.GONE); } } /** * Refreshes the transaction information */ private void refresh(){ removeSplitItemViews(); bindViews(); } /** * Remove the split item views from the transaction detail prior to refreshing them */ private void removeSplitItemViews(){ // Remove all rows that are not special. mDetailTableLayout.removeViews(0, mDetailTableLayout.getChildCount() - mDetailTableRows); mDebitBalance.setText(""); mCreditBalance.setText(""); } @OnClick(R.id.fab_edit_transaction) public void editTransaction(){ Intent createTransactionIntent = new Intent(this.getApplicationContext(), FormActivity.class); createTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT); createTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); createTransactionIntent.putExtra(UxArgument.SELECTED_TRANSACTION_UID, mTransactionUID); createTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name()); startActivityForResult(createTransactionIntent, REQUEST_EDIT_TRANSACTION); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK){ refresh(); } } }
8,545
38.748837
153
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/TransactionFormFragment.java
/* * Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.inputmethodservice.KeyboardView; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.format.DateUtils; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import android.widget.CheckBox; import android.widget.EditText; import android.widget.FilterQueryProvider; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment; import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment; import com.codetroopers.betterpickers.recurrencepicker.EventRecurrence; import com.codetroopers.betterpickers.recurrencepicker.EventRecurrenceFormatter; import com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.db.adapter.PricesDbAdapter; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.AccountType; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Recurrence; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity; import org.gnucash.android.ui.settings.PreferenceActivity; import org.gnucash.android.ui.transaction.dialog.TransferFundsDialogFragment; import org.gnucash.android.ui.util.RecurrenceParser; import org.gnucash.android.ui.util.RecurrenceViewClickListener; import org.gnucash.android.ui.util.widget.CalculatorEditText; import org.gnucash.android.ui.util.widget.TransactionTypeSwitch; import org.gnucash.android.util.QualifiedAccountNameCursorAdapter; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Fragment for creating or editing transactions * @author Ngewi Fet <[email protected]> */ public class TransactionFormFragment extends Fragment implements CalendarDatePickerDialogFragment.OnDateSetListener, RadialTimePickerDialogFragment.OnTimeSetListener, RecurrencePickerDialogFragment.OnRecurrenceSetListener, OnTransferFundsListener { private static final int REQUEST_SPLIT_EDITOR = 0x11; /** * Transactions database adapter */ private TransactionsDbAdapter mTransactionsDbAdapter; /** * Accounts database adapter */ private AccountsDbAdapter mAccountsDbAdapter; /** * Adapter for transfer account spinner */ private QualifiedAccountNameCursorAdapter mAccountCursorAdapter; /** * Cursor for transfer account spinner */ private Cursor mCursor; /** * Transaction to be created/updated */ private Transaction mTransaction; /** * Formats a {@link Date} object into a date string of the format dd MMM yyyy e.g. 18 July 2012 */ public final static DateFormat DATE_FORMATTER = DateFormat.getDateInstance(); /** * Formats a {@link Date} object to time string of format HH:mm e.g. 15:25 */ public final static DateFormat TIME_FORMATTER = DateFormat.getTimeInstance(); /** * Button for setting the transaction type, either credit or debit */ @BindView(R.id.input_transaction_type) TransactionTypeSwitch mTransactionTypeSwitch; /** * Input field for the transaction name (description) */ @BindView(R.id.input_transaction_name) AutoCompleteTextView mDescriptionEditText; /** * Input field for the transaction amount */ @BindView(R.id.input_transaction_amount) CalculatorEditText mAmountEditText; /** * Field for the transaction currency. * The transaction uses the currency of the account */ @BindView(R.id.currency_symbol) TextView mCurrencyTextView; /** * Input field for the transaction description (note) */ @BindView(R.id.input_description) EditText mNotesEditText; /** * Input field for the transaction date */ @BindView(R.id.input_date) TextView mDateTextView; /** * Input field for the transaction time */ @BindView(R.id.input_time) TextView mTimeTextView; /** * Spinner for selecting the transfer account */ @BindView(R.id.input_transfer_account_spinner) Spinner mTransferAccountSpinner; /** * Checkbox indicating if this transaction should be saved as a template or not */ @BindView(R.id.checkbox_save_template) CheckBox mSaveTemplateCheckbox; @BindView(R.id.input_recurrence) TextView mRecurrenceTextView; /** * View which displays the calculator keyboard */ @BindView(R.id.calculator_keyboard) KeyboardView mKeyboardView; /** * Open the split editor */ @BindView(R.id.btn_split_editor) ImageView mOpenSplitEditor; /** * Layout for transfer account and associated views */ @BindView(R.id.layout_double_entry) View mDoubleEntryLayout; /** * Flag to note if double entry accounting is in use or not */ private boolean mUseDoubleEntry; /** * {@link Calendar} for holding the set date */ private Calendar mDate; /** * {@link Calendar} object holding the set time */ private Calendar mTime; /** * The AccountType of the account to which this transaction belongs. * Used for determining the accounting rules for credits and debits */ AccountType mAccountType; private String mRecurrenceRule; private EventRecurrence mEventRecurrence = new EventRecurrence(); private String mAccountUID; private List<Split> mSplitsList = new ArrayList<>(); private boolean mEditMode = false; /** * Flag which is set if another action is triggered during a transaction save (which interrrupts the save process). * Allows the fragment to check and resume the save operation. * Primarily used for multicurrency transactions when the currency transfer dialog is opened during save */ private boolean onSaveAttempt = false; /** * Split quantity which will be set from the funds transfer dialog */ private Money mSplitQuantity; /** * Create the view and retrieve references to the UI elements */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_transaction_form, container, false); ButterKnife.bind(this, v); mAmountEditText.bindListeners(mKeyboardView); mOpenSplitEditor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openSplitEditor(); } }); return v; } /** * Starts the transfer of funds from one currency to another */ private void startTransferFunds() { Commodity fromCommodity = Commodity.getInstance((mTransactionsDbAdapter.getAccountCurrencyCode(mAccountUID))); long id = mTransferAccountSpinner.getSelectedItemId(); String targetCurrencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountsDbAdapter.getUID(id)); if (fromCommodity.equals(Commodity.getInstance(targetCurrencyCode)) || !mAmountEditText.isInputModified() || mSplitQuantity != null) //if both accounts have same currency return; BigDecimal amountBigd = mAmountEditText.getValue(); if ((amountBigd == null) || amountBigd.equals(BigDecimal.ZERO)) return; Money amount = new Money(amountBigd, fromCommodity).abs(); TransferFundsDialogFragment fragment = TransferFundsDialogFragment.getInstance(amount, targetCurrencyCode, this); fragment.show(getFragmentManager(), "transfer_funds_editor"); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mAmountEditText.bindListeners(mKeyboardView); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); SharedPreferences sharedPrefs = PreferenceActivity.getActiveBookSharedPreferences(); mUseDoubleEntry = sharedPrefs.getBoolean(getString(R.string.key_use_double_entry), false); if (!mUseDoubleEntry){ mDoubleEntryLayout.setVisibility(View.GONE); mOpenSplitEditor.setVisibility(View.GONE); } mAccountUID = getArguments().getString(UxArgument.SELECTED_ACCOUNT_UID); assert(mAccountUID != null); mAccountsDbAdapter = AccountsDbAdapter.getInstance(); mAccountType = mAccountsDbAdapter.getAccountType(mAccountUID); String transactionUID = getArguments().getString(UxArgument.SELECTED_TRANSACTION_UID); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); if (transactionUID != null) { mTransaction = mTransactionsDbAdapter.getRecord(transactionUID); } setListeners(); //updateTransferAccountsList must only be called after initializing mAccountsDbAdapter updateTransferAccountsList(); mTransferAccountSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { /** * Flag for ignoring first call to this listener. * The first call is during layout, but we want it called only in response to user interaction */ boolean userInteraction = false; @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { removeFavoriteIconFromSelectedView((TextView) view); if (mSplitsList.size() == 2) { //when handling simple transfer to one account for (Split split : mSplitsList) { if (!split.getAccountUID().equals(mAccountUID)) { split.setAccountUID(mAccountsDbAdapter.getUID(id)); } // else case is handled when saving the transactions } } if (!userInteraction) { userInteraction = true; return; } startTransferFunds(); } // Removes the icon from view to avoid visual clutter private void removeFavoriteIconFromSelectedView(TextView view) { if (view != null) { view.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { //nothing to see here, move along } }); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); assert actionBar != null; // actionBar.setSubtitle(mAccountsDbAdapter.getFullyQualifiedAccountName(mAccountUID)); if (mTransaction == null) { actionBar.setTitle(R.string.title_add_transaction); initalizeViews(); initTransactionNameAutocomplete(); } else { actionBar.setTitle(R.string.title_edit_transaction); initializeViewsWithTransaction(); mEditMode = true; } getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } /** * Extension of SimpleCursorAdapter which is used to populate the fields for the list items * in the transactions suggestions (auto-complete transaction description). */ private class DropDownCursorAdapter extends SimpleCursorAdapter{ public DropDownCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to, 0); } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); String transactionUID = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry.COLUMN_UID)); Money balance = TransactionsDbAdapter.getInstance().getBalance(transactionUID, mAccountUID); long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry.COLUMN_TIMESTAMP)); String dateString = DateUtils.formatDateTime(getActivity(), timestamp, DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR); TextView secondaryTextView = (TextView) view.findViewById(R.id.secondary_text); secondaryTextView.setText(balance.formattedString() + " on " + dateString); //TODO: Extract string } } /** * Initializes the transaction name field for autocompletion with existing transaction names in the database */ private void initTransactionNameAutocomplete() { final int[] to = new int[]{R.id.primary_text}; final String[] from = new String[]{DatabaseSchema.TransactionEntry.COLUMN_DESCRIPTION}; SimpleCursorAdapter adapter = new DropDownCursorAdapter( getActivity(), R.layout.dropdown_item_2lines, null, from, to); adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() { @Override public CharSequence convertToString(Cursor cursor) { final int colIndex = cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry.COLUMN_DESCRIPTION); return cursor.getString(colIndex); } }); adapter.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(CharSequence name) { return mTransactionsDbAdapter.fetchTransactionSuggestions(name == null ? "" : name.toString(), mAccountUID); } }); mDescriptionEditText.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { mTransaction = new Transaction(mTransactionsDbAdapter.getRecord(id), true); mTransaction.setTime(System.currentTimeMillis()); //we check here because next method will modify it and we want to catch user-modification boolean amountEntered = mAmountEditText.isInputModified(); initializeViewsWithTransaction(); List<Split> splitList = mTransaction.getSplits(); boolean isSplitPair = splitList.size() == 2 && splitList.get(0).isPairOf(splitList.get(1)); if (isSplitPair){ mSplitsList.clear(); if (!amountEntered) //if user already entered an amount mAmountEditText.setValue(splitList.get(0).getValue().asBigDecimal()); } else { if (amountEntered){ //if user entered own amount, clear loaded splits and use the user value mSplitsList.clear(); setDoubleEntryViewsVisibility(View.VISIBLE); } else { if (mUseDoubleEntry) { //don't hide the view in single entry mode setDoubleEntryViewsVisibility(View.GONE); } } } mTransaction = null; //we are creating a new transaction after all } }); mDescriptionEditText.setAdapter(adapter); } /** * Initialize views in the fragment with information from a transaction. * This method is called if the fragment is used for editing a transaction */ private void initializeViewsWithTransaction(){ mDescriptionEditText.setText(mTransaction.getDescription()); mDescriptionEditText.setSelection(mDescriptionEditText.getText().length()); mTransactionTypeSwitch.setAccountType(mAccountType); mTransactionTypeSwitch.setChecked(mTransaction.getBalance(mAccountUID).isNegative()); if (!mAmountEditText.isInputModified()){ //when autocompleting, only change the amount if the user has not manually changed it already mAmountEditText.setValue(mTransaction.getBalance(mAccountUID).asBigDecimal()); } mCurrencyTextView.setText(mTransaction.getCommodity().getSymbol()); mNotesEditText.setText(mTransaction.getNote()); mDateTextView.setText(DATE_FORMATTER.format(mTransaction.getTimeMillis())); mTimeTextView.setText(TIME_FORMATTER.format(mTransaction.getTimeMillis())); Calendar cal = GregorianCalendar.getInstance(); cal.setTimeInMillis(mTransaction.getTimeMillis()); mDate = mTime = cal; //TODO: deep copy the split list. We need a copy so we can modify with impunity mSplitsList = new ArrayList<>(mTransaction.getSplits()); toggleAmountInputEntryMode(mSplitsList.size() <= 2); if (mSplitsList.size() == 2){ for (Split split : mSplitsList) { if (split.getAccountUID().equals(mAccountUID)) { if (!split.getQuantity().getCommodity().equals(mTransaction.getCommodity())){ mSplitQuantity = split.getQuantity(); } } } } //if there are more than two splits (which is the default for one entry), then //disable editing of the transfer account. User should open editor if (mSplitsList.size() == 2 && mSplitsList.get(0).isPairOf(mSplitsList.get(1))) { for (Split split : mTransaction.getSplits()) { //two splits, one belongs to this account and the other to another account if (mUseDoubleEntry && !split.getAccountUID().equals(mAccountUID)) { setSelectedTransferAccount(mAccountsDbAdapter.getID(split.getAccountUID())); } } } else { setDoubleEntryViewsVisibility(View.GONE); } String currencyCode = mTransactionsDbAdapter.getAccountCurrencyCode(mAccountUID); Commodity accountCommodity = Commodity.getInstance(currencyCode); mCurrencyTextView.setText(accountCommodity.getSymbol()); Commodity commodity = Commodity.getInstance(currencyCode); mAmountEditText.setCommodity(commodity); mSaveTemplateCheckbox.setChecked(mTransaction.isTemplate()); String scheduledActionUID = getArguments().getString(UxArgument.SCHEDULED_ACTION_UID); if (scheduledActionUID != null && !scheduledActionUID.isEmpty()) { ScheduledAction scheduledAction = ScheduledActionDbAdapter.getInstance().getRecord(scheduledActionUID); mRecurrenceRule = scheduledAction.getRuleString(); mEventRecurrence.parse(mRecurrenceRule); mRecurrenceTextView.setText(scheduledAction.getRepeatString()); } } private void setDoubleEntryViewsVisibility(int visibility) { mDoubleEntryLayout.setVisibility(visibility); mTransactionTypeSwitch.setVisibility(visibility); } private void toggleAmountInputEntryMode(boolean enabled){ if (enabled){ mAmountEditText.setFocusable(true); mAmountEditText.bindListeners(mKeyboardView); } else { mAmountEditText.setFocusable(false); mAmountEditText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openSplitEditor(); } }); } } /** * Initialize views with default data for new transactions */ private void initalizeViews() { Date time = new Date(System.currentTimeMillis()); mDateTextView.setText(DATE_FORMATTER.format(time)); mTimeTextView.setText(TIME_FORMATTER.format(time)); mTime = mDate = Calendar.getInstance(); mTransactionTypeSwitch.setAccountType(mAccountType); String typePref = PreferenceActivity.getActiveBookSharedPreferences().getString(getString(R.string.key_default_transaction_type), "DEBIT"); mTransactionTypeSwitch.setChecked(TransactionType.valueOf(typePref)); String code = GnuCashApplication.getDefaultCurrencyCode(); if (mAccountUID != null){ code = mTransactionsDbAdapter.getAccountCurrencyCode(mAccountUID); } Commodity commodity = Commodity.getInstance(code); mCurrencyTextView.setText(commodity.getSymbol()); mAmountEditText.setCommodity(commodity); if (mUseDoubleEntry){ String currentAccountUID = mAccountUID; long defaultTransferAccountID; String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID(); do { defaultTransferAccountID = mAccountsDbAdapter.getDefaultTransferAccountID(mAccountsDbAdapter.getID(currentAccountUID)); if (defaultTransferAccountID > 0) { setSelectedTransferAccount(defaultTransferAccountID); break; //we found a parent with default transfer setting } currentAccountUID = mAccountsDbAdapter.getParentAccountUID(currentAccountUID); } while (!currentAccountUID.equals(rootAccountUID)); } } /** * Updates the list of possible transfer accounts. * Only accounts with the same currency can be transferred to */ private void updateTransferAccountsList(){ String conditions = "(" + DatabaseSchema.AccountEntry.COLUMN_UID + " != ?" + " AND " + DatabaseSchema.AccountEntry.COLUMN_TYPE + " != ?" + " AND " + DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + " = 0" + ")"; if (mCursor != null) { mCursor.close(); } mCursor = mAccountsDbAdapter.fetchAccountsOrderedByFavoriteAndFullName(conditions, new String[]{mAccountUID, AccountType.ROOT.name()}); mAccountCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), mCursor); mTransferAccountSpinner.setAdapter(mAccountCursorAdapter); } /** * Opens the split editor dialog */ private void openSplitEditor(){ if (mAmountEditText.getValue() == null){ Toast.makeText(getActivity(), R.string.toast_enter_amount_to_split, Toast.LENGTH_SHORT).show(); return; } String baseAmountString; if (mTransaction == null){ //if we are creating a new transaction (not editing an existing one) BigDecimal enteredAmount = mAmountEditText.getValue(); baseAmountString = enteredAmount.toPlainString(); } else { Money biggestAmount = Money.createZeroInstance(mTransaction.getCurrencyCode()); for (Split split : mTransaction.getSplits()) { if (split.getValue().asBigDecimal().compareTo(biggestAmount.asBigDecimal()) > 0) biggestAmount = split.getValue(); } baseAmountString = biggestAmount.toPlainString(); } Intent intent = new Intent(getActivity(), FormActivity.class); intent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.SPLIT_EDITOR.name()); intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); intent.putExtra(UxArgument.AMOUNT_STRING, baseAmountString); intent.putParcelableArrayListExtra(UxArgument.SPLIT_LIST, (ArrayList<Split>) extractSplitsFromView()); startActivityForResult(intent, REQUEST_SPLIT_EDITOR); } /** * Sets click listeners for the dialog buttons */ private void setListeners() { mTransactionTypeSwitch.setAmountFormattingListener(mAmountEditText, mCurrencyTextView); mDateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { long dateMillis = 0; try { Date date = DATE_FORMATTER.parse(mDateTextView.getText().toString()); dateMillis = date.getTime(); } catch (ParseException e) { Log.e(getTag(), "Error converting input time to Date object"); } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(dateMillis); int year = calendar.get(Calendar.YEAR); int monthOfYear = calendar.get(Calendar.MONTH); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); CalendarDatePickerDialogFragment datePickerDialog = new CalendarDatePickerDialogFragment() .setOnDateSetListener(TransactionFormFragment.this) .setPreselectedDate(year, monthOfYear, dayOfMonth); datePickerDialog.show(getFragmentManager(), "date_picker_fragment"); } }); mTimeTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { long timeMillis = 0; try { Date date = TIME_FORMATTER.parse(mTimeTextView.getText().toString()); timeMillis = date.getTime(); } catch (ParseException e) { Log.e(getTag(), "Error converting input time to Date object"); } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeMillis); RadialTimePickerDialogFragment timePickerDialog = new RadialTimePickerDialogFragment() .setOnTimeSetListener(TransactionFormFragment.this) .setStartTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)); timePickerDialog.show(getFragmentManager(), "time_picker_dialog_fragment"); } }); mRecurrenceTextView.setOnClickListener(new RecurrenceViewClickListener((AppCompatActivity) getActivity(), mRecurrenceRule, this)); } /** * Updates the spinner to the selected transfer account * @param accountId Database ID of the transfer account */ private void setSelectedTransferAccount(long accountId){ int position = mAccountCursorAdapter.getPosition(mAccountsDbAdapter.getUID(accountId)); if (position >= 0) mTransferAccountSpinner.setSelection(position); } /** * Returns a list of splits based on the input in the transaction form. * This only gets the splits from the simple view, and not those from the Split Editor. * If the Split Editor has been used and there is more than one split, then it returns {@link #mSplitsList} * @return List of splits in the view or {@link #mSplitsList} is there are more than 2 splits in the transaction */ private List<Split> extractSplitsFromView(){ if (mTransactionTypeSwitch.getVisibility() != View.VISIBLE){ return mSplitsList; } BigDecimal amountBigd = mAmountEditText.getValue(); String baseCurrencyCode = mTransactionsDbAdapter.getAccountCurrencyCode(mAccountUID); Money value = new Money(amountBigd, Commodity.getInstance(baseCurrencyCode)); Money quantity = new Money(value); String transferAcctUID = getTransferAccountUID(); CommoditiesDbAdapter cmdtyDbAdapter = CommoditiesDbAdapter.getInstance(); if (isMultiCurrencyTransaction()){ //if multi-currency transaction String transferCurrencyCode = mAccountsDbAdapter.getCurrencyCode(transferAcctUID); String commodityUID = cmdtyDbAdapter.getCommodityUID(baseCurrencyCode); String targetCmdtyUID = cmdtyDbAdapter.getCommodityUID(transferCurrencyCode); Pair<Long, Long> pricePair = PricesDbAdapter.getInstance() .getPrice(commodityUID, targetCmdtyUID); if (pricePair.first > 0 && pricePair.second > 0) { quantity = quantity.multiply(pricePair.first.intValue()) .divide(pricePair.second.intValue()) .withCurrency(cmdtyDbAdapter.getRecord(targetCmdtyUID)); } } Split split1; Split split2; // Try to preserve the other split attributes. if (mSplitsList.size() >= 2) { split1 = mSplitsList.get(0); split1.setValue(value); split1.setQuantity(value); split1.setAccountUID(mAccountUID); split2 = mSplitsList.get(1); split2.setValue(value); split2.setQuantity(quantity); split2.setAccountUID(transferAcctUID); } else { split1 = new Split(value, mAccountUID); split2 = new Split(value, quantity, transferAcctUID); } split1.setType(mTransactionTypeSwitch.getTransactionType()); split2.setType(mTransactionTypeSwitch.getTransactionType().invert()); List<Split> splitList = new ArrayList<>(); splitList.add(split1); splitList.add(split2); return splitList; } /** * Returns the GUID of the currently selected transfer account. * If double-entry is disabled, this method returns the GUID of the imbalance account for the currently active account * @return GUID of transfer account */ private @NonNull String getTransferAccountUID() { String transferAcctUID; if (mUseDoubleEntry) { long transferAcctId = mTransferAccountSpinner.getSelectedItemId(); transferAcctUID = mAccountsDbAdapter.getUID(transferAcctId); } else { Commodity baseCommodity = mAccountsDbAdapter.getRecord(mAccountUID).getCommodity(); transferAcctUID = mAccountsDbAdapter.getOrCreateImbalanceAccountUID(baseCommodity); } return transferAcctUID; } /** * Extracts a transaction from the input in the form fragment * @return New transaction object containing all info in the form */ private @NonNull Transaction extractTransactionFromView(){ Calendar cal = new GregorianCalendar( mDate.get(Calendar.YEAR), mDate.get(Calendar.MONTH), mDate.get(Calendar.DAY_OF_MONTH), mTime.get(Calendar.HOUR_OF_DAY), mTime.get(Calendar.MINUTE), mTime.get(Calendar.SECOND)); String description = mDescriptionEditText.getText().toString(); String notes = mNotesEditText.getText().toString(); String currencyCode = mAccountsDbAdapter.getAccountCurrencyCode(mAccountUID); Commodity commodity = CommoditiesDbAdapter.getInstance().getCommodity(currencyCode); List<Split> splits = extractSplitsFromView(); Transaction transaction = new Transaction(description); transaction.setTime(cal.getTimeInMillis()); transaction.setCommodity(commodity); transaction.setNote(notes); transaction.setSplits(splits); transaction.setExported(false); //not necessary as exports use timestamps now. Because, legacy return transaction; } /** * Checks whether the split editor has been used for editing this transaction. * <p>The Split Editor is considered to have been used if the transaction type switch is not visible</p> * @return {@code true} if split editor was used, {@code false} otherwise */ private boolean splitEditorUsed(){ return mTransactionTypeSwitch.getVisibility() != View.VISIBLE; } /** * Checks if this is a multi-currency transaction being created/edited * <p>A multi-currency transaction is one in which the main account and transfer account have different currencies. <br> * Single-entry transactions cannot be multi-currency</p> * @return {@code true} if multi-currency transaction, {@code false} otherwise */ private boolean isMultiCurrencyTransaction(){ if (!mUseDoubleEntry) return false; String transferAcctUID = mAccountsDbAdapter.getUID(mTransferAccountSpinner.getSelectedItemId()); String currencyCode = mAccountsDbAdapter.getAccountCurrencyCode(mAccountUID); String transferCurrencyCode = mAccountsDbAdapter.getCurrencyCode(transferAcctUID); return !currencyCode.equals(transferCurrencyCode); } /** * Collects information from the fragment views and uses it to create * and save a transaction */ private void saveNewTransaction() { mAmountEditText.getCalculatorKeyboard().hideCustomKeyboard(); //determine whether we need to do currency conversion if (isMultiCurrencyTransaction() && !splitEditorUsed() && !mCurrencyConversionDone){ onSaveAttempt = true; startTransferFunds(); return; } Transaction transaction = extractTransactionFromView(); if (mEditMode) { //if editing an existing transaction transaction.setUID(mTransaction.getUID()); } mTransaction = transaction; mAccountsDbAdapter.beginTransaction(); try { // 1) mTransactions may be existing or non-existing // 2) when mTransactions exists in the db, the splits may exist or not exist in the db // So replace is chosen. mTransactionsDbAdapter.addRecord(mTransaction, DatabaseAdapter.UpdateMethod.replace); if (mSaveTemplateCheckbox.isChecked()) {//template is automatically checked when a transaction is scheduled if (!mEditMode) { //means it was new transaction, so a new template Transaction templateTransaction = new Transaction(mTransaction, true); templateTransaction.setTemplate(true); mTransactionsDbAdapter.addRecord(templateTransaction, DatabaseAdapter.UpdateMethod.replace); scheduleRecurringTransaction(templateTransaction.getUID()); } else scheduleRecurringTransaction(mTransaction.getUID()); } else { String scheduledActionUID = getArguments().getString(UxArgument.SCHEDULED_ACTION_UID); if (scheduledActionUID != null){ //we were editing a schedule and it was turned off ScheduledActionDbAdapter.getInstance().deleteRecord(scheduledActionUID); } } mAccountsDbAdapter.setTransactionSuccessful(); } finally { mAccountsDbAdapter.endTransaction(); } //update widgets, if any WidgetConfigurationActivity.updateAllWidgets(getActivity().getApplicationContext()); finish(Activity.RESULT_OK); } /** * Schedules a recurring transaction (if necessary) after the transaction has been saved * @see #saveNewTransaction() */ private void scheduleRecurringTransaction(String transactionUID) { ScheduledActionDbAdapter scheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance(); Recurrence recurrence = RecurrenceParser.parse(mEventRecurrence); ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction.setRecurrence(recurrence); String scheduledActionUID = getArguments().getString(UxArgument.SCHEDULED_ACTION_UID); if (scheduledActionUID != null) { //if we are editing an existing schedule if (recurrence == null){ scheduledActionDbAdapter.deleteRecord(scheduledActionUID); } else { scheduledAction.setUID(scheduledActionUID); scheduledActionDbAdapter.updateRecurrenceAttributes(scheduledAction); Toast.makeText(getActivity(), R.string.toast_updated_transaction_recurring_schedule, Toast.LENGTH_SHORT).show(); } } else { if (recurrence != null) { scheduledAction.setActionUID(transactionUID); scheduledActionDbAdapter.addRecord(scheduledAction, DatabaseAdapter.UpdateMethod.replace); Toast.makeText(getActivity(), R.string.toast_scheduled_recurring_transaction, Toast.LENGTH_SHORT).show(); } } } @Override public void onDestroyView() { super.onDestroyView(); if (mCursor != null) mCursor.close(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.default_save_actions, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { //hide the keyboard if it is visible InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mDescriptionEditText.getApplicationWindowToken(), 0); switch (item.getItemId()) { case android.R.id.home: finish(Activity.RESULT_CANCELED); return true; case R.id.menu_save: if (canSave()){ saveNewTransaction(); } else { if (mAmountEditText.getValue() == null) { Toast.makeText(getActivity(), R.string.toast_transanction_amount_required, Toast.LENGTH_SHORT).show(); } if (mUseDoubleEntry && mTransferAccountSpinner.getCount() == 0){ Toast.makeText(getActivity(), R.string.toast_disable_double_entry_to_save_transaction, Toast.LENGTH_LONG).show(); } } return true; default: return super.onOptionsItemSelected(item); } } /** * Checks if the pre-requisites for saving the transaction are fulfilled * <p>The conditions checked are that a valid amount is entered and that a transfer account is set (where applicable)</p> * @return {@code true} if the transaction can be saved, {@code false} otherwise */ private boolean canSave(){ return (mUseDoubleEntry && mAmountEditText.isInputValid() && mTransferAccountSpinner.getCount() > 0) || (!mUseDoubleEntry && mAmountEditText.isInputValid()); } /** * Called by the split editor fragment to notify of finished editing * @param splitList List of splits produced in the fragment */ public void setSplitList(List<Split> splitList){ mSplitsList = splitList; Money balance = Transaction.computeBalance(mAccountUID, mSplitsList); mAmountEditText.setValue(balance.asBigDecimal()); mTransactionTypeSwitch.setChecked(balance.isNegative()); } /** * Finishes the fragment appropriately. * Depends on how the fragment was loaded, it might have a backstack or not */ private void finish(int resultCode) { if (getActivity().getSupportFragmentManager().getBackStackEntryCount() == 0){ getActivity().setResult(resultCode); //means we got here directly from the accounts list activity, need to finish getActivity().finish(); } else { //go back to transactions list getActivity().getSupportFragmentManager().popBackStack(); } } @Override public void onDateSet(CalendarDatePickerDialogFragment calendarDatePickerDialog, int year, int monthOfYear, int dayOfMonth) { Calendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth); mDateTextView.setText(DATE_FORMATTER.format(cal.getTime())); mDate.set(Calendar.YEAR, year); mDate.set(Calendar.MONTH, monthOfYear); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); } @Override public void onTimeSet(RadialTimePickerDialogFragment radialTimePickerDialog, int hourOfDay, int minute) { Calendar cal = new GregorianCalendar(0, 0, 0, hourOfDay, minute); mTimeTextView.setText(TIME_FORMATTER.format(cal.getTime())); mTime.set(Calendar.HOUR_OF_DAY, hourOfDay); mTime.set(Calendar.MINUTE, minute); } /** * Strips formatting from a currency string. * All non-digit information is removed, but the sign is preserved. * @param s String to be stripped * @return Stripped string with all non-digits removed */ public static String stripCurrencyFormatting(String s){ if (s.length() == 0) return s; //remove all currency formatting and anything else which is not a number String sign = s.trim().substring(0,1); String stripped = s.trim().replaceAll("\\D*", ""); if (stripped.length() == 0) return ""; if (sign.equals("+") || sign.equals("-")){ stripped = sign + stripped; } return stripped; } /** * Flag for checking where the TransferFunds dialog has already been displayed to the user */ boolean mCurrencyConversionDone = false; @Override public void transferComplete(Money amount) { mCurrencyConversionDone = true; mSplitQuantity = amount; //The transfer dialog was called while attempting to save. So try saving again if (onSaveAttempt) saveNewTransaction(); onSaveAttempt = false; } @Override public void onRecurrenceSet(String rrule) { mRecurrenceRule = rrule; String repeatString = getString(R.string.label_tap_to_create_schedule); if (mRecurrenceRule != null){ mEventRecurrence.parse(mRecurrenceRule); repeatString = EventRecurrenceFormatter.getRepeatString(getActivity(), getResources(), mEventRecurrence, true); //when recurrence is set, we will definitely be saving a template mSaveTemplateCheckbox.setChecked(true); mSaveTemplateCheckbox.setEnabled(false); } else { mSaveTemplateCheckbox.setEnabled(true); mSaveTemplateCheckbox.setChecked(false); } mRecurrenceTextView.setText(repeatString); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK){ List<Split> splitList = data.getParcelableArrayListExtra(UxArgument.SPLIT_LIST); setSplitList(splitList); //once split editor has been used and saved, only allow editing through it toggleAmountInputEntryMode(false); setDoubleEntryViewsVisibility(View.GONE); mOpenSplitEditor.setVisibility(View.VISIBLE); } } }
44,599
39.955005
141
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/TransactionsActivity.java
/* * Copyright (c) 2012 - 2015 Ngewi Fet <[email protected]> * Copyright (c) 2014 Yongxin Wang <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.format.DateUtils; import android.util.Log; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Money; import org.gnucash.android.ui.account.AccountsActivity; import org.gnucash.android.ui.account.AccountsListFragment; import org.gnucash.android.ui.account.OnAccountClickedListener; import org.gnucash.android.ui.common.BaseDrawerActivity; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.ui.common.Refreshable; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.util.AccountBalanceTask; import org.gnucash.android.util.QualifiedAccountNameCursorAdapter; import org.joda.time.LocalDate; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; import butterknife.BindView; /** * Activity for displaying, creating and editing transactions * @author Ngewi Fet <[email protected]> */ public class TransactionsActivity extends BaseDrawerActivity implements Refreshable, OnAccountClickedListener, OnTransactionClickedListener{ /** * Logging tag */ protected static final String TAG = "TransactionsActivity"; /** * ViewPager index for sub-accounts fragment */ private static final int INDEX_SUB_ACCOUNTS_FRAGMENT = 0; /** * ViewPager index for transactions fragment */ private static final int INDEX_TRANSACTIONS_FRAGMENT = 1; /** * Number of pages to show */ private static final int DEFAULT_NUM_PAGES = 2; private static SimpleDateFormat mDayMonthDateFormat = new SimpleDateFormat("EEE, d MMM"); /** * GUID of {@link Account} whose transactions are displayed */ private String mAccountUID = null; /** * Account database adapter for manipulating the accounts list in navigation */ private AccountsDbAdapter mAccountsDbAdapter; /** * Hold the accounts cursor that will be used in the Navigation */ private Cursor mAccountsCursor = null; @BindView(R.id.pager) ViewPager mViewPager; @BindView(R.id.toolbar_spinner) Spinner mToolbarSpinner; @BindView(R.id.tab_layout) TabLayout mTabLayout; @BindView(R.id.transactions_sum) TextView mSumTextView; @BindView(R.id.fab_create_transaction) FloatingActionButton mCreateFloatingButton; private SparseArray<Refreshable> mFragmentPageReferenceMap = new SparseArray<>(); /** * Flag for determining is the currently displayed account is a placeholder account or not. * This will determine if the transactions tab is displayed or not */ private boolean mIsPlaceholderAccount; private AdapterView.OnItemSelectedListener mTransactionListNavigationListener = new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mAccountUID = mAccountsDbAdapter.getUID(id); getIntent().putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); //update the intent in case the account gets rotated mIsPlaceholderAccount = mAccountsDbAdapter.isPlaceholderAccount(mAccountUID); if (mIsPlaceholderAccount){ if (mTabLayout.getTabCount() > 1) { mPagerAdapter.notifyDataSetChanged(); mTabLayout.removeTabAt(1); } } else { if (mTabLayout.getTabCount() < 2) { mPagerAdapter.notifyDataSetChanged(); mTabLayout.addTab(mTabLayout.newTab().setText(R.string.section_header_transactions)); } } if (view != null) { // Hide the favorite icon of the selected account to avoid clutter ((TextView) view).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } //refresh any fragments in the tab with the new account UID refresh(); } @Override public void onNothingSelected(AdapterView<?> parent) { //nothing to see here, move along } }; private PagerAdapter mPagerAdapter; /** * Adapter for managing the sub-account and transaction fragment pages in the accounts view */ private class AccountViewPagerAdapter extends FragmentStatePagerAdapter { public AccountViewPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int i) { if (mIsPlaceholderAccount){ Fragment transactionsListFragment = prepareSubAccountsListFragment(); mFragmentPageReferenceMap.put(i, (Refreshable) transactionsListFragment); return transactionsListFragment; } Fragment currentFragment; switch (i){ case INDEX_SUB_ACCOUNTS_FRAGMENT: currentFragment = prepareSubAccountsListFragment(); break; case INDEX_TRANSACTIONS_FRAGMENT: default: currentFragment = prepareTransactionsListFragment(); break; } mFragmentPageReferenceMap.put(i, (Refreshable)currentFragment); return currentFragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); mFragmentPageReferenceMap.remove(position); } @Override public CharSequence getPageTitle(int position) { if (mIsPlaceholderAccount) return getString(R.string.section_header_subaccounts); switch (position){ case INDEX_SUB_ACCOUNTS_FRAGMENT: return getString(R.string.section_header_subaccounts); case INDEX_TRANSACTIONS_FRAGMENT: default: return getString(R.string.section_header_transactions); } } @Override public int getCount() { if (mIsPlaceholderAccount) return 1; else return DEFAULT_NUM_PAGES; } /** * Creates and initializes the fragment for displaying sub-account list * @return {@link AccountsListFragment} initialized with the sub-accounts */ private AccountsListFragment prepareSubAccountsListFragment(){ AccountsListFragment subAccountsListFragment = new AccountsListFragment(); Bundle args = new Bundle(); args.putString(UxArgument.PARENT_ACCOUNT_UID, mAccountUID); subAccountsListFragment.setArguments(args); return subAccountsListFragment; } /** * Creates and initializes fragment for displaying transactions * @return {@link TransactionsListFragment} initialized with the current account transactions */ private TransactionsListFragment prepareTransactionsListFragment(){ TransactionsListFragment transactionsListFragment = new TransactionsListFragment(); Bundle args = new Bundle(); args.putString(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); transactionsListFragment.setArguments(args); Log.i(TAG, "Opening transactions for account: " + mAccountUID); return transactionsListFragment; } } /** * Refreshes the fragments currently in the transactions activity */ @Override public void refresh(String accountUID) { for (int i = 0; i < mFragmentPageReferenceMap.size(); i++) { mFragmentPageReferenceMap.valueAt(i).refresh(accountUID); } if (mPagerAdapter != null) mPagerAdapter.notifyDataSetChanged(); new AccountBalanceTask(mSumTextView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mAccountUID); } @Override public void refresh(){ refresh(mAccountUID); setTitleIndicatorColor(); } @Override public int getContentView() { return R.layout.activity_transactions; } @Override public int getTitleRes() { return R.string.title_transactions; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setDisplayShowTitleEnabled(false); mAccountUID = getIntent().getStringExtra(UxArgument.SELECTED_ACCOUNT_UID); mAccountsDbAdapter = AccountsDbAdapter.getInstance(); mIsPlaceholderAccount = mAccountsDbAdapter.isPlaceholderAccount(mAccountUID); mTabLayout.addTab(mTabLayout.newTab().setText(R.string.section_header_subaccounts)); if (!mIsPlaceholderAccount) { mTabLayout.addTab(mTabLayout.newTab().setText(R.string.section_header_transactions)); } setupActionBarNavigation(); mPagerAdapter = new AccountViewPagerAdapter(getSupportFragmentManager()); mViewPager.setAdapter(mPagerAdapter); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout)); mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { //nothing to see here, move along } @Override public void onTabReselected(TabLayout.Tab tab) { //nothing to see here, move along } }); //if there are no transactions, and there are sub-accounts, show the sub-accounts if (TransactionsDbAdapter.getInstance().getTransactionsCount(mAccountUID) == 0 && mAccountsDbAdapter.getSubAccountCount(mAccountUID) > 0){ mViewPager.setCurrentItem(INDEX_SUB_ACCOUNTS_FRAGMENT); } else { mViewPager.setCurrentItem(INDEX_TRANSACTIONS_FRAGMENT); } mCreateFloatingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (mViewPager.getCurrentItem()) { case INDEX_SUB_ACCOUNTS_FRAGMENT: Intent addAccountIntent = new Intent(TransactionsActivity.this, FormActivity.class); addAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT); addAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.ACCOUNT.name()); addAccountIntent.putExtra(UxArgument.PARENT_ACCOUNT_UID, mAccountUID); startActivityForResult(addAccountIntent, AccountsActivity.REQUEST_EDIT_ACCOUNT); ; break; case INDEX_TRANSACTIONS_FRAGMENT: createNewTransaction(mAccountUID); break; } } }); } @Override protected void onResume() { super.onResume(); setTitleIndicatorColor(); } /** * Sets the color for the ViewPager title indicator to match the account color */ private void setTitleIndicatorColor() { int iColor = AccountsDbAdapter.getActiveAccountColorResource(mAccountUID); mTabLayout.setBackgroundColor(iColor); if (getSupportActionBar() != null) getSupportActionBar().setBackgroundDrawable(new ColorDrawable(iColor)); if (Build.VERSION.SDK_INT > 20) getWindow().setStatusBarColor(GnuCashApplication.darken(iColor)); } /** * Set up action bar navigation list and listener callbacks */ private void setupActionBarNavigation() { // set up spinner adapter for navigation list if (mAccountsCursor != null) { mAccountsCursor.close(); } mAccountsCursor = mAccountsDbAdapter.fetchAllRecordsOrderedByFullName(); SpinnerAdapter mSpinnerAdapter = new QualifiedAccountNameCursorAdapter( getSupportActionBar().getThemedContext(), mAccountsCursor, R.layout.account_spinner_item); mToolbarSpinner.setAdapter(mSpinnerAdapter); mToolbarSpinner.setOnItemSelectedListener(mTransactionListNavigationListener); getSupportActionBar().setDisplayHomeAsUpEnabled(true); updateNavigationSelection(); } /** * Updates the action bar navigation list selection to that of the current account * whose transactions are being displayed/manipulated */ public void updateNavigationSelection() { // set the selected item in the spinner int i = 0; Cursor accountsCursor = mAccountsDbAdapter.fetchAllRecordsOrderedByFullName(); while (accountsCursor.moveToNext()) { String uid = accountsCursor.getString(accountsCursor.getColumnIndexOrThrow(DatabaseSchema.AccountEntry.COLUMN_UID)); if (mAccountUID.equals(uid)) { mToolbarSpinner.setSelection(i); break; } ++i; } accountsCursor.close(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem favoriteAccountMenuItem = menu.findItem(R.id.menu_favorite_account); if (favoriteAccountMenuItem == null) //when the activity is used to edit a transaction return super.onPrepareOptionsMenu(menu); boolean isFavoriteAccount = AccountsDbAdapter.getInstance().isFavoriteAccount(mAccountUID); int favoriteIcon = isFavoriteAccount ? R.drawable.ic_star_white_24dp : R.drawable.ic_star_border_white_24dp; favoriteAccountMenuItem.setIcon(favoriteIcon); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: return super.onOptionsItemSelected(item); case R.id.menu_favorite_account: AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); long accountId = accountsDbAdapter.getID(mAccountUID); boolean isFavorite = accountsDbAdapter.isFavoriteAccount(mAccountUID); //toggle favorite preference accountsDbAdapter.updateAccount(accountId, DatabaseSchema.AccountEntry.COLUMN_FAVORITE, isFavorite ? "0" : "1"); supportInvalidateOptionsMenu(); return true; case R.id.menu_edit_account: Intent editAccountIntent = new Intent(this, FormActivity.class); editAccountIntent.setAction(Intent.ACTION_INSERT_OR_EDIT); editAccountIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); editAccountIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.ACCOUNT.name()); startActivityForResult(editAccountIntent, AccountsActivity.REQUEST_EDIT_ACCOUNT); return true; default: return false; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_CANCELED) return; refresh(); setupActionBarNavigation(); super.onActivityResult(requestCode, resultCode, data); } @Override protected void onDestroy() { super.onDestroy(); mAccountsCursor.close(); } /** * Returns the global unique ID of the current account * @return GUID of the current account */ public String getCurrentAccountUID(){ return mAccountUID; } /** * Display the balance of a transaction in a text view and format the text color to match the sign of the amount * @param balanceTextView {@link android.widget.TextView} where balance is to be displayed * @param balance {@link org.gnucash.android.model.Money} balance to display */ public static void displayBalance(TextView balanceTextView, Money balance){ balanceTextView.setText(balance.formattedString()); Context context = GnuCashApplication.getAppContext(); int fontColor = balance.isNegative() ? context.getResources().getColor(R.color.debit_red) : context.getResources().getColor(R.color.credit_green); if (balance.asBigDecimal().compareTo(BigDecimal.ZERO) == 0) fontColor = context.getResources().getColor(android.R.color.black); balanceTextView.setTextColor(fontColor); } /** * Formats the date to show the the day of the week if the {@code dateMillis} is within 7 days * of today. Else it shows the actual date formatted as short string. <br> * It also shows "today", "yesterday" or "tomorrow" if the date is on any of those days * @param dateMillis * @return */ @NonNull public static String getPrettyDateFormat(Context context, long dateMillis) { LocalDate transactionTime = new LocalDate(dateMillis); LocalDate today = new LocalDate(); String prettyDateText = null; if (transactionTime.compareTo(today.minusDays(1)) >= 0 && transactionTime.compareTo(today.plusDays(1)) <= 0){ prettyDateText = DateUtils.getRelativeTimeSpanString(dateMillis, System.currentTimeMillis(), DateUtils.DAY_IN_MILLIS).toString(); } else if (transactionTime.getYear() == today.getYear()){ prettyDateText = mDayMonthDateFormat.format(new Date(dateMillis)); } else { prettyDateText = DateUtils.formatDateTime(context, dateMillis, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_YEAR); } return prettyDateText; } @Override public void createNewTransaction(String accountUID) { Intent createTransactionIntent = new Intent(this.getApplicationContext(), FormActivity.class); createTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT); createTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID); createTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name()); startActivity(createTransactionIntent); } @Override public void editTransaction(String transactionUID){ Intent createTransactionIntent = new Intent(this.getApplicationContext(), FormActivity.class); createTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT); createTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); createTransactionIntent.putExtra(UxArgument.SELECTED_TRANSACTION_UID, transactionUID); createTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name()); startActivity(createTransactionIntent); } @Override public void accountSelected(String accountUID) { Intent restartIntent = new Intent(this.getApplicationContext(), TransactionsActivity.class); restartIntent.setAction(Intent.ACTION_VIEW); restartIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID); startActivity(restartIntent); } }
21,101
37.719266
141
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/TransactionsListFragment.java
/* * Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseCursorLoader; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.db.adapter.SplitsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.ui.common.Refreshable; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity; import org.gnucash.android.ui.settings.PreferenceActivity; import org.gnucash.android.ui.transaction.dialog.BulkMoveDialogFragment; import org.gnucash.android.ui.util.CursorRecyclerAdapter; import org.gnucash.android.ui.util.widget.EmptyRecyclerView; import org.gnucash.android.util.BackupManager; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * List Fragment for displaying list of transactions for an account * @author Ngewi Fet <[email protected]> * */ public class TransactionsListFragment extends Fragment implements Refreshable, LoaderCallbacks<Cursor>{ /** * Logging tag */ protected static final String LOG_TAG = "TransactionListFragment"; private TransactionsDbAdapter mTransactionsDbAdapter; private String mAccountUID; private boolean mUseCompactView = false; private TransactionRecyclerAdapter mTransactionRecyclerAdapter; @BindView(R.id.transaction_recycler_view) EmptyRecyclerView mRecyclerView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); Bundle args = getArguments(); mAccountUID = args.getString(UxArgument.SELECTED_ACCOUNT_UID); mUseCompactView = PreferenceActivity.getActiveBookSharedPreferences() .getBoolean(getActivity().getString(R.string.key_use_compact_list), !GnuCashApplication.isDoubleEntryEnabled()); //if there was a local override of the global setting, respect it if (savedInstanceState != null) mUseCompactView = savedInstanceState.getBoolean(getString(R.string.key_use_compact_list), mUseCompactView); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(getString(R.string.key_use_compact_list), mUseCompactView); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_transactions_list, container, false); ButterKnife.bind(this, view); mRecyclerView.setHasFixedSize(true); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2); mRecyclerView.setLayoutManager(gridLayoutManager); } else { LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLayoutManager); } mRecyclerView.setEmptyView(view.findViewById(R.id.empty_view)); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ActionBar aBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); aBar.setDisplayShowTitleEnabled(false); aBar.setDisplayHomeAsUpEnabled(true); mTransactionRecyclerAdapter = new TransactionRecyclerAdapter(null); mRecyclerView.setAdapter(mTransactionRecyclerAdapter); setHasOptionsMenu(true); } /** * Refresh the list with transactions from account with ID <code>accountId</code> * @param accountUID GUID of account to load transactions from */ @Override public void refresh(String accountUID){ mAccountUID = accountUID; refresh(); } /** * Reload the list of transactions and recompute account balances */ @Override public void refresh(){ getLoaderManager().restartLoader(0, null, this); } @Override public void onResume() { super.onResume(); ((TransactionsActivity)getActivity()).updateNavigationSelection(); refresh(); } public void onListItemClick(long id) { Intent intent = new Intent(getActivity(), TransactionDetailActivity.class); intent.putExtra(UxArgument.SELECTED_TRANSACTION_UID, mTransactionsDbAdapter.getUID(id)); intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); startActivity(intent); // mTransactionEditListener.editTransaction(mTransactionsDbAdapter.getUID(id)); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.transactions_list_actions, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem item = menu.findItem(R.id.menu_compact_trn_view); item.setChecked(mUseCompactView); item.setEnabled(GnuCashApplication.isDoubleEntryEnabled()); //always compact for single-entry } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_compact_trn_view: item.setChecked(!item.isChecked()); mUseCompactView = !mUseCompactView; refresh(); return true; default: return super.onOptionsItemSelected(item); } } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { Log.d(LOG_TAG, "Creating transactions loader"); return new TransactionsCursorLoader(getActivity(), mAccountUID); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { Log.d(LOG_TAG, "Transactions loader finished. Swapping in cursor"); mTransactionRecyclerAdapter.swapCursor(cursor); mTransactionRecyclerAdapter.notifyDataSetChanged(); } @Override public void onLoaderReset(Loader<Cursor> loader) { Log.d(LOG_TAG, "Resetting transactions loader"); mTransactionRecyclerAdapter.swapCursor(null); } /** * {@link DatabaseCursorLoader} for loading transactions asynchronously from the database * @author Ngewi Fet <[email protected]> */ protected static class TransactionsCursorLoader extends DatabaseCursorLoader { private String accountUID; public TransactionsCursorLoader(Context context, String accountUID) { super(context); this.accountUID = accountUID; } @Override public Cursor loadInBackground() { mDatabaseAdapter = TransactionsDbAdapter.getInstance(); Cursor c = ((TransactionsDbAdapter) mDatabaseAdapter).fetchAllTransactionsForAccount(accountUID); if (c != null) registerContentObserver(c); return c; } } public class TransactionRecyclerAdapter extends CursorRecyclerAdapter<TransactionRecyclerAdapter.ViewHolder>{ public static final int ITEM_TYPE_COMPACT = 0x111; public static final int ITEM_TYPE_FULL = 0x100; public TransactionRecyclerAdapter(Cursor cursor) { super(cursor); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { int layoutRes = viewType == ITEM_TYPE_COMPACT ? R.layout.cardview_compact_transaction : R.layout.cardview_transaction; View v = LayoutInflater.from(parent.getContext()) .inflate(layoutRes, parent, false); return new ViewHolder(v); } @Override public int getItemViewType(int position) { return mUseCompactView ? ITEM_TYPE_COMPACT : ITEM_TYPE_FULL; } @Override public void onBindViewHolderCursor(ViewHolder holder, Cursor cursor) { holder.transactionId = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry._ID)); String description = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry.COLUMN_DESCRIPTION)); holder.primaryText.setText(description); final String transactionUID = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry.COLUMN_UID)); Money amount = mTransactionsDbAdapter.getBalance(transactionUID, mAccountUID); TransactionsActivity.displayBalance(holder.transactionAmount, amount); long dateMillis = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.TransactionEntry.COLUMN_TIMESTAMP)); String dateText = TransactionsActivity.getPrettyDateFormat(getActivity(), dateMillis); final long id = holder.transactionId; holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onListItemClick(id); } }); if (mUseCompactView) { holder.secondaryText.setText(dateText); } else { List<Split> splits = SplitsDbAdapter.getInstance().getSplitsForTransaction(transactionUID); String text = ""; if (splits.size() == 2 && splits.get(0).isPairOf(splits.get(1))) { for (Split split : splits) { if (!split.getAccountUID().equals(mAccountUID)) { text = AccountsDbAdapter.getInstance().getFullyQualifiedAccountName(split.getAccountUID()); break; } } } if (splits.size() > 2) { text = splits.size() + " splits"; } holder.secondaryText.setText(text); holder.transactionDate.setText(dateText); holder.editTransaction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), FormActivity.class); intent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name()); intent.putExtra(UxArgument.SELECTED_TRANSACTION_UID, transactionUID); intent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, mAccountUID); startActivity(intent); } }); } } public class ViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener{ @BindView(R.id.primary_text) public TextView primaryText; @BindView(R.id.secondary_text) public TextView secondaryText; @BindView(R.id.transaction_amount) public TextView transactionAmount; @BindView(R.id.options_menu) public ImageView optionsMenu; //these views are not used in the compact view, hence the nullability @Nullable @BindView(R.id.transaction_date) public TextView transactionDate; @Nullable @BindView(R.id.edit_transaction) public ImageView editTransaction; long transactionId; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); primaryText.setTextSize(18); optionsMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(getActivity(), v); popup.setOnMenuItemClickListener(ViewHolder.this); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.transactions_context_menu, popup.getMenu()); popup.show(); } }); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.context_menu_delete: BackupManager.backupActiveBook(); mTransactionsDbAdapter.deleteRecord(transactionId); WidgetConfigurationActivity.updateAllWidgets(getActivity()); refresh(); return true; case R.id.context_menu_duplicate_transaction: Transaction transaction = mTransactionsDbAdapter.getRecord(transactionId); Transaction duplicate = new Transaction(transaction, true); duplicate.setTime(System.currentTimeMillis()); mTransactionsDbAdapter.addRecord(duplicate, DatabaseAdapter.UpdateMethod.insert); refresh(); return true; case R.id.context_menu_move_transaction: long[] ids = new long[]{transactionId}; BulkMoveDialogFragment fragment = BulkMoveDialogFragment.newInstance(ids, mAccountUID); fragment.show(getActivity().getSupportFragmentManager(), "bulk_move_transactions"); fragment.setTargetFragment(TransactionsListFragment.this, 0); return true; default: return false; } } } } }
13,647
34.26615
124
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/dialog/BulkMoveDialogFragment.java
/* * Copyright (c) 2012 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction.dialog; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import org.gnucash.android.R; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.ui.common.Refreshable; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity; import org.gnucash.android.ui.transaction.TransactionsActivity; import org.gnucash.android.util.QualifiedAccountNameCursorAdapter; /** * Dialog fragment for moving transactions from one account to another * @author Ngewi Fet <[email protected]> */ public class BulkMoveDialogFragment extends DialogFragment { /** * Spinner for selecting the account to move the transactions to */ Spinner mDestinationAccountSpinner; /** * Dialog positive button. Ok to moving the transactions */ Button mOkButton; /** * Cancel button */ Button mCancelButton; /** * Record IDs of the transactions to be moved */ long[] mTransactionIds = null; /** * GUID of account from which to move the transactions */ String mOriginAccountUID = null; /** * Create new instance of the bulk move dialog * @param transactionIds Array of transaction database record IDs * @param originAccountUID Account from which to move the transactions * @return BulkMoveDialogFragment instance with arguments set */ public static BulkMoveDialogFragment newInstance(long[] transactionIds, String originAccountUID){ Bundle args = new Bundle(); args.putLongArray(UxArgument.SELECTED_TRANSACTION_IDS, transactionIds); args.putString(UxArgument.ORIGIN_ACCOUNT_UID, originAccountUID); BulkMoveDialogFragment bulkMoveDialogFragment = new BulkMoveDialogFragment(); bulkMoveDialogFragment.setArguments(args); return bulkMoveDialogFragment; } /** * Creates the view and retrieves references to the dialog elements */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.dialog_bulk_move, container, false); mDestinationAccountSpinner = (Spinner) v.findViewById(R.id.accounts_list_spinner); mOkButton = (Button) v.findViewById(R.id.btn_save); mOkButton.setText(R.string.btn_move); mCancelButton = (Button) v.findViewById(R.id.btn_cancel); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getDialog().getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); Bundle args = getArguments(); mTransactionIds = args.getLongArray(UxArgument.SELECTED_TRANSACTION_IDS); mOriginAccountUID = args.getString(UxArgument.ORIGIN_ACCOUNT_UID); String title = getActivity().getString(R.string.title_move_transactions, mTransactionIds.length); getDialog().setTitle(title); AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); String conditions = "(" + DatabaseSchema.AccountEntry.COLUMN_UID + " != ? AND " + DatabaseSchema.AccountEntry.COLUMN_CURRENCY + " = ? AND " + DatabaseSchema.AccountEntry.COLUMN_HIDDEN + " = 0 AND " + DatabaseSchema.AccountEntry.COLUMN_PLACEHOLDER + " = 0" + ")"; Cursor cursor = accountsDbAdapter.fetchAccountsOrderedByFullName(conditions, new String[]{mOriginAccountUID, accountsDbAdapter.getCurrencyCode(mOriginAccountUID)}); SimpleCursorAdapter mCursorAdapter = new QualifiedAccountNameCursorAdapter(getActivity(), cursor); mDestinationAccountSpinner.setAdapter(mCursorAdapter); setListeners(); } /** * Binds click listeners for the dialog buttons */ protected void setListeners(){ mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); mOkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mTransactionIds == null) { dismiss(); } long dstAccountId = mDestinationAccountSpinner.getSelectedItemId(); String dstAccountUID = AccountsDbAdapter.getInstance().getUID(dstAccountId); TransactionsDbAdapter trxnAdapter = TransactionsDbAdapter.getInstance(); if (!trxnAdapter.getAccountCurrencyCode(dstAccountUID).equals(trxnAdapter.getAccountCurrencyCode(mOriginAccountUID))) { Toast.makeText(getActivity(), R.string.toast_incompatible_currency, Toast.LENGTH_LONG).show(); return; } String srcAccountUID = ((TransactionsActivity) getActivity()).getCurrentAccountUID(); for (long trxnId : mTransactionIds) { trxnAdapter.moveTransaction(trxnAdapter.getUID(trxnId), srcAccountUID, dstAccountUID); } WidgetConfigurationActivity.updateAllWidgets(getActivity()); ((Refreshable) getTargetFragment()).refresh(); dismiss(); } }); } }
6,164
34.028409
123
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/dialog/TransactionsDeleteConfirmationDialogFragment.java
/* * Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]> * Copyright (c) 2014 Yongxin Wang <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction.dialog; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Transaction; import org.gnucash.android.ui.common.Refreshable; import org.gnucash.android.ui.common.UxArgument; import org.gnucash.android.ui.homescreen.WidgetConfigurationActivity; import org.gnucash.android.util.BackupManager; import java.util.ArrayList; import java.util.List; /** * Displays a delete confirmation dialog for transactions * If the transaction ID parameter is 0, then all transactions will be deleted * @author Ngewi Fet <[email protected]> * */ public class TransactionsDeleteConfirmationDialogFragment extends DialogFragment { public static TransactionsDeleteConfirmationDialogFragment newInstance(int title, long id) { TransactionsDeleteConfirmationDialogFragment frag = new TransactionsDeleteConfirmationDialogFragment(); Bundle args = new Bundle(); args.putInt("title", title); args.putLong(UxArgument.SELECTED_TRANSACTION_IDS, id); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int title = getArguments().getInt("title"); final long rowId = getArguments().getLong(UxArgument.SELECTED_TRANSACTION_IDS); int message = rowId == 0 ? R.string.msg_delete_all_transactions_confirmation : R.string.msg_delete_transaction_confirmation; return new AlertDialog.Builder(getActivity()) .setIcon(android.R.drawable.ic_delete) .setTitle(title).setMessage(message) .setPositiveButton(R.string.alert_dialog_ok_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); if (rowId == 0) { BackupManager.backupActiveBook(); //create backup before deleting everything List<Transaction> openingBalances = new ArrayList<Transaction>(); boolean preserveOpeningBalances = GnuCashApplication.shouldSaveOpeningBalances(false); if (preserveOpeningBalances) { openingBalances = AccountsDbAdapter.getInstance().getAllOpeningBalanceTransactions(); } transactionsDbAdapter.deleteAllRecords(); if (preserveOpeningBalances) { transactionsDbAdapter.bulkAddRecords(openingBalances, DatabaseAdapter.UpdateMethod.insert); } } else { transactionsDbAdapter.deleteRecord(rowId); } if (getTargetFragment() instanceof Refreshable) { ((Refreshable) getTargetFragment()).refresh(); } WidgetConfigurationActivity.updateAllWidgets(getActivity()); } } ) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismiss(); } } ) .create(); } }
4,826
47.27
132
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/transaction/dialog/TransferFundsDialogFragment.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.transaction.dialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v4.app.DialogFragment; import android.text.Editable; import android.text.TextWatcher; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import org.gnucash.android.R; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.db.adapter.PricesDbAdapter; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Price; import org.gnucash.android.ui.transaction.OnTransferFundsListener; import org.gnucash.android.ui.transaction.TransactionsActivity; import org.gnucash.android.util.AmountParser; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import butterknife.BindView; import butterknife.ButterKnife; /** * Dialog fragment for handling currency conversions when inputting transactions. * <p>This is used whenever a multi-currency transaction is being created.</p> */ public class TransferFundsDialogFragment extends DialogFragment { @BindView(R.id.from_currency) TextView mFromCurrencyLabel; @BindView(R.id.to_currency) TextView mToCurrencyLabel; @BindView(R.id.target_currency) TextView mConvertedAmountCurrencyLabel; @BindView(R.id.amount_to_convert) TextView mStartAmountLabel; @BindView(R.id.input_exchange_rate) EditText mExchangeRateInput; @BindView(R.id.input_converted_amount) EditText mConvertedAmountInput; @BindView(R.id.btn_fetch_exchange_rate) Button mFetchExchangeRateButton; @BindView(R.id.radio_exchange_rate) RadioButton mExchangeRateRadioButton; @BindView(R.id.radio_converted_amount) RadioButton mConvertedAmountRadioButton; @BindView(R.id.label_exchange_rate_example) TextView mSampleExchangeRate; @BindView(R.id.exchange_rate_text_input_layout) TextInputLayout mExchangeRateInputLayout; @BindView(R.id.converted_amount_text_input_layout) TextInputLayout mConvertedAmountInputLayout; @BindView(R.id.btn_save) Button mSaveButton; @BindView(R.id.btn_cancel) Button mCancelButton; Money mOriginAmount; private Commodity mTargetCommodity; Money mConvertedAmount; OnTransferFundsListener mOnTransferFundsListener; public static TransferFundsDialogFragment getInstance(Money transactionAmount, String targetCurrencyCode, OnTransferFundsListener transferFundsListener){ TransferFundsDialogFragment fragment = new TransferFundsDialogFragment(); fragment.mOriginAmount = transactionAmount; fragment.mTargetCommodity = CommoditiesDbAdapter.getInstance().getCommodity(targetCurrencyCode); fragment.mOnTransferFundsListener = transferFundsListener; return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_transfer_funds, container, false); ButterKnife.bind(this, view); TransactionsActivity.displayBalance(mStartAmountLabel, mOriginAmount); String fromCurrencyCode = mOriginAmount.getCommodity().getCurrencyCode(); mFromCurrencyLabel.setText(fromCurrencyCode); mToCurrencyLabel.setText(mTargetCommodity.getCurrencyCode()); mConvertedAmountCurrencyLabel.setText(mTargetCommodity.getCurrencyCode()); mSampleExchangeRate.setText(String.format(getString(R.string.sample_exchange_rate), fromCurrencyCode, mTargetCommodity.getCurrencyCode())); final InputLayoutErrorClearer textChangeListener = new InputLayoutErrorClearer(); CommoditiesDbAdapter commoditiesDbAdapter = CommoditiesDbAdapter.getInstance(); String commodityUID = commoditiesDbAdapter.getCommodityUID(fromCurrencyCode); String currencyUID = mTargetCommodity.getUID(); PricesDbAdapter pricesDbAdapter = PricesDbAdapter.getInstance(); Pair<Long, Long> pricePair = pricesDbAdapter.getPrice(commodityUID, currencyUID); if (pricePair.first > 0 && pricePair.second > 0) { // a valid price exists Price price = new Price(commodityUID, currencyUID); price.setValueNum(pricePair.first); price.setValueDenom(pricePair.second); mExchangeRateInput.setText(price.toString()); BigDecimal numerator = new BigDecimal(pricePair.first); BigDecimal denominator = new BigDecimal(pricePair.second); // convertedAmount = mOriginAmount * numerator / denominator BigDecimal convertedAmount = mOriginAmount.asBigDecimal().multiply(numerator) .divide(denominator, mTargetCommodity.getSmallestFractionDigits(), BigDecimal.ROUND_HALF_EVEN); DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(); mConvertedAmountInput.setText(formatter.format(convertedAmount)); } mExchangeRateInput.addTextChangedListener(textChangeListener); mConvertedAmountInput.addTextChangedListener(textChangeListener); mConvertedAmountRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mConvertedAmountInput.setEnabled(isChecked); mConvertedAmountInputLayout.setErrorEnabled(isChecked); mExchangeRateRadioButton.setChecked(!isChecked); if (isChecked) { mConvertedAmountInput.requestFocus(); } } }); mExchangeRateRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mExchangeRateInput.setEnabled(isChecked); mExchangeRateInputLayout.setErrorEnabled(isChecked); mFetchExchangeRateButton.setEnabled(isChecked); mConvertedAmountRadioButton.setChecked(!isChecked); if (isChecked) { mExchangeRateInput.requestFocus(); } } }); mFetchExchangeRateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO: Pull the exchange rate for the currency here } }); mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); mSaveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { transferFunds(); } }); return view; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.setTitle(R.string.title_transfer_funds); return dialog; } /** * Converts the currency amount with the given exchange rate and saves the price to the db */ private void transferFunds() { Price price = null; String originCommodityUID = mOriginAmount.getCommodity().getUID(); String targetCommodityUID = mTargetCommodity.getUID(); if (mExchangeRateRadioButton.isChecked()) { BigDecimal rate; try { rate = AmountParser.parse(mExchangeRateInput.getText().toString()); } catch (ParseException e) { mExchangeRateInputLayout.setError(getString(R.string.error_invalid_exchange_rate)); return; } price = new Price(originCommodityUID, targetCommodityUID, rate); mConvertedAmount = mOriginAmount.multiply(rate).withCurrency(mTargetCommodity); } if (mConvertedAmountRadioButton.isChecked()) { BigDecimal amount; try { amount = AmountParser.parse(mConvertedAmountInput.getText().toString()); } catch (ParseException e) { mConvertedAmountInputLayout.setError(getString(R.string.error_invalid_amount)); return; } mConvertedAmount = new Money(amount, mTargetCommodity); price = new Price(originCommodityUID, targetCommodityUID); // fractions cannot be exactly represented by BigDecimal. price.setValueNum(mConvertedAmount.getNumerator() * mOriginAmount.getDenominator()); price.setValueDenom(mOriginAmount.getNumerator() * mConvertedAmount.getDenominator()); } price.setSource(Price.SOURCE_USER); PricesDbAdapter.getInstance().addRecord(price); if (mOnTransferFundsListener != null) mOnTransferFundsListener.transferComplete(mConvertedAmount); dismiss(); } /** * Hides the error message from mConvertedAmountInputLayout and mExchangeRateInputLayout * when the user edits their content. */ private class InputLayoutErrorClearer implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { mConvertedAmountInputLayout.setErrorEnabled(false); mExchangeRateInputLayout.setErrorEnabled(false); } } }
10,918
41.486381
111
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/AccountBalanceTask.java
/* * Copyright (c) 2014 Ngewi Fet <[email protected]> * Copyright (c) 2014 Yongxin Wang <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util; import android.os.AsyncTask; import android.util.Log; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.model.Money; import org.gnucash.android.ui.transaction.TransactionsActivity; import java.lang.ref.WeakReference; /** * An asynchronous task for computing the account balance of an account. * This is done asynchronously because in cases of deeply nested accounts, * it can take some time and would block the UI thread otherwise. */ public class AccountBalanceTask extends AsyncTask<String, Void, Money> { public static final String LOG_TAG = AccountBalanceTask.class.getName(); private final WeakReference<TextView> accountBalanceTextViewReference; private final AccountsDbAdapter accountsDbAdapter; public AccountBalanceTask(TextView balanceTextView){ accountBalanceTextViewReference = new WeakReference<>(balanceTextView); accountsDbAdapter = AccountsDbAdapter.getInstance(); } @Override protected Money doInBackground(String... params) { //if the view for which we are doing this job is dead, kill the job as well if (accountBalanceTextViewReference.get() == null){ cancel(true); return Money.getZeroInstance(); } Money balance = Money.getZeroInstance(); try { balance = accountsDbAdapter.getAccountBalance(params[0], -1, -1); } catch (Exception ex) { Log.e(LOG_TAG, "Error computing account balance ", ex); Crashlytics.logException(ex); } return balance; } @Override protected void onPostExecute(Money balance) { if (accountBalanceTextViewReference.get() != null && balance != null){ final TextView balanceTextView = accountBalanceTextViewReference.get(); if (balanceTextView != null){ TransactionsActivity.displayBalance(balanceTextView, balance); } } } }
2,750
35.197368
83
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/CursorRecyclerAdapter.java
/* * The MIT License (MIT) * * Copyright (c) 2014 Matthieu Harlé * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.gnucash.android.ui.util; import android.database.ContentObserver; import android.database.Cursor; import android.database.DataSetObserver; import android.os.Handler; import android.support.v7.widget.RecyclerView; import android.widget.Filter; import android.widget.FilterQueryProvider; import android.widget.Filterable; /** * Provide a {@link android.support.v7.widget.RecyclerView.Adapter} implementation with cursor * support. * * Child classes only need to implement {@link #onCreateViewHolder(android.view.ViewGroup, int)} and * {@link #onBindViewHolderCursor(android.support.v7.widget.RecyclerView.ViewHolder, android.database.Cursor)}. * * This class does not implement deprecated fields and methods from CursorAdapter! Incidentally, * only {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER} is available, so the * flag is implied, and only the Adapter behavior using this flag has been ported. * * @param <VH> {@inheritDoc} * * @see android.support.v7.widget.RecyclerView.Adapter * @see android.widget.CursorAdapter * @see android.widget.Filterable * @see CursorFilter.CursorFilterClient */ public abstract class CursorRecyclerAdapter<VH extends android.support.v7.widget.RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> implements Filterable, CursorFilter.CursorFilterClient { private boolean mDataValid; private int mRowIDColumn; private Cursor mCursor; private ChangeObserver mChangeObserver; private DataSetObserver mDataSetObserver; private CursorFilter mCursorFilter; private FilterQueryProvider mFilterQueryProvider; public CursorRecyclerAdapter( Cursor cursor) { init(cursor); } void init(Cursor c) { boolean cursorPresent = c != null; mCursor = c; mDataValid = cursorPresent; mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1; mChangeObserver = new ChangeObserver(); mDataSetObserver = new MyDataSetObserver(); if (cursorPresent) { if (mChangeObserver != null) c.registerContentObserver(mChangeObserver); if (mDataSetObserver != null) c.registerDataSetObserver(mDataSetObserver); } } /** * This method will move the Cursor to the correct position and call * {@link #onBindViewHolderCursor(android.support.v7.widget.RecyclerView.ViewHolder, * android.database.Cursor)}. * * @param holder {@inheritDoc} * @param i {@inheritDoc} */ @Override public void onBindViewHolder(VH holder, int i){ if (!mDataValid) { throw new IllegalStateException("this should only be called when the cursor is valid"); } if (!mCursor.moveToPosition(i)) { throw new IllegalStateException("couldn't move cursor to position " + i); } onBindViewHolderCursor(holder, mCursor); } /** * See {@link android.widget.CursorAdapter#bindView(android.view.View, android.content.Context, * android.database.Cursor)}, * {@link #onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder, int)} * * @param holder View holder. * @param cursor The cursor from which to get the data. The cursor is already * moved to the correct position. */ public abstract void onBindViewHolderCursor(VH holder, Cursor cursor); @Override public int getItemCount() { if (mDataValid && mCursor != null) { return mCursor.getCount(); } else { return 0; } } /** * @see android.widget.ListAdapter#getItemId(int) */ @Override public long getItemId(int position) { if (mDataValid && mCursor != null) { if (mCursor.moveToPosition(position)) { return mCursor.getLong(mRowIDColumn); } else { return 0; } } else { return 0; } } public Cursor getCursor(){ return mCursor; } /** * Change the underlying cursor to a new cursor. If there is an existing cursor it will be * closed. * * @param cursor The new cursor to be used */ public void changeCursor(Cursor cursor) { Cursor old = swapCursor(cursor); if (old != null) { old.close(); } } /** * Swap in a new Cursor, returning the old Cursor. Unlike * {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em> * closed. * * @param newCursor The new cursor to be used. * @return Returns the previously set Cursor, or null if there was not one. * If the given new Cursor is the same instance is the previously set * Cursor, null is also returned. */ public Cursor swapCursor(Cursor newCursor) { if (newCursor == mCursor) { return null; } Cursor oldCursor = mCursor; if (oldCursor != null) { if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver); if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver); } mCursor = newCursor; if (newCursor != null) { if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver); if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver); mRowIDColumn = newCursor.getColumnIndexOrThrow("_id"); mDataValid = true; // notify the observers about the new cursor notifyDataSetChanged(); } else { mRowIDColumn = -1; mDataValid = false; // notify the observers about the lack of a data set // notifyDataSetInvalidated(); notifyItemRangeRemoved(0, getItemCount()); } return oldCursor; } /** * <p>Converts the cursor into a CharSequence. Subclasses should override this * method to convert their results. The default implementation returns an * empty String for null values or the default String representation of * the value.</p> * * @param cursor the cursor to convert to a CharSequence * @return a CharSequence representing the value */ public CharSequence convertToString(Cursor cursor) { return cursor == null ? "" : cursor.toString(); } /** * Runs a query with the specified constraint. This query is requested * by the filter attached to this adapter. * * The query is provided by a * {@link android.widget.FilterQueryProvider}. * If no provider is specified, the current cursor is not filtered and returned. * * After this method returns the resulting cursor is passed to {@link #changeCursor(Cursor)} * and the previous cursor is closed. * * This method is always executed on a background thread, not on the * application's main thread (or UI thread.) * * Contract: when constraint is null or empty, the original results, * prior to any filtering, must be returned. * * @param constraint the constraint with which the query must be filtered * * @return a Cursor representing the results of the new query * * @see #getFilter() * @see #getFilterQueryProvider() * @see #setFilterQueryProvider(android.widget.FilterQueryProvider) */ public Cursor runQueryOnBackgroundThread(CharSequence constraint) { if (mFilterQueryProvider != null) { return mFilterQueryProvider.runQuery(constraint); } return mCursor; } public Filter getFilter() { if (mCursorFilter == null) { mCursorFilter = new CursorFilter(this); } return mCursorFilter; } /** * Returns the query filter provider used for filtering. When the * provider is null, no filtering occurs. * * @return the current filter query provider or null if it does not exist * * @see #setFilterQueryProvider(android.widget.FilterQueryProvider) * @see #runQueryOnBackgroundThread(CharSequence) */ public FilterQueryProvider getFilterQueryProvider() { return mFilterQueryProvider; } /** * Sets the query filter provider used to filter the current Cursor. * The provider's * {@link android.widget.FilterQueryProvider#runQuery(CharSequence)} * method is invoked when filtering is requested by a client of * this adapter. * * @param filterQueryProvider the filter query provider or null to remove it * * @see #getFilterQueryProvider() * @see #runQueryOnBackgroundThread(CharSequence) */ public void setFilterQueryProvider(FilterQueryProvider filterQueryProvider) { mFilterQueryProvider = filterQueryProvider; } /** * Called when the {@link ContentObserver} on the cursor receives a change notification. * Can be implemented by sub-class. * * @see ContentObserver#onChange(boolean) */ protected void onContentChanged() { notifyDataSetChanged(); } private class ChangeObserver extends ContentObserver { public ChangeObserver() { super(new Handler()); } @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange) { onContentChanged(); } } private class MyDataSetObserver extends DataSetObserver { @Override public void onChanged() { mDataValid = true; notifyDataSetChanged(); } @Override public void onInvalidated() { mDataValid = false; // notifyDataSetInvalidated(); notifyItemRangeRemoved(0, getItemCount()); } } /** * <p>The CursorFilter delegates most of the work to the CursorAdapter. * Subclasses should override these delegate methods to run the queries * and convert the results into String that can be used by auto-completion * widgets.</p> */ } class CursorFilter extends Filter { CursorFilterClient mClient; interface CursorFilterClient { CharSequence convertToString(Cursor cursor); Cursor runQueryOnBackgroundThread(CharSequence constraint); Cursor getCursor(); void changeCursor(Cursor cursor); } CursorFilter(CursorFilterClient client) { mClient = client; } @Override public CharSequence convertResultToString(Object resultValue) { return mClient.convertToString((Cursor) resultValue); } @Override protected FilterResults performFiltering(CharSequence constraint) { Cursor cursor = mClient.runQueryOnBackgroundThread(constraint); FilterResults results = new FilterResults(); if (cursor != null) { results.count = cursor.getCount(); results.values = cursor; } else { results.count = 0; results.values = null; } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { Cursor oldCursor = mClient.getCursor(); if (results.values != null && results.values != oldCursor) { mClient.changeCursor((Cursor) results.values); } } }
12,618
33.290761
111
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/RecurrenceParser.java
/* * Copyright (c) 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.format.Time; import com.codetroopers.betterpickers.recurrencepicker.EventRecurrence; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; /** * Parses {@link EventRecurrence}s to generate * {@link org.gnucash.android.model.ScheduledAction}s * * @author Ngewi Fet <[email protected]> */ public class RecurrenceParser { //these are time millisecond constants which are used for scheduled actions. //they may not be calendar accurate, but they serve the purpose for scheduling approximate time for background service execution public static final long SECOND_MILLIS = 1000; public static final long MINUTE_MILLIS = 60 * SECOND_MILLIS; public static final long HOUR_MILLIS = 60 * MINUTE_MILLIS; public static final long DAY_MILLIS = 24 * HOUR_MILLIS; public static final long WEEK_MILLIS = 7 * DAY_MILLIS; public static final long MONTH_MILLIS = 30 * DAY_MILLIS; public static final long YEAR_MILLIS = 12 * MONTH_MILLIS; /** * Parse an {@link EventRecurrence} into a {@link Recurrence} object * @param eventRecurrence EventRecurrence object * @return Recurrence object */ public static Recurrence parse(EventRecurrence eventRecurrence){ if (eventRecurrence == null) return null; PeriodType periodType; switch(eventRecurrence.freq){ case EventRecurrence.HOURLY: periodType = PeriodType.HOUR; break; case EventRecurrence.DAILY: periodType = PeriodType.DAY; break; case EventRecurrence.WEEKLY: periodType = PeriodType.WEEK; break; case EventRecurrence.MONTHLY: periodType = PeriodType.MONTH; break; case EventRecurrence.YEARLY: periodType = PeriodType.YEAR; break; default: periodType = PeriodType.MONTH; break; } int interval = eventRecurrence.interval == 0 ? 1 : eventRecurrence.interval; //bug from betterpickers library sometimes returns 0 as the interval Recurrence recurrence = new Recurrence(periodType); recurrence.setMultiplier(interval); parseEndTime(eventRecurrence, recurrence); recurrence.setByDays(parseByDay(eventRecurrence.byday)); if (eventRecurrence.startDate != null) recurrence.setPeriodStart(new Timestamp(eventRecurrence.startDate.toMillis(false))); return recurrence; } /** * Parses the end time from an EventRecurrence object and sets it to the <code>scheduledEvent</code>. * The end time is specified in the dialog either by number of occurrences or a date. * @param eventRecurrence Event recurrence pattern obtained from dialog * @param recurrence Recurrence event to set the end period to */ private static void parseEndTime(EventRecurrence eventRecurrence, Recurrence recurrence) { if (eventRecurrence.until != null && eventRecurrence.until.length() > 0) { Time endTime = new Time(); endTime.parse(eventRecurrence.until); recurrence.setPeriodEnd(new Timestamp(endTime.toMillis(false))); } else if (eventRecurrence.count > 0){ recurrence.setPeriodEnd(eventRecurrence.count); } } /** * Parses an array of byDay values to return a list of days of week * constants from {@link Calendar}. * * <p>Currently only supports byDay values for weeks.</p> * * @param byDay Array of byDay values * @return list of days of week constants from Calendar. */ private static @NonNull List<Integer> parseByDay(@Nullable int[] byDay) { if (byDay == null) { return Collections.emptyList(); } List<Integer> byDaysList = new ArrayList<>(byDay.length); for (int day : byDay) { byDaysList.add(EventRecurrence.day2CalendarDay(day)); } return byDaysList; } }
5,001
35.779412
153
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/RecurrenceViewClickListener.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.text.format.Time; import android.view.View; import com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment; import com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment.OnRecurrenceSetListener; /** * Shows the recurrence dialog when the recurrence view is clicked */ public class RecurrenceViewClickListener implements View.OnClickListener{ private static final String FRAGMENT_TAG_RECURRENCE_PICKER = "recurrence_picker"; AppCompatActivity mActivity; String mRecurrenceRule; OnRecurrenceSetListener mRecurrenceSetListener; public RecurrenceViewClickListener(AppCompatActivity activity, String recurrenceRule, OnRecurrenceSetListener recurrenceSetListener){ this.mActivity = activity; this.mRecurrenceRule = recurrenceRule; this.mRecurrenceSetListener = recurrenceSetListener; } @Override public void onClick(View v) { FragmentManager fm = mActivity.getSupportFragmentManager(); Bundle b = new Bundle(); Time t = new Time(); t.setToNow(); b.putLong(RecurrencePickerDialogFragment.BUNDLE_START_TIME_MILLIS, t.toMillis(false)); b.putString(RecurrencePickerDialogFragment.BUNDLE_TIME_ZONE, t.timezone); // may be more efficient to serialize and pass in EventRecurrence b.putString(RecurrencePickerDialogFragment.BUNDLE_RRULE, mRecurrenceRule); RecurrencePickerDialogFragment rpd = (RecurrencePickerDialogFragment) fm.findFragmentByTag( FRAGMENT_TAG_RECURRENCE_PICKER); if (rpd != null) { rpd.dismiss(); } rpd = new RecurrencePickerDialogFragment(); rpd.setArguments(b); rpd.setOnRecurrenceSetListener(mRecurrenceSetListener); rpd.show(fm, FRAGMENT_TAG_RECURRENCE_PICKER); } }
2,670
38.279412
110
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/ScrollingFABBehavior.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util; import android.content.Context; import android.os.Build; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import org.gnucash.android.R; /** * Behavior for floating action button when list is scrolled * Courtesy: https://mzgreen.github.io/2015/06/23/How-to-hideshow-Toolbar-when-list-is-scrolling(part3)/ */ public class ScrollingFABBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> { private int toolbarHeight; public ScrollingFABBehavior(Context context, AttributeSet attrs) { super(context, attrs); this.toolbarHeight = getToolbarHeight(context); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) { return dependency instanceof AppBarLayout; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) { if (dependency instanceof AppBarLayout) { CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams(); int fabBottomMargin = lp.bottomMargin; int distanceToScroll = fab.getHeight() + fabBottomMargin; float ratio = (float) dependency.getY() / (float) toolbarHeight; fab.setTranslationY(-distanceToScroll * ratio); } return true; } private int getToolbarHeight(Context context){ TypedValue tv = new TypedValue(); int actionBarHeight = android.support.v7.appcompat.R.attr.actionBarSize; if (context.getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics()); } return actionBarHeight; } }
2,681
36.25
112
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/TaskDelegate.java
/* * Copyright (c) 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util; /** * Interface for delegates which can be used to execute functions when an AsyncTask is complete * @see org.gnucash.android.importer.ImportAsyncTask * @author Ngewi Fet <[email protected]> */ public interface TaskDelegate { /** * Function to execute on completion of task */ public void onTaskComplete(); }
986
30.83871
95
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/dialog/DatePickerDialogFragment.java
/* * Copyright (c) 2012 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.dialog; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import java.util.Calendar; import java.util.GregorianCalendar; /** * Fragment for displaying a date picker dialog * @author Ngewi Fet <[email protected]> * */ public class DatePickerDialogFragment extends DialogFragment { /** * Listener to notify of events in the dialog */ private OnDateSetListener mDateSetListener; /** * Date selected in the dialog or to which the dialog is initialized */ private Calendar mDate; /** * Default Constructor * Is required for when the device is rotated while the dialog is open. * If this constructor is not present, the app will crash */ public DatePickerDialogFragment() { //nothing to see here, move along } /** * Overloaded constructor * @param callback Listener to notify when the date is set and the dialog is closed * @param dateMillis Time in milliseconds to which to initialize the dialog */ public static DatePickerDialogFragment newInstance(OnDateSetListener callback, long dateMillis) { DatePickerDialogFragment datePickerDialogFragment = new DatePickerDialogFragment(); datePickerDialogFragment.mDateSetListener = callback; if (dateMillis > 0){ datePickerDialogFragment.mDate = new GregorianCalendar(); datePickerDialogFragment.mDate.setTimeInMillis(dateMillis); } return datePickerDialogFragment; } /** * Creates and returns an Android {@link DatePickerDialog} */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Calendar cal = mDate == null ? Calendar.getInstance() : mDate; return new DatePickerDialog(getActivity(), mDateSetListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); } }
2,550
30.109756
98
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/dialog/DateRangePickerDialogFragment.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.dialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.squareup.timessquare.CalendarPickerView; import org.gnucash.android.R; import org.joda.time.LocalDate; import java.util.Calendar; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Dialog for picking date ranges in terms of months. * It is currently used for selecting ranges for reports * @author Ngewi Fet <[email protected]> */ public class DateRangePickerDialogFragment extends DialogFragment{ @BindView(R.id.calendar_view) CalendarPickerView mCalendarPickerView; @BindView(R.id.btn_save) Button mDoneButton; @BindView(R.id.btn_cancel) Button mCancelButton; private Date mStartRange = LocalDate.now().minusMonths(1).toDate(); private Date mEndRange = LocalDate.now().toDate(); private OnDateRangeSetListener mDateRangeSetListener; private static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000; public static DateRangePickerDialogFragment newInstance(OnDateRangeSetListener dateRangeSetListener){ DateRangePickerDialogFragment fragment = new DateRangePickerDialogFragment(); fragment.mDateRangeSetListener = dateRangeSetListener; return fragment; } public static DateRangePickerDialogFragment newInstance(long startDate, long endDate, OnDateRangeSetListener dateRangeSetListener){ DateRangePickerDialogFragment fragment = new DateRangePickerDialogFragment(); fragment.mStartRange = new Date(startDate); fragment.mEndRange = new Date(endDate); fragment.mDateRangeSetListener = dateRangeSetListener; return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_date_range_picker, container, false); ButterKnife.bind(this, view); Calendar nextYear = Calendar.getInstance(); nextYear.add(Calendar.YEAR, 1); Date today = new Date(); mCalendarPickerView.init(mStartRange, mEndRange) .inMode(CalendarPickerView.SelectionMode.RANGE) .withSelectedDate(today); mDoneButton.setText(R.string.done_label); mDoneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Date> selectedDates = mCalendarPickerView.getSelectedDates(); Date startDate = selectedDates.get(0); // If only one day is selected (no interval) start and end should be the same (the selected one) Date endDate = selectedDates.size() > 1 ? selectedDates.get(selectedDates.size() - 1) : new Date(startDate.getTime()); // CaledarPicker returns the start of the selected day but we want all transactions of that day to be included. // Therefore we have to add 24 hours to the endDate. endDate.setTime(endDate.getTime() + ONE_DAY_IN_MILLIS); mDateRangeSetListener.onDateRangeSet(startDate, endDate); dismiss(); } }); mCancelButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { dismiss(); } }); return view; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.setTitle("Pick time range"); return dialog; } public interface OnDateRangeSetListener { void onDateRangeSet(Date startDate, Date endDate); } }
4,727
37.129032
134
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/dialog/TimePickerDialogFragment.java
/* * Copyright (c) 2012 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.dialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.os.Bundle; import android.support.v4.app.DialogFragment; import java.util.Calendar; import java.util.GregorianCalendar; /** * Fragment for displaying a time choose dialog * @author Ngewi Fet <[email protected]> * */ public class TimePickerDialogFragment extends DialogFragment { /** * Listener to notify when the time is set */ private OnTimeSetListener mListener = null; /** * Current time to initialize the dialog to, or to notify the listener of. */ Calendar mCurrentTime = null; /** * Default constructor * Is required for when the device is rotated while the dialog is open. * If this constructor is not present, the app will crash */ public TimePickerDialogFragment() { // nothing to see here, move along } /** * Overloaded constructor * @param listener {@link OnTimeSetListener} to notify when the time has been set * @param timeMillis Time in milliseconds to initialize the dialog to */ public static TimePickerDialogFragment newInstance(OnTimeSetListener listener, long timeMillis){ TimePickerDialogFragment timePickerDialogFragment = new TimePickerDialogFragment(); timePickerDialogFragment.mListener = listener; if (timeMillis > 0){ timePickerDialogFragment.mCurrentTime = new GregorianCalendar(); timePickerDialogFragment.mCurrentTime.setTimeInMillis(timeMillis); } return timePickerDialogFragment; } /** * Creates and returns an Android {@link TimePickerDialog} */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Calendar cal = mCurrentTime == null ? Calendar.getInstance() : mCurrentTime; int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), mListener, hour, minute, true); } }
2,597
29.564706
97
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/widget/CalculatorEditText.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.widget; import android.content.Context; import android.content.res.TypedArray; import android.inputmethodservice.KeyboardView; import android.os.Build; import android.support.annotation.Nullable; import android.support.annotation.XmlRes; import android.support.v7.widget.AppCompatEditText; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.crashlytics.android.Crashlytics; import net.objecthunter.exp4j.Expression; import net.objecthunter.exp4j.ExpressionBuilder; import org.gnucash.android.R; import org.gnucash.android.model.Commodity; import org.gnucash.android.ui.common.FormActivity; import org.gnucash.android.util.AmountParser; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; /** * A custom EditText which supports computations and uses a custom calculator keyboard. * <p>After the view is inflated, make sure to call {@link #bindListeners(KeyboardView)} * with the view from your layout where the calculator keyboard should be displayed.</p> * @author Ngewi Fet <[email protected]> */ public class CalculatorEditText extends AppCompatEditText { private CalculatorKeyboard mCalculatorKeyboard; private Commodity mCommodity = Commodity.DEFAULT_COMMODITY; private Context mContext; /** * Flag which is set if the contents of this view have been modified */ private boolean isContentModified = false; private int mCalculatorKeysLayout; private KeyboardView mCalculatorKeyboardView; public CalculatorEditText(Context context) { super(context); this.mContext = context; } public CalculatorEditText(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public CalculatorEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } /** * Overloaded constructor * Reads any attributes which are specified in XML and applies them * @param context Activity context * @param attrs View attributes */ private void init(Context context, AttributeSet attrs){ this.mContext = context; TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CalculatorEditText, 0, 0); try { mCalculatorKeysLayout = a.getResourceId(R.styleable.CalculatorEditText_keyboardKeysLayout, R.xml.calculator_keyboard); } finally { a.recycle(); } addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { isContentModified = true; } }); } public void bindListeners(CalculatorKeyboard calculatorKeyboard){ mCalculatorKeyboard = calculatorKeyboard; mContext = calculatorKeyboard.getContext(); setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { setSelection(getText().length()); mCalculatorKeyboard.showCustomKeyboard(v); } else { mCalculatorKeyboard.hideCustomKeyboard(); evaluate(); } } }); setOnClickListener(new OnClickListener() { // NOTE By setting the on click listener we can show the custom keyboard again, // by tapping on an edit box that already had focus (but that had the keyboard hidden). @Override public void onClick(View v) { mCalculatorKeyboard.showCustomKeyboard(v); } }); // Disable spell check (hex strings look like words to Android) setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); // Disable system keyboard appearing on long-press, but for some reason, this prevents the text selection from working. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setShowSoftInputOnFocus(false); } else { setRawInputType(InputType.TYPE_CLASS_NUMBER); } // Although this handler doesn't make sense, if removed, the standard keyboard // shows up in addition to the calculator one when the EditText gets a touch event. setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // XXX: Use dispatchTouchEvent()? onTouchEvent(event); return false; } }); ((FormActivity)mContext).setOnBackListener(mCalculatorKeyboard); } /** * Initializes listeners on the EditText */ public void bindListeners(KeyboardView keyboardView){ bindListeners(new CalculatorKeyboard(mContext, keyboardView, mCalculatorKeysLayout)); } /** * Returns the calculator keyboard instantiated by this EditText * @return CalculatorKeyboard */ public CalculatorKeyboard getCalculatorKeyboard(){ return mCalculatorKeyboard; } /** * Returns the view Id of the keyboard view * @return Keyboard view */ public KeyboardView getCalculatorKeyboardView() { return mCalculatorKeyboardView; } /** * Set the keyboard view used for displaying the keyboard * @param calculatorKeyboardView Calculator keyboard view */ public void setCalculatorKeyboardView(KeyboardView calculatorKeyboardView) { this.mCalculatorKeyboardView = calculatorKeyboardView; bindListeners(calculatorKeyboardView); } /** * Returns the XML resource ID describing the calculator keys layout * @return XML resource ID */ public @XmlRes int getCalculatorKeysLayout() { return mCalculatorKeysLayout; } /** * Sets the XML resource describing the layout of the calculator keys * @param calculatorKeysLayout XML resource ID */ public void setCalculatorKeysLayout(@XmlRes int calculatorKeysLayout) { this.mCalculatorKeysLayout = calculatorKeysLayout; bindListeners(mCalculatorKeyboardView); } /** * Sets the calculator keyboard to use for this EditText * @param keyboard Properly intialized calculator keyobard */ public void setCalculatorKeyboard(CalculatorKeyboard keyboard){ this.mCalculatorKeyboard = keyboard; } /** * Returns the currency used for computations * @return ISO 4217 currency */ public Commodity getCommodity() { return mCommodity; } /** * Sets the commodity to use for calculations * The commodity determines the number of decimal places used * @param commodity ISO 4217 currency */ public void setCommodity(Commodity commodity) { this.mCommodity = commodity; } /** * Evaluates the arithmetic expression in the EditText and sets the text property * @return Result of arithmetic evaluation which is same as text displayed in EditText */ public String evaluate(){ String amountString = getCleanString(); if (amountString.isEmpty()) return amountString; ExpressionBuilder expressionBuilder = new ExpressionBuilder(amountString); Expression expression; try { expression = expressionBuilder.build(); } catch (RuntimeException e) { setError(getContext().getString(R.string.label_error_invalid_expression)); String msg = "Invalid expression: " + amountString; Log.e(this.getClass().getSimpleName(), msg); Crashlytics.log(msg); return ""; } if (expression != null && expression.validate().isValid()) { BigDecimal result = new BigDecimal(expression.evaluate()); setValue(result); } else { setError(getContext().getString(R.string.label_error_invalid_expression)); Log.w(VIEW_LOG_TAG, "Expression is null or invalid: " + expression); } return getText().toString(); } /** * Evaluates the expression in the text and returns true if the result is valid * @return @{code true} if the input is valid, {@code false} otherwise */ public boolean isInputValid(){ String text = evaluate(); return !text.isEmpty() && getError() == null; } /** * Returns the amount string formatted as a decimal in Locale.US and trimmed. * This also converts decimal operators from other locales into a period (.) * @return String with the amount in the EditText or empty string if there is no input */ public String getCleanString(){ return getText().toString().replaceAll(",", ".").trim(); } /** * Returns true if the content of this view has been modified * @return {@code true} if content has changed, {@code false} otherwise */ public boolean isInputModified(){ return this.isContentModified; } /** * Returns the value of the amount in the edit text or null if the field is empty. * Performs an evaluation of the expression first * @return BigDecimal value */ public @Nullable BigDecimal getValue(){ evaluate(); try { //catch any exceptions in the conversion e.g. if a string with only "-" is entered return AmountParser.parse(getText().toString()); } catch (ParseException e){ String msg = "Error parsing amount string " + getText() + " from CalculatorEditText"; Log.i(getClass().getSimpleName(), msg, e); return null; } } /** * Set the text to the value of {@code amount} formatted according to the locale. * <p>The number of decimal places are determined by the currency set to the view, and the * decimal separator is determined by the device locale. There are no thousandths separators.</p> * @param amount BigDecimal amount */ public void setValue(BigDecimal amount){ BigDecimal newAmount = amount.setScale(mCommodity.getSmallestFractionDigits(), BigDecimal.ROUND_HALF_EVEN); DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault()); formatter.setMinimumFractionDigits(0); formatter.setMaximumFractionDigits(mCommodity.getSmallestFractionDigits()); formatter.setGroupingUsed(false); String resultString = formatter.format(newAmount.doubleValue()); super.setText(resultString); setSelection(resultString.length()); } }
11,907
34.335312
130
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/widget/CalculatorKeyboard.java
/** * Copyright 2013 Maarten Pennings extended by SimplicityApks * * Modified by: * Copyright 2015 Àlex Magaz Graça <[email protected]> * Copyright 2015 Ngewi Fet <[email protected]> * * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * <p/> * If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. */ package org.gnucash.android.ui.util.widget; import android.app.Activity; import android.content.Context; import android.inputmethodservice.Keyboard; import android.inputmethodservice.KeyboardView; import android.inputmethodservice.KeyboardView.OnKeyboardActionListener; import android.provider.Settings; import android.support.annotation.XmlRes; import android.text.Editable; import android.view.HapticFeedbackConstants; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import java.text.DecimalFormatSymbols; /** * When an activity hosts a keyboardView, this class allows several EditText's to register for it. * * Known issues: * - It's not possible to select text. * - When in landscape, the EditText is covered by the keyboard. * - No i18n. * * @author Maarten Pennings, extended by SimplicityApks * @date 2012 December 23 * * @author Àlex Magaz Graça <[email protected]> * @author Ngewi Fet <[email protected]> * */ public class CalculatorKeyboard { public static final int KEY_CODE_DECIMAL_SEPARATOR = 46; /** A link to the KeyboardView that is used to render this CalculatorKeyboard. */ private KeyboardView mKeyboardView; private Context mContext; private boolean hapticFeedback; public static final String LOCALE_DECIMAL_SEPARATOR = Character.toString(DecimalFormatSymbols.getInstance().getDecimalSeparator()); private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() { @Override public void onKey(int primaryCode, int[] keyCodes) { View focusCurrent = ((Activity)mContext).getWindow().getCurrentFocus(); assert focusCurrent != null; /* if (focusCurrent == null || focusCurrent.getClass() != EditText.class) return; */ if (!(focusCurrent instanceof CalculatorEditText)){ return; } CalculatorEditText calculatorEditText = (CalculatorEditText) focusCurrent; Editable editable = calculatorEditText.getText(); int start = calculatorEditText.getSelectionStart(); int end = calculatorEditText.getSelectionEnd(); // FIXME: use replace() down // delete the selection, if chars are selected: if (end > start) editable.delete(start, end); switch (primaryCode) { case KEY_CODE_DECIMAL_SEPARATOR: editable.insert(start, LOCALE_DECIMAL_SEPARATOR); break; case 42: case 43: case 45: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: //editable.replace(start, end, Character.toString((char) primaryCode)); // XXX: could be android:keyOutputText attribute used instead of this? editable.insert(start, Character.toString((char) primaryCode)); break; case -5: int deleteStart = start > 0 ? start - 1: 0; editable.delete(deleteStart, end); break; case 1003: // C[lear] editable.clear(); break; case 1001: calculatorEditText.evaluate(); break; case 1002: calculatorEditText.focusSearch(View.FOCUS_DOWN).requestFocus(); hideCustomKeyboard(); break; } } @Override public void onPress(int primaryCode) { if (isHapticFeedbackEnabled() && primaryCode != 0) mKeyboardView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); } @Override public void onRelease(int primaryCode) { } @Override public void onText(CharSequence text) { } @Override public void swipeLeft() { } @Override public void swipeRight() { } @Override public void swipeDown() { } @Override public void swipeUp() { } }; /** * Returns true if the haptic feedback is enabled. * * @return true if the haptic feedback is enabled in the system settings. */ private boolean isHapticFeedbackEnabled() { int value = Settings.System.getInt(mKeyboardView.getContext().getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 0); return value != 0; } /** * Create a custom keyboard, that uses the KeyboardView (with resource id <var>viewid</var>) of the <var>host</var> activity, * and load the keyboard layout from xml file <var>layoutid</var> (see {@link Keyboard} for description). * Note that the <var>host</var> activity must have a <var>KeyboardView</var> in its layout (typically aligned with the bottom of the activity). * Note that the keyboard layout xml file may include key codes for navigation; see the constants in this class for their values. * * @param context Context within with the calculator is created * @param keyboardView KeyboardView in the layout * @param keyboardLayoutResId The id of the xml file containing the keyboard layout. */ public CalculatorKeyboard(Context context, KeyboardView keyboardView, @XmlRes int keyboardLayoutResId) { mContext = context; mKeyboardView = keyboardView; Keyboard keyboard = new Keyboard(mContext, keyboardLayoutResId); for (Keyboard.Key key : keyboard.getKeys()) { if (key.codes[0] == KEY_CODE_DECIMAL_SEPARATOR){ key.label = LOCALE_DECIMAL_SEPARATOR; break; } } mKeyboardView.setKeyboard(keyboard); mKeyboardView.setPreviewEnabled(false); // NOTE Do not show the preview balloons mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener); // Hide the standard keyboard initially ((Activity)mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } /** Returns whether the CalculatorKeyboard is visible. */ public boolean isCustomKeyboardVisible() { return mKeyboardView.getVisibility() == View.VISIBLE; } /** Make the CalculatorKeyboard visible, and hide the system keyboard for view v. */ public void showCustomKeyboard(View v) { if (v != null) ((InputMethodManager) mContext.getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0); mKeyboardView.setVisibility(View.VISIBLE); mKeyboardView.setEnabled(true); } /** Make the CalculatorKeyboard invisible. */ public void hideCustomKeyboard() { mKeyboardView.setVisibility(View.GONE); mKeyboardView.setEnabled(false); } public boolean onBackPressed() { if (isCustomKeyboardVisible()) { hideCustomKeyboard(); return true; } else return false; } /** * Returns the context of this keyboard * @return Context */ public Context getContext(){ return mContext; } }
8,400
37.013575
148
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/widget/CheckableLinearLayout.java
/* * Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.widget; import android.annotation.TargetApi; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.LinearLayout; /** * An implementation of {@link android.widget.LinearLayout} which implements the {@link android.widget.Checkable} interface. * This layout keeps track of its checked state or alternatively queries its child views for any {@link View} which is Checkable. * If there is a Checkable child view, then that child view determines the check state of the whole layout. * * <p>This layout is designed for use with ListViews with a choice mode other than {@link android.widget.ListView#CHOICE_MODE_NONE}. * Android requires the parent view of the row items in the list to be checkable in order to take advantage of the APIs</p> * @author Ngewi Fet <[email protected]> */ public class CheckableLinearLayout extends LinearLayout implements Checkable { /** * Checkable view which holds the checked state of the linear layout */ private Checkable mCheckable = null; /** * Fallback check state of the linear layout if there is no {@link Checkable} amongst its child views. */ private boolean mIsChecked = false; public CheckableLinearLayout(Context context) { super(context); } public CheckableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Find any instance of a {@link Checkable} amongst the children of the linear layout and store a reference to it */ @Override protected void onFinishInflate() { super.onFinishInflate(); //this prevents us from opening transactions since simply clicking on the item checks the checkable and //activates action mode. // mCheckable = findCheckableView(this); } /** * Iterates through the child views of <code>parent</code> to an arbitrary depth and returns the first * {@link Checkable} view found * @param parent ViewGroup in which to search for Checkable children * @return First {@link Checkable} child view of parent found */ private Checkable findCheckableView(ViewGroup parent){ for (int i = 0; i < parent.getChildCount(); i++) { View childView = parent.getChildAt(i); if (childView instanceof Checkable) return (Checkable)childView; if (childView instanceof ViewGroup){ Checkable checkable = findCheckableView((ViewGroup)childView); if (checkable != null){ return checkable; } } } return null; } @Override public void setChecked(boolean b) { if (mCheckable != null){ mCheckable.setChecked(b); } else { mIsChecked = b; } refreshDrawableState(); } @Override public boolean isChecked() { return (mCheckable != null) ? mCheckable.isChecked() : mIsChecked; } @Override public void toggle() { if (mCheckable != null){ mCheckable.toggle(); } else { mIsChecked = !mIsChecked; } refreshDrawableState(); } }
4,089
33.661017
132
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/widget/EmptyRecyclerView.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.widget; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; /** * Code from https://gist.github.com/AnirudhaAgashe/61e523dadbaaf064b9a0 * @author Anirudha Agashe <[email protected]> */ public class EmptyRecyclerView extends RecyclerView { @Nullable View emptyView; public EmptyRecyclerView(Context context) { super(context); } public EmptyRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); } public EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } void checkIfEmpty() { if (emptyView != null && getAdapter() != null) { emptyView.setVisibility(getAdapter().getItemCount() > 0 ? GONE : VISIBLE); } } final @NonNull AdapterDataObserver observer = new AdapterDataObserver() { @Override public void onChanged() { super.onChanged(); checkIfEmpty(); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); checkIfEmpty(); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { super.onItemRangeRemoved(positionStart, itemCount); checkIfEmpty(); } }; @Override public void setAdapter(@Nullable Adapter adapter) { final Adapter oldAdapter = getAdapter(); if (oldAdapter != null) { oldAdapter.unregisterAdapterDataObserver(observer); } super.setAdapter(adapter); if (adapter != null) { adapter.registerAdapterDataObserver(observer); } } public void setEmptyView(@Nullable View emptyView) { this.emptyView = emptyView; checkIfEmpty(); } }
2,674
31.228916
92
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/widget/ReselectSpinner.java
package org.gnucash.android.ui.util.widget; import android.content.Context; import android.support.v7.widget.AppCompatSpinner; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import org.gnucash.android.ui.export.ExportFormFragment; /** * Spinner which fires OnItemSelectedListener even when an item is reselected. * Normal Spinners only fire item selected notifications when the selected item changes. * <p>This is used in {@code ReportsActivity} for the time range and in the {@link ExportFormFragment}</p> * <p>It could happen that the selected item is fired twice especially if the item is the first in the list. * The Android system does this internally. In order to capture the first one, check whether the view parameter * of {@link android.widget.AdapterView.OnItemSelectedListener#onItemSelected(AdapterView, View, int, long)} is null. * That would represent the first call during initialization of the views. This call can be ignored. * See {@link ExportFormFragment#bindViewListeners()} for an example * </p> */ public class ReselectSpinner extends AppCompatSpinner { public ReselectSpinner(Context context) { super(context); } public ReselectSpinner(Context context, AttributeSet attrs) { super(context, attrs); } public ReselectSpinner(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void setSelection(int position) { boolean sameSelected = getSelectedItemPosition() == position; super.setSelection(position); if (sameSelected){ OnItemSelectedListener listener = getOnItemSelectedListener(); if (listener != null) listener.onItemSelected(this, getSelectedView(), position, getSelectedItemId()); } } }
1,873
39.73913
117
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/util/widget/TransactionTypeSwitch.java
/* * Copyright (c) 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.util.widget; import android.content.Context; import android.support.v4.content.ContextCompat; import android.support.v7.widget.SwitchCompat; import android.util.AttributeSet; import android.widget.CompoundButton; import android.widget.TextView; import org.gnucash.android.R; import org.gnucash.android.model.AccountType; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * A special type of {@link android.widget.ToggleButton} which displays the appropriate CREDIT/DEBIT labels for the * different account types. * @author Ngewi Fet <[email protected]> */ public class TransactionTypeSwitch extends SwitchCompat { private AccountType mAccountType = AccountType.EXPENSE; List<OnCheckedChangeListener> mOnCheckedChangeListeners = new ArrayList<>(); public TransactionTypeSwitch(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public TransactionTypeSwitch(Context context, AttributeSet attrs) { super(context, attrs); } public TransactionTypeSwitch(Context context) { super(context); } public void setAccountType(AccountType accountType){ this.mAccountType = accountType; Context context = getContext().getApplicationContext(); switch (mAccountType) { case CASH: setTextOn(context.getString(R.string.label_spend)); setTextOff(context.getString(R.string.label_receive)); break; case BANK: setTextOn(context.getString(R.string.label_withdrawal)); setTextOff(context.getString(R.string.label_deposit)); break; case CREDIT: setTextOn(context.getString(R.string.label_payment)); setTextOff(context.getString(R.string.label_charge)); break; case ASSET: case EQUITY: case LIABILITY: setTextOn(context.getString(R.string.label_decrease)); setTextOff(context.getString(R.string.label_increase)); break; case INCOME: setTextOn(context.getString(R.string.label_charge)); setTextOff(context.getString(R.string.label_income)); break; case EXPENSE: setTextOn(context.getString(R.string.label_rebate)); setTextOff(context.getString(R.string.label_expense)); break; case PAYABLE: setTextOn(context.getString(R.string.label_payment)); setTextOff(context.getString(R.string.label_bill)); break; case RECEIVABLE: setTextOn(context.getString(R.string.label_payment)); setTextOff(context.getString(R.string.label_invoice)); break; case STOCK: case MUTUAL: setTextOn(context.getString(R.string.label_buy)); setTextOff(context.getString(R.string.label_sell)); break; case CURRENCY: case ROOT: default: setTextOn(context.getString(R.string.label_debit)); setTextOff(context.getString(R.string.label_credit)); break; } setText(isChecked() ? getTextOn() : getTextOff()); invalidate(); } /** * Set a checked change listener to monitor the amount view and currency views and update the display (color & balance accordingly) * @param amoutView Amount string {@link android.widget.EditText} * @param currencyTextView Currency symbol text view */ public void setAmountFormattingListener(CalculatorEditText amoutView, TextView currencyTextView){ setOnCheckedChangeListener(new OnTypeChangedListener(amoutView, currencyTextView)); } /** * Add listeners to be notified when the checked status changes * @param checkedChangeListener Checked change listener */ public void addOnCheckedChangeListener(OnCheckedChangeListener checkedChangeListener){ mOnCheckedChangeListeners.add(checkedChangeListener); } /** * Toggles the button checked based on the movement caused by the transaction type for the specified account * @param transactionType {@link org.gnucash.android.model.TransactionType} of the split */ public void setChecked(TransactionType transactionType){ setChecked(Transaction.shouldDecreaseBalance(mAccountType, transactionType)); } /** * Returns the account type associated with this button * @return Type of account */ public AccountType getAccountType(){ return mAccountType; } public TransactionType getTransactionType(){ if (mAccountType.hasDebitNormalBalance()){ return isChecked() ? TransactionType.CREDIT : TransactionType.DEBIT; } else { return isChecked() ? TransactionType.DEBIT : TransactionType.CREDIT; } } private class OnTypeChangedListener implements OnCheckedChangeListener{ private CalculatorEditText mAmountEditText; private TextView mCurrencyTextView; /** * Constructor with the amount view * @param amountEditText EditText displaying the amount value * @param currencyTextView Currency symbol text view */ public OnTypeChangedListener(CalculatorEditText amountEditText, TextView currencyTextView){ this.mAmountEditText = amountEditText; this.mCurrencyTextView = currencyTextView; } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { setText(isChecked ? getTextOn() : getTextOff()); if (isChecked){ int red = ContextCompat.getColor(getContext(), R.color.debit_red); TransactionTypeSwitch.this.setTextColor(red); mAmountEditText.setTextColor(red); mCurrencyTextView.setTextColor(red); } else { int green = ContextCompat.getColor(getContext(), R.color.credit_green); TransactionTypeSwitch.this.setTextColor(green); mAmountEditText.setTextColor(green); mCurrencyTextView.setTextColor(green); } BigDecimal amount = mAmountEditText.getValue(); if (amount != null){ if ((isChecked && amount.signum() > 0) //we switched to debit but the amount is +ve || (!isChecked && amount.signum() < 0)){ //credit but amount is -ve mAmountEditText.setValue(amount.negate()); } } for (OnCheckedChangeListener listener : mOnCheckedChangeListeners) { listener.onCheckedChanged(compoundButton, isChecked); } } } }
7,706
38.523077
135
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/wizard/CurrencySelectFragment.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.wizard; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.tech.freak.wizardpager.ui.PageFragmentCallbacks; import org.gnucash.android.R; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.util.CommoditiesCursorAdapter; import butterknife.ButterKnife; /** * Displays a list of all currencies in the database and allows selection of one * <p>This fragment is intended for use with the first run wizard</p> * @author Ngewi Fet <[email protected]> * @see CurrencySelectPage * @see FirstRunWizardActivity * @see FirstRunWizardModel */ public class CurrencySelectFragment extends ListFragment { private CurrencySelectPage mPage; private PageFragmentCallbacks mCallbacks; private CommoditiesDbAdapter mCommoditiesDbAdapter; String mPageKey; public static CurrencySelectFragment newInstance(String key){ CurrencySelectFragment fragment = new CurrencySelectFragment(); fragment.mPageKey = key; return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_wizard_currency_select_page, container, false); ButterKnife.bind(this, view); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPage = (CurrencySelectPage) mCallbacks.onGetPage(mPageKey); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); CommoditiesCursorAdapter commoditiesCursorAdapter = new CommoditiesCursorAdapter(getActivity(), R.layout.list_item_commodity); setListAdapter(commoditiesCursorAdapter); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); mCommoditiesDbAdapter = CommoditiesDbAdapter.getInstance(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof PageFragmentCallbacks)) { throw new ClassCastException("Activity must implement PageFragmentCallbacks"); } mCallbacks = (PageFragmentCallbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); String currencyCode = mCommoditiesDbAdapter.getCurrencyCode(mCommoditiesDbAdapter.getUID(id)); mPage.getData().putString(CurrencySelectPage.CURRENCY_CODE_DATA_KEY, currencyCode); } }
3,539
31.777778
134
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/wizard/CurrencySelectPage.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.wizard; import android.support.v4.app.Fragment; import android.text.TextUtils; import com.tech.freak.wizardpager.model.ModelCallbacks; import com.tech.freak.wizardpager.model.Page; import com.tech.freak.wizardpager.model.ReviewItem; import java.util.ArrayList; /** * Page displaying all the commodities in the database */ public class CurrencySelectPage extends Page{ public static final String CURRENCY_CODE_DATA_KEY = "currency_code_data_key"; protected CurrencySelectPage(ModelCallbacks callbacks, String title) { super(callbacks, title); } @Override public Fragment createFragment() { return CurrencySelectFragment.newInstance(getKey()); } @Override public void getReviewItems(ArrayList<ReviewItem> arrayList) { arrayList.add(new ReviewItem(getTitle(), mData.getString(CURRENCY_CODE_DATA_KEY), getKey())); } @Override public boolean isCompleted() { return !TextUtils.isEmpty(mData.getString(CURRENCY_CODE_DATA_KEY)); } }
1,664
29.833333
101
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/wizard/FirstRunWizardActivity.java
/* * Copyright 2012 Roman Nurik * Copyright 2012 Ngewi Fet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.wizard; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.tech.freak.wizardpager.model.AbstractWizardModel; import com.tech.freak.wizardpager.model.ModelCallbacks; import com.tech.freak.wizardpager.model.Page; import com.tech.freak.wizardpager.model.ReviewItem; import com.tech.freak.wizardpager.ui.PageFragmentCallbacks; import com.tech.freak.wizardpager.ui.ReviewFragment; import com.tech.freak.wizardpager.ui.StepPagerStrip; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.ui.account.AccountsActivity; import org.gnucash.android.ui.util.TaskDelegate; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Activity for managing the wizard displayed upon first run of the application */ public class FirstRunWizardActivity extends AppCompatActivity implements PageFragmentCallbacks, ReviewFragment.Callbacks, ModelCallbacks { @BindView(R.id.pager) ViewPager mPager; private MyPagerAdapter mPagerAdapter; private boolean mEditingAfterReview; private AbstractWizardModel mWizardModel; private boolean mConsumePageSelectedEvent; @BindView(R.id.btn_save) AppCompatButton mNextButton; @BindView(R.id.btn_cancel) Button mPrevButton; @BindView(R.id.strip) StepPagerStrip mStepPagerStrip; private List<Page> mCurrentPageSequence; private String mAccountOptions; private String mCurrencyCode; public void onCreate(Bundle savedInstanceState) { // we need to construct the wizard model before we call super.onCreate, because it's used in // onGetPage (which is indirectly called through super.onCreate if savedInstanceState is not // null) mWizardModel = createWizardModel(savedInstanceState); super.onCreate(savedInstanceState); setContentView(R.layout.activity_first_run_wizard); ButterKnife.bind(this); setTitle(getString(R.string.title_setup_gnucash)); mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager()); mPager.setAdapter(mPagerAdapter); mStepPagerStrip .setOnPageSelectedListener(new StepPagerStrip.OnPageSelectedListener() { @Override public void onPageStripSelected(int position) { position = Math.min(mPagerAdapter.getCount() - 1, position); if (mPager.getCurrentItem() != position) { mPager.setCurrentItem(position); } } }); mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { mStepPagerStrip.setCurrentPage(position); if (mConsumePageSelectedEvent) { mConsumePageSelectedEvent = false; return; } mEditingAfterReview = false; updateBottomBar(); } }); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mPager.getCurrentItem() == mCurrentPageSequence.size()) { ArrayList<ReviewItem> reviewItems = new ArrayList<>(); for (Page page : mCurrentPageSequence) { page.getReviewItems(reviewItems); } mCurrencyCode = GnuCashApplication.getDefaultCurrencyCode(); mAccountOptions = getString(R.string.wizard_option_let_me_handle_it); //default value, do nothing String feedbackOption = getString(R.string.wizard_option_disable_crash_reports); for (ReviewItem reviewItem : reviewItems) { String title = reviewItem.getTitle(); if (title.equals(getString(R.string.wizard_title_default_currency))){ mCurrencyCode = reviewItem.getDisplayValue(); } else if (title.equals(getString(R.string.wizard_title_select_currency))){ mCurrencyCode = reviewItem.getDisplayValue(); } else if (title.equals(getString(R.string.wizard_title_account_setup))){ mAccountOptions = reviewItem.getDisplayValue(); } else if (title.equals(getString(R.string.wizard_title_feedback_options))){ feedbackOption = reviewItem.getDisplayValue(); } } GnuCashApplication.setDefaultCurrencyCode(mCurrencyCode); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(FirstRunWizardActivity.this); SharedPreferences.Editor preferenceEditor = preferences.edit(); if (feedbackOption.equals(getString(R.string.wizard_option_auto_send_crash_reports))){ preferenceEditor.putBoolean(getString(R.string.key_enable_crashlytics), true); } else { preferenceEditor.putBoolean(getString(R.string.key_enable_crashlytics), false); } preferenceEditor.apply(); createAccountsAndFinish(); } else { if (mEditingAfterReview) { mPager.setCurrentItem(mPagerAdapter.getCount() - 1); } else { mPager.setCurrentItem(mPager.getCurrentItem() + 1); } } } }); mPrevButton.setText(R.string.wizard_btn_back); TypedValue v = new TypedValue(); getTheme().resolveAttribute(android.R.attr.textAppearanceMedium, v, true); mPrevButton.setTextAppearance(this, v.resourceId); mNextButton.setTextAppearance(this, v.resourceId); mPrevButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPager.setCurrentItem(mPager.getCurrentItem() - 1); } }); onPageTreeChanged(); updateBottomBar(); } /** * Create the wizard model for the activity, taking into accoun the savedInstanceState if it * exists (and if it contains a "model" key that we can use). * @param savedInstanceState the instance state available in {{@link #onCreate(Bundle)}} * @return an appropriate wizard model for this activity */ private AbstractWizardModel createWizardModel(Bundle savedInstanceState) { AbstractWizardModel model = new FirstRunWizardModel(this); if (savedInstanceState != null) { Bundle wizardModel = savedInstanceState.getBundle("model"); if (wizardModel != null) { model.load(wizardModel); } } model.registerListener(this); return model; } /** * Create accounts depending on the user preference (import or default set) and finish this activity * <p>This method also removes the first run flag from the application</p> */ private void createAccountsAndFinish() { AccountsActivity.removeFirstRunFlag(); if (mAccountOptions.equals(getString(R.string.wizard_option_create_default_accounts))){ //save the UID of the active book, and then delete it after successful import String bookUID = BooksDbAdapter.getInstance().getActiveBookUID(); AccountsActivity.createDefaultAccounts(mCurrencyCode, FirstRunWizardActivity.this); BooksDbAdapter.getInstance().deleteBook(bookUID); //a default book is usually created finish(); } else if (mAccountOptions.equals(getString(R.string.wizard_option_import_my_accounts))){ AccountsActivity.startXmlFileChooser(this); } else { //user prefers to handle account creation themselves AccountsActivity.start(this); finish(); } } @Override public void onPageTreeChanged() { mCurrentPageSequence = mWizardModel.getCurrentPageSequence(); recalculateCutOffPage(); mStepPagerStrip.setPageCount(mCurrentPageSequence.size() + 1); // + 1 = // review // step mPagerAdapter.notifyDataSetChanged(); updateBottomBar(); } private void updateBottomBar() { int position = mPager.getCurrentItem(); final Resources res = getResources(); if (position == mCurrentPageSequence.size()) { mNextButton.setText(R.string.btn_wizard_finish); mNextButton.setBackgroundDrawable( new ColorDrawable(ContextCompat.getColor(this, R.color.theme_accent))); mNextButton.setTextColor(ContextCompat.getColor(this, android.R.color.white)); } else { mNextButton.setText(mEditingAfterReview ? R.string.review : R.string.btn_wizard_next); mNextButton.setBackgroundDrawable( new ColorDrawable(ContextCompat.getColor(this, android.R.color.transparent))); mNextButton.setTextColor(ContextCompat.getColor(this, R.color.theme_accent)); mNextButton.setEnabled(position != mPagerAdapter.getCutOffPage()); } mPrevButton .setVisibility(position <= 0 ? View.INVISIBLE : View.VISIBLE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case AccountsActivity.REQUEST_PICK_ACCOUNTS_FILE: if (resultCode == Activity.RESULT_OK && data != null) { AccountsActivity.importXmlFileFromIntent(this, data, new TaskDelegate() { @Override public void onTaskComplete() { finish(); } }); } break; } } @Override protected void onDestroy() { super.onDestroy(); mWizardModel.unregisterListener(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle("model", mWizardModel.save()); } @Override public AbstractWizardModel onGetModel() { return mWizardModel; } @Override public void onEditScreenAfterReview(String key) { for (int i = mCurrentPageSequence.size() - 1; i >= 0; i--) { if (mCurrentPageSequence.get(i).getKey().equals(key)) { mConsumePageSelectedEvent = true; mEditingAfterReview = true; mPager.setCurrentItem(i); updateBottomBar(); break; } } } @Override public void onPageDataChanged(Page page) { if (page.isRequired()) { if (recalculateCutOffPage()) { mPagerAdapter.notifyDataSetChanged(); updateBottomBar(); } } } @Override public Page onGetPage(String key) { return mWizardModel.findByKey(key); } private boolean recalculateCutOffPage() { // Cut off the pager adapter at first required page that isn't completed int cutOffPage = mCurrentPageSequence.size() + 1; for (int i = 0; i < mCurrentPageSequence.size(); i++) { Page page = mCurrentPageSequence.get(i); if (page.isRequired() && !page.isCompleted()) { cutOffPage = i; break; } } if (mPagerAdapter.getCutOffPage() != cutOffPage) { mPagerAdapter.setCutOffPage(cutOffPage); return true; } return false; } public class MyPagerAdapter extends FragmentStatePagerAdapter { private int mCutOffPage; private Fragment mPrimaryItem; public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { if (i >= mCurrentPageSequence.size()) { return new ReviewFragment(); } return mCurrentPageSequence.get(i).createFragment(); } @Override public int getItemPosition(Object object) { // TODO: be smarter about this if (object == mPrimaryItem) { // Re-use the current fragment (its position never changes) return POSITION_UNCHANGED; } return POSITION_NONE; } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object); mPrimaryItem = (Fragment) object; } @Override public int getCount() { return Math.min(mCutOffPage + 1, mCurrentPageSequence == null ? 1 : mCurrentPageSequence.size() + 1); } public void setCutOffPage(int cutOffPage) { if (cutOffPage < 0) { cutOffPage = Integer.MAX_VALUE; } mCutOffPage = cutOffPage; } public int getCutOffPage() { return mCutOffPage; } } }
15,084
36.90201
127
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/wizard/FirstRunWizardModel.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.wizard; import android.content.Context; import com.tech.freak.wizardpager.model.AbstractWizardModel; import com.tech.freak.wizardpager.model.BranchPage; import com.tech.freak.wizardpager.model.Page; import com.tech.freak.wizardpager.model.PageList; import com.tech.freak.wizardpager.model.SingleFixedChoicePage; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; /** * Wizard displayed upon first run of the application for setup */ public class FirstRunWizardModel extends AbstractWizardModel { public FirstRunWizardModel(Context context) { super(context); } @Override protected PageList onNewRootPageList() { String defaultCurrencyCode = GnuCashApplication.getDefaultCurrencyCode(); BranchPage defaultCurrencyPage = new BranchPage(this, mContext.getString(R.string.wizard_title_default_currency)); String[] currencies = new String[]{defaultCurrencyCode, "CHF", "EUR", "GBP", "USD"}; Set<String> currencySet = new TreeSet<>(Arrays.asList(currencies)); defaultCurrencyPage.setChoices(currencySet.toArray(new String[currencySet.size()])); defaultCurrencyPage.setRequired(true); defaultCurrencyPage.setValue(defaultCurrencyCode); Page defaultAccountsPage = new SingleFixedChoicePage(this, mContext.getString(R.string.wizard_title_account_setup)) .setChoices(mContext.getString(R.string.wizard_option_create_default_accounts), mContext.getString(R.string.wizard_option_import_my_accounts), mContext.getString(R.string.wizard_option_let_me_handle_it)) .setValue(mContext.getString(R.string.wizard_option_create_default_accounts)) .setRequired(true); for (String currency : currencySet) { defaultCurrencyPage.addBranch(currency, defaultAccountsPage); } defaultCurrencyPage.addBranch(mContext.getString(R.string.wizard_option_currency_other), new CurrencySelectPage(this, mContext.getString(R.string.wizard_title_select_currency)), defaultAccountsPage).setRequired(true); return new PageList( new WelcomePage(this, mContext.getString(R.string.wizard_title_welcome_to_gnucash)), defaultCurrencyPage, new SingleFixedChoicePage(this, mContext.getString(R.string.wizard_title_feedback_options)) .setChoices(mContext.getString(R.string.wizard_option_auto_send_crash_reports), mContext.getString(R.string.wizard_option_disable_crash_reports)) .setRequired(true) ); } }
3,405
43.233766
144
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/wizard/WelcomePage.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.wizard; import android.support.v4.app.Fragment; import com.tech.freak.wizardpager.model.ModelCallbacks; import com.tech.freak.wizardpager.model.Page; import com.tech.freak.wizardpager.model.ReviewItem; import java.util.ArrayList; /** * Welcome page for the first run wizard * @author Ngewi Fet */ public class WelcomePage extends Page { protected WelcomePage(ModelCallbacks callbacks, String title) { super(callbacks, title); } @Override public Fragment createFragment() { return new WelcomePageFragment(); } @Override public void getReviewItems(ArrayList<ReviewItem> arrayList) { //nothing to see here, move along } }
1,333
27.382979
75
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/ui/wizard/WelcomePageFragment.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.wizard; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.gnucash.android.R; /** * Welcome page fragment is the first fragment that will be displayed to the user */ public class WelcomePageFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_wizard_welcome_page, container, false); } }
1,265
31.461538
103
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/AmountParser.java
package org.gnucash.android.util; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; /** * Parses amounts as String into BigDecimal. */ public class AmountParser { /** * Parses {@code amount} and returns it as a BigDecimal. * * @param amount String with the amount to parse. * @return The amount parsed as a BigDecimal. * @throws ParseException if the full string couldn't be parsed as an amount. */ public static BigDecimal parse(String amount) throws ParseException { DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(); formatter.setParseBigDecimal(true); ParsePosition parsePosition = new ParsePosition(0); BigDecimal parsedAmount = (BigDecimal) formatter.parse(amount, parsePosition); // Ensure any mistyping by the user is caught instead of partially parsed if ((parsedAmount == null) || (parsePosition.getIndex() < amount.length())) throw new ParseException("Parse error", parsePosition.getErrorIndex()); return parsedAmount; } }
1,181
35.9375
86
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/BackupJob.java
/* Copyright (c) 2018 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.app.JobIntentService; import android.util.Log; /** * Job to back up books periodically. * * <p>The backups are triggered by an alarm set in * {@link BackupManager#schedulePeriodicBackups(Context)} * (through {@link org.gnucash.android.receivers.PeriodicJobReceiver}).</p> */ public class BackupJob extends JobIntentService { private static final String LOG_TAG = "BackupJob"; private static final int JOB_ID = 1000; public static void enqueueWork(Context context) { Intent intent = new Intent(context, BackupJob.class); enqueueWork(context, BackupJob.class, JOB_ID, intent); } @Override protected void onHandleWork(@NonNull Intent intent) { Log.i(LOG_TAG, "Doing backup of all books."); BackupManager.backupAllBooks(); } }
1,590
32.851064
75
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/BackupManager.java
/* Copyright (c) 2018 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.SystemClock; import android.support.annotation.Nullable; import android.util.Log; import com.crashlytics.android.Crashlytics; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.export.ExportFormat; import org.gnucash.android.export.ExportParams; import org.gnucash.android.export.Exporter; import org.gnucash.android.export.xml.GncXmlExporter; import org.gnucash.android.model.Book; import org.gnucash.android.receivers.PeriodicJobReceiver; import org.gnucash.android.ui.settings.PreferenceActivity; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.zip.GZIPOutputStream; /** * Deals with all backup-related tasks. */ public class BackupManager { private static final String LOG_TAG = "BackupManager"; public static final String KEY_BACKUP_FILE = "book_backup_file_key"; /** * Perform an automatic backup of all books in the database. * This method is run every time the service is executed */ static void backupAllBooks() { BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance(); List<String> bookUIDs = booksDbAdapter.getAllBookUIDs(); Context context = GnuCashApplication.getAppContext(); for (String bookUID : bookUIDs) { String backupFile = getBookBackupFileUri(bookUID); if (backupFile == null){ backupBook(bookUID); continue; } try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(context.getContentResolver().openOutputStream(Uri.parse(backupFile)))){ GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bufferedOutputStream); OutputStreamWriter writer = new OutputStreamWriter(gzipOutputStream); ExportParams params = new ExportParams(ExportFormat.XML); new GncXmlExporter(params).generateExport(writer); writer.close(); } catch (IOException ex) { Log.e(LOG_TAG, "Auto backup failed for book " + bookUID); ex.printStackTrace(); Crashlytics.logException(ex); } } } /** * Backs up the active book to the directory {@link #getBackupFolderPath(String)}. * * @return {@code true} if backup was successful, {@code false} otherwise */ public static boolean backupActiveBook() { return backupBook(BooksDbAdapter.getInstance().getActiveBookUID()); } /** * Backs up the book with UID {@code bookUID} to the directory * {@link #getBackupFolderPath(String)}. * * @param bookUID Unique ID of the book * @return {@code true} if backup was successful, {@code false} otherwise */ public static boolean backupBook(String bookUID){ OutputStream outputStream; try { String backupFile = getBookBackupFileUri(bookUID); if (backupFile != null){ outputStream = GnuCashApplication.getAppContext().getContentResolver().openOutputStream(Uri.parse(backupFile)); } else { //no Uri set by user, use default location on SD card backupFile = getBackupFilePath(bookUID); outputStream = new FileOutputStream(backupFile); } BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bufferedOutputStream); OutputStreamWriter writer = new OutputStreamWriter(gzipOutputStream); ExportParams params = new ExportParams(ExportFormat.XML); new GncXmlExporter(params).generateExport(writer); writer.close(); return true; } catch (IOException | Exporter.ExporterException e) { Crashlytics.logException(e); Log.e("GncXmlExporter", "Error creating XML backup", e); return false; } } /** * Returns the full path of a file to make database backup of the specified book. * Backups are done in XML format and are Gzipped (with ".gnca" extension). * @param bookUID GUID of the book * @return the file path for backups of the database. * @see #getBackupFolderPath(String) */ private static String getBackupFilePath(String bookUID){ Book book = BooksDbAdapter.getInstance().getRecord(bookUID); return getBackupFolderPath(book.getUID()) + Exporter.buildExportFilename(ExportFormat.XML, book.getDisplayName()); } /** * Returns the path to the backups folder for the book with GUID {@code bookUID}. * * <p>Each book has its own backup folder.</p> * * @return Absolute path to backup folder for the book */ private static String getBackupFolderPath(String bookUID){ String baseFolderPath = GnuCashApplication.getAppContext() .getExternalFilesDir(null) .getAbsolutePath(); String path = baseFolderPath + "/" + bookUID + "/backups/"; File file = new File(path); if (!file.exists()) file.mkdirs(); return path; } /** * Return the user-set backup file URI for the book with UID {@code bookUID}. * @param bookUID Unique ID of the book * @return DocumentFile for book backups, or null if the user hasn't set any. */ @Nullable public static String getBookBackupFileUri(String bookUID){ SharedPreferences sharedPreferences = PreferenceActivity.getBookSharedPreferences(bookUID); return sharedPreferences.getString(KEY_BACKUP_FILE, null); } public static List<File> getBackupList(String bookUID) { File[] backupFiles = new File(getBackupFolderPath(bookUID)).listFiles(); Arrays.sort(backupFiles); List<File> backupFilesList = Arrays.asList(backupFiles); Collections.reverse(backupFilesList); return backupFilesList; } public static void schedulePeriodicBackups(Context context) { Log.i(LOG_TAG, "Scheduling backup job"); Intent intent = new Intent(context, PeriodicJobReceiver.class); intent.setAction(PeriodicJobReceiver.ACTION_BACKUP); PendingIntent alarmIntent = PendingIntent.getBroadcast(context,0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES, AlarmManager.INTERVAL_DAY, alarmIntent); } }
7,970
40.087629
127
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/BookUtils.java
package org.gnucash.android.util; import android.support.annotation.NonNull; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.ui.account.AccountsActivity; /** * Utility class for common operations involving books */ public class BookUtils { /** * Activates the book with unique identifer {@code bookUID}, and refreshes the database adapters * @param bookUID GUID of the book to be activated */ public static void activateBook(@NonNull String bookUID){ GnuCashApplication.getBooksDbAdapter().setActive(bookUID); GnuCashApplication.initializeDatabaseAdapters(); } /** * Loads the book with GUID {@code bookUID} and opens the AccountsActivity * @param bookUID GUID of the book to be loaded */ public static void loadBook(@NonNull String bookUID){ activateBook(bookUID); AccountsActivity.start(GnuCashApplication.getAppContext()); } }
954
28.84375
100
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/CommoditiesCursorAdapter.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import android.content.Context; import android.database.Cursor; import android.support.annotation.LayoutRes; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; /** * Cursor adapter for displaying list of commodities. * <p>You should provide the layout and the layout should contain a view with the id {@code android:id/text1}, * which is where the name of the commodity will be displayed</p> * <p>The list is sorted by the currency code (which is also displayed first before the full name)</p> */ public class CommoditiesCursorAdapter extends SimpleCursorAdapter { public CommoditiesCursorAdapter(Context context, @LayoutRes int itemLayoutResource) { super(context, itemLayoutResource, CommoditiesDbAdapter.getInstance().fetchAllRecords(DatabaseSchema.CommodityEntry.COLUMN_MNEMONIC + " ASC"), new String[]{DatabaseSchema.CommodityEntry.COLUMN_FULLNAME}, new int[] {android.R.id.text1}, 0); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setEllipsize(TextUtils.TruncateAt.MIDDLE); String currencyName = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommodityEntry.COLUMN_FULLNAME)); String currencyCode = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.CommodityEntry.COLUMN_MNEMONIC)); textView.setText(currencyCode + " - " + currencyName); } }
2,361
41.178571
124
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/FileUtils.java
package org.gnucash.android.util; import android.support.annotation.NonNull; import android.util.Log; import org.gnucash.android.export.ExportAsyncTask; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Misc methods for dealing with files. */ public final class FileUtils { private static final String LOG_TAG = "FileUtils"; public static void zipFiles(List<String> files, String zipFileName) throws IOException { OutputStream outputStream = new FileOutputStream(zipFileName); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); byte[] buffer = new byte[1024]; for (String fileName : files) { File file = new File(fileName); FileInputStream fileInputStream = new FileInputStream(file); zipOutputStream.putNextEntry(new ZipEntry(file.getName())); int length; while ((length = fileInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, length); } zipOutputStream.closeEntry(); fileInputStream.close(); } zipOutputStream.close(); } /** * Moves a file from <code>src</code> to <code>dst</code> * @param src Absolute path to the source file * @param dst Absolute path to the destination file * @throws IOException if the file could not be moved. */ public static void moveFile(String src, String dst) throws IOException { File srcFile = new File(src); File dstFile = new File(dst); FileChannel inChannel = new FileInputStream(srcFile).getChannel(); FileChannel outChannel = new FileOutputStream(dstFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); outChannel.close(); } srcFile.delete(); } /** * Move file from a location on disk to an outputstream. * The outputstream could be for a URI in the Storage Access Framework * @param src Input file (usually newly exported file) * @param outputStream Output stream to write to * @throws IOException if error occurred while moving the file */ public static void moveFile(@NonNull String src, @NonNull OutputStream outputStream) throws IOException { byte[] buffer = new byte[1024]; int read; try (FileInputStream inputStream = new FileInputStream(src)) { while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } } finally { outputStream.flush(); outputStream.close(); } Log.i(LOG_TAG, "Deleting temp export file: " + src); new File(src).delete(); } }
3,072
34.321839
92
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/PreferencesHelper.java
/* * Copyright (c) 2015 Alceu Rodrigues Neto <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import android.content.Context; import android.util.Log; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.ui.settings.PreferenceActivity; import java.sql.Timestamp; /** * A utility class to deal with Android Preferences in a centralized way. */ public final class PreferencesHelper { /** * Should be not instantiated. */ private PreferencesHelper() {} /** * Tag for logging */ private static final String LOG_TAG = "PreferencesHelper"; /** * Preference key for saving the last export time */ public static final String PREFERENCE_LAST_EXPORT_TIME_KEY = "last_export_time"; /** * Set the last export time in UTC time zone of the currently active Book in the application. * This method calls through to {@link #setLastExportTime(Timestamp, String)} * * @param lastExportTime the last export time to set. * @see #setLastExportTime(Timestamp, String) */ public static void setLastExportTime(Timestamp lastExportTime) { Log.v(LOG_TAG, "Saving last export time for the currently active book"); setLastExportTime(lastExportTime, BooksDbAdapter.getInstance().getActiveBookUID()); } /** * Set the last export time in UTC time zone for a specific book. * This value will be used during export to determine new transactions since the last export * * @param lastExportTime the last export time to set. */ public static void setLastExportTime(Timestamp lastExportTime, String bookUID) { final String utcString = TimestampHelper.getUtcStringFromTimestamp(lastExportTime); Log.d(LOG_TAG, "Storing '" + utcString + "' as lastExportTime in Android Preferences."); GnuCashApplication.getAppContext().getSharedPreferences(bookUID, Context.MODE_PRIVATE) .edit() .putString(PREFERENCE_LAST_EXPORT_TIME_KEY, utcString) .apply(); } /** * Get the time for the last export operation. * * @return A {@link Timestamp} with the time. */ public static Timestamp getLastExportTime() { final String utcString = PreferenceActivity.getActiveBookSharedPreferences() .getString(PREFERENCE_LAST_EXPORT_TIME_KEY, TimestampHelper.getUtcStringFromTimestamp(TimestampHelper.getTimestampFromEpochZero())); Log.d(LOG_TAG, "Retrieving '" + utcString + "' as lastExportTime from Android Preferences."); return TimestampHelper.getTimestampFromUtcString(utcString); } /** * Get the time for the last export operation of a specific book. * * @return A {@link Timestamp} with the time. */ public static Timestamp getLastExportTime(String bookUID) { final String utcString = GnuCashApplication.getAppContext() .getSharedPreferences(bookUID, Context.MODE_PRIVATE) .getString(PREFERENCE_LAST_EXPORT_TIME_KEY, TimestampHelper.getUtcStringFromTimestamp( TimestampHelper.getTimestampFromEpochZero())); Log.d(LOG_TAG, "Retrieving '" + utcString + "' as lastExportTime from Android Preferences."); return TimestampHelper.getTimestampFromUtcString(utcString); } }
4,047
38.686275
112
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/QualifiedAccountNameCursorAdapter.java
/* * Copyright (c) 2013 - 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import android.content.Context; import android.database.Cursor; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.v4.widget.SimpleCursorAdapter; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import org.gnucash.android.R; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; /** * Cursor adapter which looks up the fully qualified account name and returns that instead of just the simple name. * <p>The fully qualified account name includes the parent hierarchy</p> * * @author Ngewi Fet <[email protected]> */ public class QualifiedAccountNameCursorAdapter extends SimpleCursorAdapter { /** * Initialize the Cursor adapter for account names using default spinner views * @param context Application context * @param cursor Cursor to accounts */ public QualifiedAccountNameCursorAdapter(Context context, Cursor cursor) { super(context, android.R.layout.simple_spinner_item, cursor, new String[]{DatabaseSchema.AccountEntry.COLUMN_FULL_NAME}, new int[]{android.R.id.text1}, 0); setDropDownViewResource(R.layout.account_spinner_dropdown_item); } /** * Overloaded constructor. Specifies the view to use for displaying selected spinner text * @param context Application context * @param cursor Cursor to account data * @param selectedSpinnerItem Layout resource for selected item text */ public QualifiedAccountNameCursorAdapter(Context context, Cursor cursor, @LayoutRes int selectedSpinnerItem) { super(context, selectedSpinnerItem, cursor, new String[]{DatabaseSchema.AccountEntry.COLUMN_FULL_NAME}, new int[]{android.R.id.text1}, 0); setDropDownViewResource(R.layout.account_spinner_dropdown_item); } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setEllipsize(TextUtils.TruncateAt.MIDDLE); Integer isFavorite = cursor.getInt(cursor.getColumnIndex(DatabaseSchema.AccountEntry.COLUMN_FAVORITE)); if(isFavorite == 0) { textView.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0); } else { textView.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_star_black_18dp,0); } } /** * Returns the position of a given account in the adapter * @param accountUID GUID of the account * @return Position of the account or -1 if the account is not found */ public int getPosition(@NonNull String accountUID){ long accountId = AccountsDbAdapter.getInstance().getID(accountUID); for (int pos = 0; pos < getCount(); pos++) { if (getItemId(pos) == accountId){ return pos; } } return -1; } }
3,753
38.515789
115
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/RecursiveMoveFiles.java
/* * Copyright (c) 2016 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import android.util.Log; import org.gnucash.android.db.MigrationHelper; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; /** * Moves all files from one directory into another. * The destination directory is assumed to already exist */ public class RecursiveMoveFiles implements Runnable { File mSource; File mDestination; /** * Constructor, specify origin and target directories * @param src Source directory/file. If directory, all files within it will be moved * @param dst Destination directory/file. If directory, it should already exist */ public RecursiveMoveFiles(File src, File dst){ mSource = src; mDestination = dst; } /** * Copy file from one location to another. * Does not support copying of directories * @param src Source file * @param dst Destination of the file * @return {@code true} if the file was successfully copied, {@code false} otherwise * @throws IOException */ private boolean copy(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { long bytesCopied = inChannel.transferTo(0, inChannel.size(), outChannel); return bytesCopied >= src.length(); } finally { if (inChannel != null) inChannel.close(); outChannel.close(); } } /** * Recursively copy files from one location to another and deletes the origin files after copy. * If the source file is a directory, all of the files in it will be moved. * This method will create the destination directory if the {@code src} is also a directory * @param src origin file * @param dst destination file or directory * @return number of files copied (excluding parent directory) */ private int recursiveMove(File src, File dst){ int copyCount = 0; if (src.isDirectory() && src.listFiles() != null){ dst.mkdirs(); //we assume it works everytime. Great, right? for (File file : src.listFiles()) { File target = new File(dst, file.getName()); copyCount += recursiveMove(file, target); } src.delete(); } else { try { if(copy(src, dst)) src.delete(); } catch (IOException e) { Log.d(MigrationHelper.LOG_TAG, "Error moving file: " + src.getAbsolutePath()); } } Log.d("RecursiveMoveFiles", String.format("Moved %d files from %s to %s", copyCount, src.getPath(), dst.getPath())); return copyCount; } @Override public void run() { recursiveMove(mSource, mDestination); } }
3,608
34.732673
124
java
gnucash-android
gnucash-android-master/app/src/main/java/org/gnucash/android/util/TimestampHelper.java
/* * Copyright (c) 2016 Alceu Rodrigues Neto <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.util; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.sql.Timestamp; /** * A utility class to deal with {@link Timestamp} operations in a centralized way. */ public final class TimestampHelper { public static final Timestamp EPOCH_ZERO_TIMESTAMP = new Timestamp(0); /** * Should be not instantiated. */ private TimestampHelper() {} /** * We are using Joda Time classes because they are thread-safe. */ private static final DateTimeZone UTC_TIME_ZONE = DateTimeZone.forID("UTC"); private static final DateTimeFormatter UTC_DATE_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); private static final DateTimeFormatter UTC_DATE_WITH_MILLISECONDS_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"); /** * Get a {@link String} representing the {@link Timestamp} * in UTC time zone and 'yyyy-MM-dd HH:mm:ss.SSS' format. * * @param timestamp The {@link Timestamp} to format. * @return The formatted {@link String}. */ public static String getUtcStringFromTimestamp(Timestamp timestamp) { return UTC_DATE_WITH_MILLISECONDS_FORMAT.withZone(UTC_TIME_ZONE).print(timestamp.getTime()); } /** * @return A {@link Timestamp} with time in milliseconds equals to zero. */ public static Timestamp getTimestampFromEpochZero() { return EPOCH_ZERO_TIMESTAMP; } /** * Get the {@link Timestamp} with the value of given UTC {@link String}. * The {@link String} should be a representation in UTC time zone with the following format * 'yyyy-MM-dd HH:mm:ss.SSS' OR 'yyyy-MM-dd HH:mm:ss' otherwise an IllegalArgumentException * will be throw. * * @param utcString A {@link String} in UTC. * @return A {@link Timestamp} for given utcString. */ public static Timestamp getTimestampFromUtcString(String utcString) { DateTime dateTime; try { dateTime = UTC_DATE_WITH_MILLISECONDS_FORMAT.withZone(UTC_TIME_ZONE).parseDateTime(utcString); return new Timestamp(dateTime.getMillis()); } catch (IllegalArgumentException firstException) { try { // In case of parsing of string without milliseconds. dateTime = UTC_DATE_FORMAT.withZone(UTC_TIME_ZONE).parseDateTime(utcString); return new Timestamp(dateTime.getMillis()); } catch (IllegalArgumentException secondException) { // If we are here: // - The utcString has an invalid format OR // - We are missing some relevant pattern. throw new IllegalArgumentException("Unknown utcString = '" + utcString + "'.", secondException); } } } /** * @return A {@link Timestamp} initialized with the system current time. */ public static Timestamp getTimestampFromNow() { return new Timestamp(System.currentTimeMillis()); } }
3,777
36.405941
112
java
gnucash-android
gnucash-android-master/app/src/release/java/org/gnucash/android/app/StethoUtils.java
package org.gnucash.android.app; import android.app.Application; /** * Dummy utility class for overriding Stetho initializing in release build variants */ public class StethoUtils { public static void install(Application application) { //nothing to see here, move along //check the debug version of this class to see Stetho init code } }
368
22.0625
83
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/AccountsDbAdapterTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.db; import android.database.sqlite.SQLiteDatabase; import org.assertj.core.data.Index; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseHelper; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.db.adapter.BudgetAmountsDbAdapter; import org.gnucash.android.db.adapter.BudgetsDbAdapter; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.db.adapter.PricesDbAdapter; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.db.adapter.SplitsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.importer.GncXmlImporter; import org.gnucash.android.model.Account; import org.gnucash.android.model.AccountType; import org.gnucash.android.model.Budget; import org.gnucash.android.model.BudgetAmount; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.xml.sax.SAXException; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class AccountsDbAdapterTest{ private static final String BRAVO_ACCOUNT_NAME = "Bravo"; private static final String ALPHA_ACCOUNT_NAME = "Alpha"; private AccountsDbAdapter mAccountsDbAdapter; private TransactionsDbAdapter mTransactionsDbAdapter; private SplitsDbAdapter mSplitsDbAdapter; private CommoditiesDbAdapter mCommoditiesDbAdapter; @Before public void setUp() throws Exception { initAdapters(null); } /** * Initialize database adapters for a specific book. * This method should be called everytime a new book is loaded into the database * @param bookUID GUID of the GnuCash book */ private void initAdapters(String bookUID){ if (bookUID == null){ mSplitsDbAdapter = SplitsDbAdapter.getInstance(); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); mAccountsDbAdapter = AccountsDbAdapter.getInstance(); mCommoditiesDbAdapter = CommoditiesDbAdapter.getInstance(); } else { DatabaseHelper databaseHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), bookUID); SQLiteDatabase db = databaseHelper.getWritableDatabase(); mSplitsDbAdapter = new SplitsDbAdapter(db); mTransactionsDbAdapter = new TransactionsDbAdapter(db, mSplitsDbAdapter); mAccountsDbAdapter = new AccountsDbAdapter(db, mTransactionsDbAdapter); mCommoditiesDbAdapter = new CommoditiesDbAdapter(db); BooksDbAdapter.getInstance().setActive(bookUID); } } /** * Test that the list of accounts is always returned sorted alphabetically */ @Test public void shouldBeAlphabeticallySortedByDefault(){ Account first = new Account(ALPHA_ACCOUNT_NAME); Account second = new Account(BRAVO_ACCOUNT_NAME); //purposefully added the second after the first mAccountsDbAdapter.addRecord(second); mAccountsDbAdapter.addRecord(first); List<Account> accountsList = mAccountsDbAdapter.getAllRecords(); assertEquals(2, accountsList.size()); //bravo was saved first, but alpha should be first alphabetically assertThat(accountsList).contains(first, Index.atIndex(0)); assertThat(accountsList).contains(second, Index.atIndex(1)); } @Test public void bulkAddAccountsShouldNotModifyTransactions(){ Account account1 = new Account("AlphaAccount"); Account account2 = new Account("BetaAccount"); Transaction transaction = new Transaction("MyTransaction"); Split split = new Split(Money.getZeroInstance(), account1.getUID()); transaction.addSplit(split); transaction.addSplit(split.createPair(account2.getUID())); account1.addTransaction(transaction); account2.addTransaction(transaction); List<Account> accounts = new ArrayList<>(); accounts.add(account1); accounts.add(account2); mAccountsDbAdapter.bulkAddRecords(accounts); SplitsDbAdapter splitsDbAdapter = SplitsDbAdapter.getInstance(); assertThat(splitsDbAdapter.getSplitsForTransactionInAccount(transaction.getUID(), account1.getUID())).hasSize(1); assertThat(splitsDbAdapter.getSplitsForTransactionInAccount(transaction.getUID(), account2.getUID())).hasSize(1); assertThat(mAccountsDbAdapter.getRecord(account1.getUID()).getTransactions()).hasSize(1); } @Test public void shouldAddAccountsToDatabase(){ Account account1 = new Account("AlphaAccount"); Account account2 = new Account("BetaAccount"); Transaction transaction = new Transaction("MyTransaction"); Split split = new Split(Money.getZeroInstance(), account1.getUID()); transaction.addSplit(split); transaction.addSplit(split.createPair(account2.getUID())); account1.addTransaction(transaction); account2.addTransaction(transaction); mAccountsDbAdapter.addRecord(account1); mAccountsDbAdapter.addRecord(account2); Account firstAccount = mAccountsDbAdapter.getRecord(account1.getUID()); assertThat(firstAccount).isNotNull(); assertThat(firstAccount.getUID()).isEqualTo(account1.getUID()); assertThat(firstAccount.getFullName()).isEqualTo(account1.getFullName()); Account secondAccount = mAccountsDbAdapter.getRecord(account2.getUID()); assertThat(secondAccount).isNotNull(); assertThat(secondAccount.getUID()).isEqualTo(account2.getUID()); assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1); } /** * Tests the foreign key constraint "ON DELETE CASCADE" between accounts and splits */ @Test public void shouldDeleteSplitsWhenAccountDeleted(){ Account first = new Account(ALPHA_ACCOUNT_NAME); first.setUID(ALPHA_ACCOUNT_NAME); Account second = new Account(BRAVO_ACCOUNT_NAME); second.setUID(BRAVO_ACCOUNT_NAME); mAccountsDbAdapter.addRecord(second); mAccountsDbAdapter.addRecord(first); Transaction transaction = new Transaction("TestTrn"); Split split = new Split(Money.getZeroInstance(), ALPHA_ACCOUNT_NAME); transaction.addSplit(split); transaction.addSplit(split.createPair(BRAVO_ACCOUNT_NAME)); mTransactionsDbAdapter.addRecord(transaction); mAccountsDbAdapter.deleteRecord(ALPHA_ACCOUNT_NAME); Transaction trxn = mTransactionsDbAdapter.getRecord(transaction.getUID()); assertThat(trxn.getSplits().size()).isEqualTo(1); assertThat(trxn.getSplits().get(0).getAccountUID()).isEqualTo(BRAVO_ACCOUNT_NAME); } /** * Tests that a ROOT account will always be created in the system */ @Test public void shouldCreateDefaultRootAccount(){ Account account = new Account("Some account"); mAccountsDbAdapter.addRecord(account); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2L); List<Account> accounts = mAccountsDbAdapter.getSimpleAccountList(); assertThat(accounts).extracting("mAccountType").contains(AccountType.ROOT); String rootAccountUID = mAccountsDbAdapter.getOrCreateGnuCashRootAccountUID(); assertThat(rootAccountUID).isEqualTo(accounts.get(1).getParentUID()); } @Test public void shouldUpdateFullNameAfterParentChange(){ Account parent = new Account("Test"); Account child = new Account("Child"); mAccountsDbAdapter.addRecord(parent); mAccountsDbAdapter.addRecord(child); child.setParentUID(parent.getUID()); mAccountsDbAdapter.addRecord(child); child = mAccountsDbAdapter.getRecord(child.getUID()); parent = mAccountsDbAdapter.getRecord(parent.getUID()); assertThat(mAccountsDbAdapter.getSubAccountCount(parent.getUID())).isEqualTo(1); assertThat(parent.getUID()).isEqualTo(child.getParentUID()); assertThat(child.getFullName()).isEqualTo("Test:Child"); } @Test public void shouldAddTransactionsAndSplitsWhenAddingAccounts(){ Account account = new Account("Test"); mAccountsDbAdapter.addRecord(account); Transaction transaction = new Transaction("Test description"); Split split = new Split(Money.getZeroInstance(), account.getUID()); transaction.addSplit(split); Account account1 = new Account("Transfer account"); transaction.addSplit(split.createPair(account1.getUID())); account1.addTransaction(transaction); mAccountsDbAdapter.addRecord(account1); assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1); assertThat(mSplitsDbAdapter.getRecordsCount()).isEqualTo(2); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(3); //ROOT account automatically added } @Test public void shouldClearAllTablesWhenDeletingAllAccounts(){ Account account = new Account("Test"); Transaction transaction = new Transaction("Test description"); Split split = new Split(Money.getZeroInstance(), account.getUID()); transaction.addSplit(split); Account account2 = new Account("Transfer account"); transaction.addSplit(split.createPair(account2.getUID())); mAccountsDbAdapter.addRecord(account); mAccountsDbAdapter.addRecord(account2); ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); scheduledAction.setActionUID("Test-uid"); scheduledAction.setRecurrence(new Recurrence(PeriodType.WEEK)); ScheduledActionDbAdapter scheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance(); scheduledActionDbAdapter.addRecord(scheduledAction); Budget budget = new Budget("Test"); BudgetAmount budgetAmount = new BudgetAmount(Money.getZeroInstance(), account.getUID()); budget.addBudgetAmount(budgetAmount); budget.setRecurrence(new Recurrence(PeriodType.MONTH)); BudgetsDbAdapter.getInstance().addRecord(budget); mAccountsDbAdapter.deleteAllRecords(); assertThat(mAccountsDbAdapter.getRecordsCount()).isZero(); assertThat(mTransactionsDbAdapter.getRecordsCount()).isZero(); assertThat(mSplitsDbAdapter.getRecordsCount()).isZero(); assertThat(scheduledActionDbAdapter.getRecordsCount()).isZero(); assertThat(BudgetAmountsDbAdapter.getInstance().getRecordsCount()).isZero(); assertThat(BudgetsDbAdapter.getInstance().getRecordsCount()).isZero(); assertThat(PricesDbAdapter.getInstance().getRecordsCount()).isZero(); //prices should remain assertThat(CommoditiesDbAdapter.getInstance().getRecordsCount()).isGreaterThan(50); //commodities should remain } @Test public void simpleAccountListShouldNotContainTransactions(){ Account account = new Account("Test"); Transaction transaction = new Transaction("Test description"); Split split = new Split(Money.getZeroInstance(), account.getUID()); transaction.addSplit(split); Account account1 = new Account("Transfer"); transaction.addSplit(split.createPair(account1.getUID())); mAccountsDbAdapter.addRecord(account); mAccountsDbAdapter.addRecord(account1); List<Account> accounts = mAccountsDbAdapter.getSimpleAccountList(); for (Account testAcct : accounts) { assertThat(testAcct.getTransactionCount()).isZero(); } } @Test public void shouldComputeAccountBalanceCorrectly(){ Account account = new Account("Test", Commodity.USD); account.setAccountType(AccountType.ASSET); //debit normal account balance Account transferAcct = new Account("Transfer"); mAccountsDbAdapter.addRecord(account); mAccountsDbAdapter.addRecord(transferAcct); Transaction transaction = new Transaction("Test description"); mTransactionsDbAdapter.addRecord(transaction); Split split = new Split(new Money(BigDecimal.TEN, Commodity.USD), account.getUID()); split.setTransactionUID(transaction.getUID()); split.setType(TransactionType.DEBIT); mSplitsDbAdapter.addRecord(split); split = new Split(new Money("4.99", "USD"), account.getUID()); split.setTransactionUID(transaction.getUID()); split.setType(TransactionType.DEBIT); mSplitsDbAdapter.addRecord(split); split = new Split(new Money("1.19", "USD"), account.getUID()); split.setTransactionUID(transaction.getUID()); split.setType(TransactionType.CREDIT); mSplitsDbAdapter.addRecord(split); split = new Split(new Money("3.49", "EUR"), account.getUID()); split.setTransactionUID(transaction.getUID()); split.setType(TransactionType.DEBIT); mSplitsDbAdapter.addRecord(split); split = new Split(new Money("8.39", "USD"), transferAcct.getUID()); split.setTransactionUID(transaction.getUID()); mSplitsDbAdapter.addRecord(split); //balance computation ignores the currency of the split Money balance = mAccountsDbAdapter.getAccountBalance(account.getUID()); Money expectedBalance = new Money("17.29", "USD"); //EUR splits should be ignored assertThat(balance).isEqualTo(expectedBalance); } /** * Test creating an account hierarchy by specifying fully qualified name */ @Test public void shouldCreateAccountHierarchy(){ String uid = mAccountsDbAdapter.createAccountHierarchy("Assets:Current Assets:Cash in Wallet", AccountType.ASSET); List<Account> accounts = mAccountsDbAdapter.getAllRecords(); assertThat(accounts).hasSize(3); assertThat(accounts).extracting("mUID").contains(uid); } @Test public void shouldRecursivelyDeleteAccount(){ Account account = new Account("Parent"); Account account2 = new Account("Child"); account2.setParentUID(account.getUID()); Transaction transaction = new Transaction("Random"); account2.addTransaction(transaction); Split split = new Split(Money.getZeroInstance(), account.getUID()); transaction.addSplit(split); transaction.addSplit(split.createPair(account2.getUID())); mAccountsDbAdapter.addRecord(account); mAccountsDbAdapter.addRecord(account2); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(3); assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1); assertThat(mSplitsDbAdapter.getRecordsCount()).isEqualTo(2); boolean result = mAccountsDbAdapter.recursiveDeleteAccount(mAccountsDbAdapter.getID(account.getUID())); assertThat(result).isTrue(); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(1); //the root account assertThat(mTransactionsDbAdapter.getRecordsCount()).isZero(); assertThat(mSplitsDbAdapter.getRecordsCount()).isZero(); } @Test public void shouldGetDescendantAccounts(){ loadDefaultAccounts(); String uid = mAccountsDbAdapter.findAccountUidByFullName("Expenses:Auto"); List<String> descendants = mAccountsDbAdapter.getDescendantAccountUIDs(uid, null, null); assertThat(descendants).hasSize(4); } @Test public void shouldReassignDescendantAccounts(){ loadDefaultAccounts(); String savingsAcctUID = mAccountsDbAdapter.findAccountUidByFullName("Assets:Current Assets:Savings Account"); String currentAssetsUID = mAccountsDbAdapter.findAccountUidByFullName("Assets:Current Assets"); String assetsUID = mAccountsDbAdapter.findAccountUidByFullName("Assets"); assertThat(mAccountsDbAdapter.getParentAccountUID(savingsAcctUID)).isEqualTo(currentAssetsUID); mAccountsDbAdapter.reassignDescendantAccounts(currentAssetsUID, assetsUID); assertThat(mAccountsDbAdapter.getParentAccountUID(savingsAcctUID)).isEqualTo(assetsUID); assertThat(mAccountsDbAdapter.getFullyQualifiedAccountName(savingsAcctUID)).isEqualTo("Assets:Savings Account"); } @Test public void shouldCreateImbalanceAccountOnDemand(){ assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(1L); Commodity usd = mCommoditiesDbAdapter.getCommodity("USD"); String imbalanceUID = mAccountsDbAdapter.getImbalanceAccountUID(usd); assertThat(imbalanceUID).isNull(); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(1L); imbalanceUID = mAccountsDbAdapter.getOrCreateImbalanceAccountUID(usd); assertThat(imbalanceUID).isNotNull().isNotEmpty(); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2); } @Test public void editingAccountShouldNotDeleteTemplateSplits(){ Account account = new Account("First", Commodity.EUR); Account transferAccount = new Account("Transfer", Commodity.EUR); mAccountsDbAdapter.addRecord(account); mAccountsDbAdapter.addRecord(transferAccount); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(3); //plus root account Money money = new Money(BigDecimal.TEN, Commodity.EUR); Transaction transaction = new Transaction("Template"); transaction.setTemplate(true); transaction.setCommodity(Commodity.EUR); Split split = new Split(money, account.getUID()); transaction.addSplit(split); transaction.addSplit(split.createPair(transferAccount.getUID())); mTransactionsDbAdapter.addRecord(transaction); List<Transaction> transactions = mTransactionsDbAdapter.getAllRecords(); assertThat(transactions).hasSize(1); assertThat(mTransactionsDbAdapter.getScheduledTransactionsForAccount(account.getUID())).hasSize(1); //edit the account account.setName("Edited account"); mAccountsDbAdapter.addRecord(account, DatabaseAdapter.UpdateMethod.update); assertThat(mTransactionsDbAdapter.getScheduledTransactionsForAccount(account.getUID())).hasSize(1); assertThat(mSplitsDbAdapter.getSplitsForTransaction(transaction.getUID())).hasSize(2); } @Test public void shouldSetDefaultTransferColumnToNull_WhenTheAccountIsDeleted(){ mAccountsDbAdapter.deleteAllRecords(); assertThat(mAccountsDbAdapter.getRecordsCount()).isZero(); Account account1 = new Account("Test"); Account account2 = new Account("Transfer Account"); account1.setDefaultTransferAccountUID(account2.getUID()); mAccountsDbAdapter.addRecord(account1); mAccountsDbAdapter.addRecord(account2); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(3L); //plus ROOT account mAccountsDbAdapter.deleteRecord(account2.getUID()); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2L); assertThat(mAccountsDbAdapter.getRecord(account1.getUID()).getDefaultTransferAccountUID()).isNull(); Account account3 = new Account("Sub-test"); account3.setParentUID(account1.getUID()); Account account4 = new Account("Third-party"); account4.setDefaultTransferAccountUID(account3.getUID()); mAccountsDbAdapter.addRecord(account3); mAccountsDbAdapter.addRecord(account4); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(4L); mAccountsDbAdapter.recursiveDeleteAccount(mAccountsDbAdapter.getID(account1.getUID())); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(2L); assertThat(mAccountsDbAdapter.getRecord(account4.getUID()).getDefaultTransferAccountUID()).isNull(); } /** * Opening an XML file should set the default currency to that used by the most accounts in the file */ @Test public void importingXml_shouldSetDefaultCurrencyFromXml(){ GnuCashApplication.setDefaultCurrencyCode("JPY"); assertThat(GnuCashApplication.getDefaultCurrencyCode()).isEqualTo("JPY"); assertThat(Commodity.DEFAULT_COMMODITY).isEqualTo(Commodity.JPY); mAccountsDbAdapter.deleteAllRecords(); loadDefaultAccounts(); assertThat(GnuCashApplication.getDefaultCurrencyCode()).isNotEqualTo("JPY"); //the book has USD occuring most often and this will be used as the default currency assertThat(GnuCashApplication.getDefaultCurrencyCode()).isEqualTo("USD"); assertThat(Commodity.DEFAULT_COMMODITY).isEqualTo(Commodity.USD); System.out.println("Default currency is now: " + Commodity.DEFAULT_COMMODITY); } /** * Loads the default accounts from file resource */ private void loadDefaultAccounts(){ try { String bookUID = GncXmlImporter.parse(GnuCashApplication.getAppContext().getResources().openRawResource(R.raw.default_accounts)); initAdapters(bookUID); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create default accounts"); } } @After public void tearDown() throws Exception { mAccountsDbAdapter.deleteAllRecords(); } }
23,111
41.959108
141
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/BooksDbAdapterTest.java
/* * Copyright (c) 2016 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.db; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.importer.GncXmlImporter; import org.gnucash.android.model.BaseModel; import org.gnucash.android.model.Book; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; /** * Test the book database adapter */ @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class BooksDbAdapterTest { private BooksDbAdapter mBooksDbAdapter; @Before public void setUp() { mBooksDbAdapter = BooksDbAdapter.getInstance(); assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(1); //there is always a default book after app start assertThat(mBooksDbAdapter.getActiveBookUID()).isNotNull(); mBooksDbAdapter.deleteAllRecords(); assertThat(mBooksDbAdapter.getRecordsCount()).isZero(); } @Test public void addBook(){ Book book = new Book(BaseModel.generateUID()); mBooksDbAdapter.addRecord(book, DatabaseAdapter.UpdateMethod.insert); assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(1); assertThat(mBooksDbAdapter.getRecord(book.getUID()).getDisplayName()).isEqualTo("Book 1"); } @Test(expected = IllegalArgumentException.class) public void savingBook_requiresRootAccountGUID(){ Book book = new Book(); mBooksDbAdapter.addRecord(book); } @Test public void deleteBook(){ Book book = new Book(); book.setRootAccountUID(BaseModel.generateUID()); mBooksDbAdapter.addRecord(book); mBooksDbAdapter.deleteRecord(book.getUID()); assertThat(mBooksDbAdapter.getRecordsCount()).isZero(); } @Test public void setBookActive(){ Book book1 = new Book(BaseModel.generateUID()); Book book2 = new Book(BaseModel.generateUID()); mBooksDbAdapter.addRecord(book1); mBooksDbAdapter.addRecord(book2); mBooksDbAdapter.setActive(book1.getUID()); assertThat(mBooksDbAdapter.getActiveBookUID()).isEqualTo(book1.getUID()); mBooksDbAdapter.setActive(book2.getUID()); assertThat(mBooksDbAdapter.isActive(book2.getUID())).isTrue(); //setting book2 as active should disable book1 as active Book book = mBooksDbAdapter.getRecord(book1.getUID()); assertThat(book.isActive()).isFalse(); } /** * Test that the generated display name has an ordinal greater than the number of * book records in the database */ @Test public void testGeneratedDisplayName(){ Book book1 = new Book(BaseModel.generateUID()); Book book2 = new Book(BaseModel.generateUID()); mBooksDbAdapter.addRecord(book1); mBooksDbAdapter.addRecord(book2); assertThat(mBooksDbAdapter.generateDefaultBookName()).isEqualTo("Book 3"); } /** * Test that deleting a book record also deletes the book database */ @Test public void deletingBook_shouldDeleteDbFile(){ String bookUID = createNewBookWithDefaultAccounts(); File dbPath = GnuCashApplication.getAppContext().getDatabasePath(bookUID); assertThat(dbPath).exists(); BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance(); assertThat(booksDbAdapter.getRecord(bookUID)).isNotNull(); long booksCount = booksDbAdapter.getRecordsCount(); booksDbAdapter.deleteBook(bookUID); assertThat(dbPath).doesNotExist(); assertThat(booksDbAdapter.getRecordsCount()).isEqualTo(booksCount - 1); } /** * Test that book names never conflict and that the ordinal attached to the book name is * increased irrespective of the order in which books are added to and deleted from the db */ @Test public void testGeneratedDisplayNames_shouldBeUnique(){ Book book1 = new Book(BaseModel.generateUID()); Book book2 = new Book(BaseModel.generateUID()); Book book3 = new Book(BaseModel.generateUID()); mBooksDbAdapter.addRecord(book1); mBooksDbAdapter.addRecord(book2); mBooksDbAdapter.addRecord(book3); assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(3L); mBooksDbAdapter.deleteRecord(book2.getUID()); assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(2L); String generatedName = mBooksDbAdapter.generateDefaultBookName(); assertThat(generatedName).isNotEqualTo(book3.getDisplayName()); assertThat(generatedName).isEqualTo("Book 4"); } @Test public void recoverFromNoActiveBookFound() { Book book1 = new Book(BaseModel.generateUID()); book1.setActive(false); mBooksDbAdapter.addRecord(book1); Book book2 = new Book(BaseModel.generateUID()); book2.setActive(false); mBooksDbAdapter.addRecord(book2); try { mBooksDbAdapter.getActiveBookUID(); fail("There shouldn't be any active book."); } catch (BooksDbAdapter.NoActiveBookFoundException e) { mBooksDbAdapter.fixBooksDatabase(); } assertThat(mBooksDbAdapter.getActiveBookUID()).isEqualTo(book1.getUID()); } /** * Tests the recovery from an empty books database. */ @Test public void recoverFromEmptyDatabase() { createNewBookWithDefaultAccounts(); mBooksDbAdapter.deleteAllRecords(); assertThat(mBooksDbAdapter.getRecordsCount()).isZero(); mBooksDbAdapter.fixBooksDatabase(); // Should've recovered the one from setUp() plus the one created above assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(2); mBooksDbAdapter.getActiveBookUID(); // should not throw exception } /** * Creates a new database with default accounts * @return The book UID for the new database * @throws RuntimeException if the new books could not be created */ private String createNewBookWithDefaultAccounts(){ try { return GncXmlImporter.parse(GnuCashApplication.getAppContext().getResources().openRawResource(R.raw.default_accounts)); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create default accounts"); } } }
7,720
35.419811
131
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/BudgetsDbAdapterTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.db; import android.support.annotation.NonNull; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BudgetAmountsDbAdapter; import org.gnucash.android.db.adapter.BudgetsDbAdapter; import org.gnucash.android.db.adapter.RecurrenceDbAdapter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Budget; import org.gnucash.android.model.BudgetAmount; import org.gnucash.android.model.Money; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for the budgets database adapter */ @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class BudgetsDbAdapterTest { private BudgetsDbAdapter mBudgetsDbAdapter; private RecurrenceDbAdapter mRecurrenceDbAdapter; private BudgetAmountsDbAdapter mBudgetAmountsDbAdapter; private AccountsDbAdapter mAccountsDbAdapter; private Account mAccount; private Account mSecondAccount; @Before public void setUp(){ mAccountsDbAdapter = AccountsDbAdapter.getInstance(); mBudgetsDbAdapter = BudgetsDbAdapter.getInstance(); mBudgetAmountsDbAdapter = BudgetAmountsDbAdapter.getInstance(); mRecurrenceDbAdapter = RecurrenceDbAdapter.getInstance(); mAccount = new Account("Budgeted account"); mSecondAccount = new Account("Another account"); mAccountsDbAdapter.addRecord(mAccount); mAccountsDbAdapter.addRecord(mSecondAccount); } @After public void tearDown(){ mBudgetsDbAdapter.deleteAllRecords(); mBudgetAmountsDbAdapter.deleteAllRecords(); mRecurrenceDbAdapter.deleteAllRecords(); } @Test public void testAddingBudget(){ assertThat(mBudgetsDbAdapter.getRecordsCount()).isZero(); assertThat(mBudgetAmountsDbAdapter.getRecordsCount()).isZero(); assertThat(mRecurrenceDbAdapter.getRecordsCount()).isZero(); Budget budget = new Budget("Test"); budget.addBudgetAmount(new BudgetAmount(Money.getZeroInstance(), mAccount.getUID())); budget.addBudgetAmount(new BudgetAmount(new Money("10", Money.DEFAULT_CURRENCY_CODE), mSecondAccount.getUID())); Recurrence recurrence = new Recurrence(PeriodType.MONTH); budget.setRecurrence(recurrence); mBudgetsDbAdapter.addRecord(budget); assertThat(mBudgetsDbAdapter.getRecordsCount()).isEqualTo(1); assertThat(mBudgetAmountsDbAdapter.getRecordsCount()).isEqualTo(2); assertThat(mRecurrenceDbAdapter.getRecordsCount()).isEqualTo(1); budget.getBudgetAmounts().clear(); BudgetAmount budgetAmount = new BudgetAmount(new Money("5", Money.DEFAULT_CURRENCY_CODE), mAccount.getUID()); budget.addBudgetAmount(budgetAmount); mBudgetsDbAdapter.addRecord(budget); assertThat(mBudgetAmountsDbAdapter.getRecordsCount()).isEqualTo(1); assertThat(mBudgetAmountsDbAdapter.getAllRecords().get(0).getUID()).isEqualTo(budgetAmount.getUID()); } /** * Test that when bulk adding budgets, all the associated budgetAmounts and recurrences are saved */ @Test public void testBulkAddBudgets(){ assertThat(mBudgetsDbAdapter.getRecordsCount()).isZero(); assertThat(mBudgetAmountsDbAdapter.getRecordsCount()).isZero(); assertThat(mRecurrenceDbAdapter.getRecordsCount()).isZero(); List<Budget> budgets = bulkCreateBudgets(); mBudgetsDbAdapter.bulkAddRecords(budgets); assertThat(mBudgetsDbAdapter.getRecordsCount()).isEqualTo(2); assertThat(mBudgetAmountsDbAdapter.getRecordsCount()).isEqualTo(3); assertThat(mRecurrenceDbAdapter.getRecordsCount()).isEqualTo(2); } @Test public void testGetAccountBudgets(){ mBudgetsDbAdapter.bulkAddRecords(bulkCreateBudgets()); List<Budget> budgets = mBudgetsDbAdapter.getAccountBudgets(mAccount.getUID()); assertThat(budgets).hasSize(2); assertThat(mBudgetsDbAdapter.getAccountBudgets(mSecondAccount.getUID())).hasSize(1); } @NonNull private List<Budget> bulkCreateBudgets() { List<Budget> budgets = new ArrayList<>(); Budget budget = new Budget("", new Recurrence(PeriodType.MONTH)); budget.addBudgetAmount(new BudgetAmount(Money.getZeroInstance(), mAccount.getUID())); budgets.add(budget); budget = new Budget("Random", new Recurrence(PeriodType.WEEK)); budget.addBudgetAmount(new BudgetAmount(new Money("10.50", Money.DEFAULT_CURRENCY_CODE), mAccount.getUID())); budget.addBudgetAmount(new BudgetAmount(new Money("32.35", Money.DEFAULT_CURRENCY_CODE), mSecondAccount.getUID())); budgets.add(budget); return budgets; } @Test(expected = NullPointerException.class) public void savingBudget_shouldRequireExistingAccount(){ Budget budget = new Budget(""); budget.addBudgetAmount(new BudgetAmount(Money.getZeroInstance(), "unknown-account")); mBudgetsDbAdapter.addRecord(budget); } @Test(expected = NullPointerException.class) public void savingBudget_shouldRequireRecurrence(){ Budget budget = new Budget(""); budget.addBudgetAmount(new BudgetAmount(Money.getZeroInstance(), mAccount.getUID())); mBudgetsDbAdapter.addRecord(budget); } @Test(expected = IllegalArgumentException.class) public void savingBudget_shouldRequireBudgetAmount(){ Budget budget = new Budget(""); budget.setRecurrence(new Recurrence(PeriodType.MONTH)); mBudgetsDbAdapter.addRecord(budget); } }
6,861
38.66474
123
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/MigrationHelperTest.java
/* * Copyright (c) 2016 Alceu Rodrigues Neto <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.db; import org.gnucash.android.db.MigrationHelper; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.TimestampHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.sql.Timestamp; import java.util.TimeZone; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class MigrationHelperTest { @Test public void shouldSubtractTimeZoneOffset() { /** * The values used here are well known. * See https://en.wikipedia.org/wiki/Unix_time#Notable_events_in_Unix_time * for details. */ final long unixBillennium = 1_000_000_000 * 1000L; final Timestamp unixBillenniumTimestamp = new Timestamp(unixBillennium); final String unixBillenniumUtcString = "2001-09-09 01:46:40.000"; final String unixBillenniumUtcStringAfterSubtract = "2001-09-09 00:46:40.000"; TimeZone timeZone = TimeZone.getTimeZone("GMT-1:00"); Timestamp result = MigrationHelper.subtractTimeZoneOffset(unixBillenniumTimestamp, timeZone); assertThat(TimestampHelper.getUtcStringFromTimestamp(result)) .isEqualTo(unixBillenniumUtcStringAfterSubtract); timeZone = TimeZone.getTimeZone("GMT+1:00"); result = MigrationHelper.subtractTimeZoneOffset(unixBillenniumTimestamp, timeZone); assertThat(TimestampHelper.getUtcStringFromTimestamp(result)) .isEqualTo(unixBillenniumUtcStringAfterSubtract); timeZone = TimeZone.getTimeZone("GMT+0:00"); result = MigrationHelper.subtractTimeZoneOffset(unixBillenniumTimestamp, timeZone); assertThat(TimestampHelper.getUtcStringFromTimestamp(result)) .isEqualTo(unixBillenniumUtcString); } }
2,744
42.571429
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/PriceDbAdapterTest.java
package org.gnucash.android.test.unit.db; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.db.adapter.PricesDbAdapter; import org.gnucash.android.model.Price; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.assertj.core.api.Assertions.assertThat; /** * Test price functions */ @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class PriceDbAdapterTest { /** * The price table should override price for any commodity/currency pair * todo: maybe move this to UI testing. Not sure how Robolectric handles this */ @Test public void shouldOnlySaveOnePricePerCommodityPair(){ String commodityUID = CommoditiesDbAdapter.getInstance().getCommodityUID("EUR"); String currencyUID = CommoditiesDbAdapter.getInstance().getCommodityUID("USD"); Price price = new Price(commodityUID, currencyUID); price.setValueNum(134); price.setValueDenom(100); PricesDbAdapter pricesDbAdapter = PricesDbAdapter.getInstance(); pricesDbAdapter.addRecord(price); price = pricesDbAdapter.getRecord(price.getUID()); assertThat(pricesDbAdapter.getRecordsCount()).isEqualTo(1); assertThat(price.getValueNum()).isEqualTo(67); //the price is reduced to 57/100 before saving Price price1 = new Price(commodityUID, currencyUID); price1.setValueNum(187); price1.setValueDenom(100); pricesDbAdapter.addRecord(price1); assertThat(pricesDbAdapter.getRecordsCount()).isEqualTo(1); Price savedPrice = pricesDbAdapter.getAllRecords().get(0); assertThat(savedPrice.getUID()).isEqualTo(price1.getUID()); //different records assertThat(savedPrice.getValueNum()).isEqualTo(187); assertThat(savedPrice.getValueDenom()).isEqualTo(100); Price price2 = new Price(currencyUID, commodityUID); price2.setValueNum(190); price2.setValueDenom(100); pricesDbAdapter.addRecord(price2); assertThat(pricesDbAdapter.getRecordsCount()).isEqualTo(2); } }
2,478
40.316667
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/ScheduledActionDbAdapterTest.java
package org.gnucash.android.test.unit.db; import android.content.res.Resources; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.model.BaseModel; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Test the scheduled actions database adapter */ @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class ScheduledActionDbAdapterTest { ScheduledActionDbAdapter mScheduledActionDbAdapter; @Before public void setUp(){ mScheduledActionDbAdapter = ScheduledActionDbAdapter.getInstance(); } public void shouldFetchOnlyEnabledScheduledActions(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction.setRecurrence(new Recurrence(PeriodType.MONTH)); scheduledAction.setEnabled(false); mScheduledActionDbAdapter.addRecord(scheduledAction); scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction.setRecurrence(new Recurrence(PeriodType.WEEK)); mScheduledActionDbAdapter.addRecord(scheduledAction); assertThat(mScheduledActionDbAdapter.getAllRecords()).hasSize(2); List<ScheduledAction> enabledActions = mScheduledActionDbAdapter.getAllEnabledScheduledActions(); assertThat(enabledActions).hasSize(1); assertThat(enabledActions.get(0).getRecurrence().getPeriodType()).isEqualTo(PeriodType.WEEK); } @Test(expected = NullPointerException.class) //no recurrence is set public void everyScheduledActionShouldHaveRecurrence(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction.setActionUID(BaseModel.generateUID()); mScheduledActionDbAdapter.addRecord(scheduledAction); } @Test public void testGenerateRepeatString(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); PeriodType periodType = PeriodType.MONTH; Recurrence recurrence = new Recurrence(periodType); recurrence.setMultiplier(2); scheduledAction.setRecurrence(recurrence); scheduledAction.setTotalPlannedExecutionCount(4); Resources res = GnuCashApplication.getAppContext().getResources(); String repeatString = res.getQuantityString(R.plurals.label_every_x_months, 2, 2) + ", " + res.getString(R.string.repeat_x_times, 4); assertThat(scheduledAction.getRepeatString().trim()).isEqualTo(repeatString); } @Test public void testAddGetRecord() { ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); scheduledAction.setActionUID("Some UID"); scheduledAction.setAdvanceCreateDays(1); scheduledAction.setAdvanceNotifyDays(2); scheduledAction.setAutoCreate(true); scheduledAction.setAutoNotify(true); scheduledAction.setEnabled(true); scheduledAction.setStartTime(11111); scheduledAction.setEndTime(33333); scheduledAction.setLastRun(22222); scheduledAction.setExecutionCount(3); scheduledAction.setRecurrence(new Recurrence(PeriodType.MONTH)); scheduledAction.setTag("QIF;SD_CARD;2016-06-25 12:56:07.175;false"); mScheduledActionDbAdapter.addRecord(scheduledAction); ScheduledAction scheduledActionFromDb = mScheduledActionDbAdapter.getRecord(scheduledAction.getUID()); assertThat(scheduledActionFromDb.getUID()).isEqualTo( scheduledAction.getUID()); assertThat(scheduledActionFromDb.getActionUID()).isEqualTo( scheduledAction.getActionUID()); assertThat(scheduledActionFromDb.getAdvanceCreateDays()).isEqualTo( scheduledAction.getAdvanceCreateDays()); assertThat(scheduledActionFromDb.getAdvanceNotifyDays()).isEqualTo( scheduledAction.getAdvanceNotifyDays()); assertThat(scheduledActionFromDb.shouldAutoCreate()).isEqualTo( scheduledAction.shouldAutoCreate()); assertThat(scheduledActionFromDb.shouldAutoNotify()).isEqualTo( scheduledAction.shouldAutoNotify()); assertThat(scheduledActionFromDb.isEnabled()).isEqualTo( scheduledAction.isEnabled()); assertThat(scheduledActionFromDb.getStartTime()).isEqualTo( scheduledAction.getStartTime()); assertThat(scheduledActionFromDb.getEndTime()).isEqualTo( scheduledAction.getEndTime()); assertThat(scheduledActionFromDb.getLastRunTime()).isEqualTo( scheduledAction.getLastRunTime()); assertThat(scheduledActionFromDb.getExecutionCount()).isEqualTo( scheduledAction.getExecutionCount()); assertThat(scheduledActionFromDb.getRecurrence()).isEqualTo( scheduledAction.getRecurrence()); assertThat(scheduledActionFromDb.getTag()).isEqualTo( scheduledAction.getTag()); } }
5,796
45.007937
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/SplitsDbAdapterTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.db; import android.database.sqlite.SQLiteException; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.SplitsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Some tests for the splits database adapter */ @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class SplitsDbAdapterTest { private AccountsDbAdapter mAccountsDbAdapter; private TransactionsDbAdapter mTransactionsDbAdapter; private SplitsDbAdapter mSplitsDbAdapter; private Account mAccount; @Before public void setUp() throws Exception { mSplitsDbAdapter = SplitsDbAdapter.getInstance(); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); mAccountsDbAdapter = AccountsDbAdapter.getInstance(); mAccount = new Account("Test account"); mAccountsDbAdapter.addRecord(mAccount); } /** * Adding a split where the account does not exist in the database should generate an exception */ @Test(expected = SQLiteException.class) public void shouldHaveAccountInDatabase(){ Transaction transaction = new Transaction(""); mTransactionsDbAdapter.addRecord(transaction); Split split = new Split(Money.getZeroInstance(), "non-existent"); split.setTransactionUID(transaction.getUID()); mSplitsDbAdapter.addRecord(split); } /** * Adding a split where the account does not exist in the database should generate an exception */ @Test(expected = SQLiteException.class) public void shouldHaveTransactionInDatabase(){ Transaction transaction = new Transaction(""); //not added to the db Split split = new Split(Money.getZeroInstance(), mAccount.getUID()); split.setTransactionUID(transaction.getUID()); mSplitsDbAdapter.addRecord(split); } @Test public void testAddSplit(){ Transaction transaction = new Transaction(""); mTransactionsDbAdapter.addRecord(transaction); Split split = new Split(Money.getZeroInstance(), mAccount.getUID()); split.setTransactionUID(transaction.getUID()); mSplitsDbAdapter.addRecord(split); List<Split> splits = mSplitsDbAdapter.getSplitsForTransaction(transaction.getUID()); assertThat(splits).isNotEmpty(); assertThat(splits.get(0).getUID()).isEqualTo(split.getUID()); } /** * When a split is added or modified to a transaction, we should set the */ @Test public void addingSplitShouldUnsetExportedFlagOfTransaction(){ Transaction transaction = new Transaction(""); transaction.setExported(true); mTransactionsDbAdapter.addRecord(transaction); assertThat(transaction.isExported()).isTrue(); Split split = new Split(Money.getZeroInstance(), mAccount.getUID()); split.setTransactionUID(transaction.getUID()); mSplitsDbAdapter.addRecord(split); String isExported = mTransactionsDbAdapter.getAttribute(transaction.getUID(), DatabaseSchema.TransactionEntry.COLUMN_EXPORTED); assertThat(Boolean.parseBoolean(isExported)).isFalse(); } @After public void tearDown(){ mAccountsDbAdapter.deleteAllRecords(); } }
4,719
36.165354
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/db/TransactionsDbAdapterTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.db; import org.assertj.core.data.Index; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.SplitsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.math.BigDecimal; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class TransactionsDbAdapterTest { private static final String ALPHA_ACCOUNT_NAME = "Alpha"; private static final String BRAVO_ACCOUNT_NAME = "Bravo"; private static final Commodity DEFAULT_CURRENCY = Commodity.getInstance(Money.DEFAULT_CURRENCY_CODE); private AccountsDbAdapter mAccountsDbAdapter; private TransactionsDbAdapter mTransactionsDbAdapter; private SplitsDbAdapter mSplitsDbAdapter; private Account alphaAccount; private Account bravoAccount; private Split mTestSplit; @Before public void setUp() throws Exception { mSplitsDbAdapter = SplitsDbAdapter.getInstance(); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); mAccountsDbAdapter = AccountsDbAdapter.getInstance(); alphaAccount = new Account(ALPHA_ACCOUNT_NAME); bravoAccount = new Account(BRAVO_ACCOUNT_NAME); mAccountsDbAdapter.addRecord(bravoAccount); mAccountsDbAdapter.addRecord(alphaAccount); mTestSplit = new Split(new Money(BigDecimal.TEN, DEFAULT_CURRENCY), alphaAccount.getUID()); } @Test public void testTransactionsAreTimeSorted(){ Transaction t1 = new Transaction("T800"); t1.setTime(System.currentTimeMillis() - 10000); Split split = new Split(Money.getZeroInstance(), alphaAccount.getUID()); t1.addSplit(split); t1.addSplit(split.createPair(bravoAccount.getUID())); Transaction t2 = new Transaction( "T1000"); t2.setTime(System.currentTimeMillis()); Split split2 = new Split(new Money("23.50", DEFAULT_CURRENCY.getCurrencyCode()), bravoAccount.getUID()); t2.addSplit(split2); t2.addSplit(split2.createPair(alphaAccount.getUID())); mTransactionsDbAdapter.addRecord(t1); mTransactionsDbAdapter.addRecord(t2); List<Transaction> transactionsList = mTransactionsDbAdapter.getAllTransactionsForAccount(alphaAccount.getUID()); assertThat(transactionsList).contains(t2, Index.atIndex(0)); assertThat(transactionsList).contains(t1, Index.atIndex(1)); } @Test public void deletingTransactionsShouldDeleteSplits(){ Transaction transaction = new Transaction(""); Split split = new Split(Money.getZeroInstance(), alphaAccount.getUID()); transaction.addSplit(split); mTransactionsDbAdapter.addRecord(transaction); assertThat(mSplitsDbAdapter.getSplitsForTransaction(transaction.getUID())).hasSize(1); mTransactionsDbAdapter.deleteRecord(transaction.getUID()); assertThat(mSplitsDbAdapter.getSplitsForTransaction(transaction.getUID())).hasSize(0); } @Test public void shouldBalanceTransactionsOnSave(){ Transaction transaction = new Transaction("Auto balance"); Split split = new Split(new Money(BigDecimal.TEN, DEFAULT_CURRENCY), alphaAccount.getUID()); transaction.addSplit(split); mTransactionsDbAdapter.addRecord(transaction); Transaction trn = mTransactionsDbAdapter.getRecord(transaction.getUID()); assertThat(trn.getSplits()).hasSize(2); String imbalanceAccountUID = mAccountsDbAdapter.getImbalanceAccountUID(Commodity.getInstance(Money.DEFAULT_CURRENCY_CODE)); assertThat(trn.getSplits()).extracting("mAccountUID").contains(imbalanceAccountUID); } @Test public void testComputeBalance(){ Transaction transaction = new Transaction("Compute"); Money firstSplitAmount = new Money("4.99", DEFAULT_CURRENCY.getCurrencyCode()); Split split = new Split(firstSplitAmount, alphaAccount.getUID()); transaction.addSplit(split); Money secondSplitAmount = new Money("3.50", DEFAULT_CURRENCY.getCurrencyCode()); split = new Split(secondSplitAmount, bravoAccount.getUID()); transaction.addSplit(split); mTransactionsDbAdapter.addRecord(transaction); //balance is negated because the CASH account has inverse normal balance transaction = mTransactionsDbAdapter.getRecord(transaction.getUID()); Money savedBalance = transaction.getBalance(alphaAccount.getUID()); assertThat(savedBalance).isEqualTo(firstSplitAmount.negate()); savedBalance = transaction.getBalance(bravoAccount.getUID()); assertThat(savedBalance.getNumerator()).isEqualTo(secondSplitAmount.negate().getNumerator()); assertThat(savedBalance.getCommodity()).isEqualTo(secondSplitAmount.getCommodity()); } @After public void tearDown() throws Exception { mAccountsDbAdapter.deleteAllRecords(); } }
5,961
38.483444
125
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/export/BackupTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.export; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.export.ExportFormat; import org.gnucash.android.export.ExportParams; import org.gnucash.android.export.Exporter; import org.gnucash.android.export.xml.GncXmlExporter; import org.gnucash.android.importer.GncXmlImporter; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.BackupManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; /** * Test backup and restore functionality */ @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class BackupTest { @Before public void setUp(){ loadDefaultAccounts(); } @Test public void shouldCreateBackupFileName() throws Exporter.ExporterException { Exporter exporter = new GncXmlExporter(new ExportParams(ExportFormat.XML)); List<String> xmlFiles = exporter.generateExport(); assertThat(xmlFiles).hasSize(1); assertThat(new File(xmlFiles.get(0))) .exists() .hasExtension(ExportFormat.XML.getExtension().substring(1)); } /** * Loads the default accounts from file resource */ private void loadDefaultAccounts(){ try { String bookUID = GncXmlImporter.parse(GnuCashApplication.getAppContext().getResources().openRawResource(R.raw.default_accounts)); BooksDbAdapter.getInstance().setActive(bookUID); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create default accounts"); } } }
2,881
34.580247
141
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/export/GncXmlHelperTest.java
/* * Copyright (c) 2014 - 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.export; import org.gnucash.android.export.xml.GncXmlHelper; import org.gnucash.android.model.Commodity; import org.junit.Test; import java.math.BigDecimal; import java.text.ParseException; import java.util.Currency; import static org.assertj.core.api.Assertions.assertThat; /** * Test the helper methods used for generating GnuCash XML */ public class GncXmlHelperTest { /** * Tests the parsing of split amounts */ @Test public void testParseSplitAmount() throws ParseException { String splitAmount = "12345/100"; BigDecimal amount = GncXmlHelper.parseSplitAmount(splitAmount); assertThat(amount.toPlainString()).isEqualTo("123.45"); amount = GncXmlHelper.parseSplitAmount("1.234,50/100"); assertThat(amount.toPlainString()).isEqualTo("1234.50"); } @Test(expected = ParseException.class) public void shouldFailToParseWronglyFormattedInput() throws ParseException { GncXmlHelper.parseSplitAmount("123.45"); } @Test public void testFormatSplitAmount(){ Commodity usdCommodity = new Commodity("US Dollars", "USD", 100); Commodity euroCommodity = new Commodity("Euro", "EUR", 100); BigDecimal bigDecimal = new BigDecimal("45.90"); String amount = GncXmlHelper.formatSplitAmount(bigDecimal, usdCommodity); assertThat(amount).isEqualTo("4590/100"); bigDecimal = new BigDecimal("350"); amount = GncXmlHelper.formatSplitAmount(bigDecimal, euroCommodity); assertThat(amount).isEqualTo("35000/100"); } }
2,231
32.313433
81
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/export/OfxExporterTest.java
/* * Copyright (c) 2016 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.export; import android.database.sqlite.SQLiteDatabase; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.BookDbHelper; import org.gnucash.android.db.DatabaseHelper; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.export.ExportFormat; import org.gnucash.android.export.ExportParams; import org.gnucash.android.export.ofx.OfxExporter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Book; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.TimestampHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.File; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class OfxExporterTest { private SQLiteDatabase mDb; @Before public void setUp() throws Exception { BookDbHelper bookDbHelper = new BookDbHelper(GnuCashApplication.getAppContext()); BooksDbAdapter booksDbAdapter = new BooksDbAdapter(bookDbHelper.getWritableDatabase()); Book testBook = new Book("testRootAccountUID"); booksDbAdapter.addRecord(testBook); DatabaseHelper databaseHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), testBook.getUID()); mDb = databaseHelper.getWritableDatabase(); } /** * When there aren't new or modified transactions, the OFX exporter * shouldn't create any file. */ @Test public void testWithNoTransactionsToExport_shouldNotCreateAnyFile(){ ExportParams exportParameters = new ExportParams(ExportFormat.OFX); exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero()); exportParameters.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParameters.setDeleteTransactionsAfterExport(false); OfxExporter exporter = new OfxExporter(exportParameters, mDb); assertThat(exporter.generateExport()).isEmpty(); } /** * Test that OFX files are generated */ //FIXME: test failing with NPE public void testGenerateOFXExport(){ AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(mDb); Account account = new Account("Basic Account"); Transaction transaction = new Transaction("One transaction"); transaction.addSplit(new Split(Money.createZeroInstance("EUR"),account.getUID())); account.addTransaction(transaction); accountsDbAdapter.addRecord(account); ExportParams exportParameters = new ExportParams(ExportFormat.OFX); exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero()); exportParameters.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParameters.setDeleteTransactionsAfterExport(false); OfxExporter ofxExporter = new OfxExporter(exportParameters, mDb); List<String> exportedFiles = ofxExporter.generateExport(); assertThat(exportedFiles).hasSize(1); File file = new File(exportedFiles.get(0)); assertThat(file).exists().hasExtension("ofx"); assertThat(file.length()).isGreaterThan(0L); } }
4,446
40.560748
102
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/export/QifExporterTest.java
/* * Copyright (c) 2016 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.export; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.BookDbHelper; import org.gnucash.android.db.DatabaseHelper; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.export.ExportFormat; import org.gnucash.android.export.ExportParams; import org.gnucash.android.export.qif.QifExporter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Book; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.TimestampHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.zip.ZipFile; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class QifExporterTest { private SQLiteDatabase mDb; @Before public void setUp() throws Exception { BookDbHelper bookDbHelper = new BookDbHelper(GnuCashApplication.getAppContext()); BooksDbAdapter booksDbAdapter = new BooksDbAdapter(bookDbHelper.getWritableDatabase()); Book testBook = new Book("testRootAccountUID"); booksDbAdapter.addRecord(testBook); DatabaseHelper databaseHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), testBook.getUID()); mDb = databaseHelper.getWritableDatabase(); } /** * When there aren't new or modified transactions, the QIF exporter * shouldn't create any file. */ @Test public void testWithNoTransactionsToExport_shouldNotCreateAnyFile(){ ExportParams exportParameters = new ExportParams(ExportFormat.QIF); exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero()); exportParameters.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParameters.setDeleteTransactionsAfterExport(false); QifExporter exporter = new QifExporter(exportParameters, mDb); assertThat(exporter.generateExport()).isEmpty(); } /** * Test that QIF files are generated */ @Test public void testGenerateQIFExport(){ AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(mDb); Account account = new Account("Basic Account"); Transaction transaction = new Transaction("One transaction"); transaction.addSplit(new Split(Money.createZeroInstance("EUR"),account.getUID())); account.addTransaction(transaction); accountsDbAdapter.addRecord(account); ExportParams exportParameters = new ExportParams(ExportFormat.QIF); exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero()); exportParameters.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParameters.setDeleteTransactionsAfterExport(false); QifExporter qifExporter = new QifExporter(exportParameters, mDb); List<String> exportedFiles = qifExporter.generateExport(); assertThat(exportedFiles).hasSize(1); File file = new File(exportedFiles.get(0)); assertThat(file).exists().hasExtension("qif"); assertThat(file.length()).isGreaterThan(0L); } /** * Test that when more than one currency is in use, a zip with multiple QIF files * will be generated */ // @Test Fails randomly. Sometimes it doesn't split the QIF. public void multiCurrencyTransactions_shouldResultInMultipleZippedQifFiles() throws IOException { AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(mDb); Account account = new Account("Basic Account", Commodity.getInstance("EUR")); Transaction transaction = new Transaction("One transaction"); transaction.addSplit(new Split(Money.createZeroInstance("EUR"),account.getUID())); account.addTransaction(transaction); accountsDbAdapter.addRecord(account); Account foreignAccount = new Account("US Konto", Commodity.getInstance("USD")); Transaction multiCulti = new Transaction("Multicurrency"); Split split = new Split(new Money("12", "USD"), new Money("15", "EUR"), foreignAccount.getUID()); Split split2 = split.createPair(account.getUID()); multiCulti.addSplit(split); multiCulti.addSplit(split2); foreignAccount.addTransaction(multiCulti); accountsDbAdapter.addRecord(foreignAccount); ExportParams exportParameters = new ExportParams(ExportFormat.QIF); exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero()); exportParameters.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParameters.setDeleteTransactionsAfterExport(false); QifExporter qifExporter = new QifExporter(exportParameters, mDb); List<String> exportedFiles = qifExporter.generateExport(); assertThat(exportedFiles).hasSize(1); File file = new File(exportedFiles.get(0)); assertThat(file).exists().hasExtension("zip"); assertThat(new ZipFile(file).size()).isEqualTo(2); } /** * Test that the memo and description fields of transactions are exported. */ @Test public void memoAndDescription_shouldBeExported() throws IOException { String expectedDescription = "my description"; String expectedMemo = "my memo"; AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(mDb); Account account = new Account("Basic Account"); Transaction transaction = new Transaction("One transaction"); transaction.addSplit(new Split(Money.createZeroInstance("EUR"), account.getUID())); transaction.setDescription(expectedDescription); transaction.setNote(expectedMemo); account.addTransaction(transaction); accountsDbAdapter.addRecord(account); ExportParams exportParameters = new ExportParams(ExportFormat.QIF); exportParameters.setExportStartTime(TimestampHelper.getTimestampFromEpochZero()); exportParameters.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParameters.setDeleteTransactionsAfterExport(false); QifExporter qifExporter = new QifExporter(exportParameters, mDb); List<String> exportedFiles = qifExporter.generateExport(); assertThat(exportedFiles).hasSize(1); File file = new File(exportedFiles.get(0)); String fileContent = readFileContent(file); assertThat(file).exists().hasExtension("qif"); assertThat(fileContent.contains(expectedDescription)); assertThat(fileContent.contains(expectedMemo)); } @NonNull public String readFileContent(File file) throws IOException { StringBuilder fileContentsBuilder = new StringBuilder(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { fileContentsBuilder.append(line).append('\n'); } return fileContentsBuilder.toString(); } }
8,463
41.964467
105
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/importer/GncXmlHandlerTest.java
/* * Copyright (c) 2016 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.importer; import android.database.sqlite.SQLiteDatabase; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseHelper; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.db.adapter.RecurrenceDbAdapter; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.db.adapter.SplitsDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.export.xml.GncXmlHelper; import org.gnucash.android.importer.GncXmlHandler; import org.gnucash.android.model.Account; import org.gnucash.android.model.AccountType; import org.gnucash.android.model.Money; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; /** * Imports GnuCash XML files and checks the objects defined in them are imported correctly. */ @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class GncXmlHandlerTest { private BooksDbAdapter mBooksDbAdapter; private TransactionsDbAdapter mTransactionsDbAdapter; private AccountsDbAdapter mAccountsDbAdapter; private ScheduledActionDbAdapter mScheduledActionDbAdapter; @Before public void setUp() throws Exception { mBooksDbAdapter = BooksDbAdapter.getInstance(); mBooksDbAdapter.deleteAllRecords(); assertThat(mBooksDbAdapter.getRecordsCount()).isZero(); } private String importGnuCashXml(String filename) { SAXParser parser; GncXmlHandler handler = null; try { parser = SAXParserFactory.newInstance().newSAXParser(); XMLReader reader = parser.getXMLReader(); handler = new GncXmlHandler(); reader.setContentHandler(handler); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename); InputSource inputSource = new InputSource(new BufferedInputStream(inputStream)); reader.parse(inputSource); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); fail(); } return handler.getBookUID(); } private void setUpDbAdapters(String bookUID) { DatabaseHelper databaseHelper = new DatabaseHelper(GnuCashApplication.getAppContext(), bookUID); SQLiteDatabase mainDb = databaseHelper.getReadableDatabase(); mTransactionsDbAdapter = new TransactionsDbAdapter(mainDb, new SplitsDbAdapter(mainDb)); mAccountsDbAdapter = new AccountsDbAdapter(mainDb, mTransactionsDbAdapter); RecurrenceDbAdapter recurrenceDbAdapter = new RecurrenceDbAdapter(mainDb); mScheduledActionDbAdapter = new ScheduledActionDbAdapter(mainDb, recurrenceDbAdapter); } /** * Tests basic accounts import. * * <p>Checks hierarchy and attributes. We should have:</p> * <pre> * Root * |_ Assets * | |_ Cash in wallet * |_ Expenses * |_ Dining * </pre> */ @Test public void accountsImport() { String bookUID = importGnuCashXml("accountsImport.xml"); setUpDbAdapters(bookUID); assertThat(mAccountsDbAdapter.getRecordsCount()).isEqualTo(5); // 4 accounts + root Account rootAccount = mAccountsDbAdapter.getRecord("308ade8cf0be2b0b05c5eec3114a65fa"); assertThat(rootAccount.getParentUID()).isNull(); assertThat(rootAccount.getName()).isEqualTo("Root Account"); assertThat(rootAccount.isHidden()).isTrue(); Account assetsAccount = mAccountsDbAdapter.getRecord("3f44d61cb1afd201e8ea5a54ec4fbbff"); assertThat(assetsAccount.getParentUID()).isEqualTo(rootAccount.getUID()); assertThat(assetsAccount.getName()).isEqualTo("Assets"); assertThat(assetsAccount.isHidden()).isFalse(); assertThat(assetsAccount.isPlaceholderAccount()).isTrue(); assertThat(assetsAccount.getAccountType()).isEqualTo(AccountType.ASSET); Account diningAccount = mAccountsDbAdapter.getRecord("6a7cf8267314992bdddcee56d71a3908"); assertThat(diningAccount.getParentUID()).isEqualTo("9b607f63aecb1a175556676904432365"); assertThat(diningAccount.getName()).isEqualTo("Dining"); assertThat(diningAccount.getDescription()).isEqualTo("Dining"); assertThat(diningAccount.isHidden()).isFalse(); assertThat(diningAccount.isPlaceholderAccount()).isFalse(); assertThat(diningAccount.isFavorite()).isFalse(); assertThat(diningAccount.getAccountType()).isEqualTo(AccountType.EXPENSE); assertThat(diningAccount.getCommodity().getCurrencyCode()).isEqualTo("USD"); assertThat(diningAccount.getColor()).isEqualTo(Account.DEFAULT_COLOR); assertThat(diningAccount.getDefaultTransferAccountUID()).isNull(); } /** * Tests importing a simple transaction with default splits. * * @throws ParseException */ @Test public void simpleTransactionImport() throws ParseException { String bookUID = importGnuCashXml("simpleTransactionImport.xml"); setUpDbAdapters(bookUID); assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1); Transaction transaction = mTransactionsDbAdapter.getRecord("b33c8a6160494417558fd143731fc26a"); // Check attributes assertThat(transaction.getDescription()).isEqualTo("Kahuna Burger"); assertThat(transaction.getCommodity().getCurrencyCode()).isEqualTo("USD"); assertThat(transaction.getNote()).isEqualTo(""); assertThat(transaction.getScheduledActionUID()).isNull(); assertThat(transaction.isExported()).isTrue(); assertThat(transaction.isTemplate()).isFalse(); assertThat(transaction.getTimeMillis()). isEqualTo(GncXmlHelper.parseDate("2016-08-23 00:00:00 +0200")); assertThat(transaction.getCreatedTimestamp().getTime()). isEqualTo(GncXmlHelper.parseDate("2016-08-23 12:44:19 +0200")); // Check splits assertThat(transaction.getSplits().size()).isEqualTo(2); // FIXME: don't depend on the order Split split1 = transaction.getSplits().get(0); assertThat(split1.getUID()).isEqualTo("ad2cbc774fc4e71885d17e6932448e8e"); assertThat(split1.getAccountUID()).isEqualTo("6a7cf8267314992bdddcee56d71a3908"); assertThat(split1.getTransactionUID()).isEqualTo("b33c8a6160494417558fd143731fc26a"); assertThat(split1.getType()).isEqualTo(TransactionType.DEBIT); assertThat(split1.getMemo()).isNull(); assertThat(split1.getValue()).isEqualTo(new Money("10", "USD")); assertThat(split1.getQuantity()).isEqualTo(new Money("10", "USD")); assertThat(split1.getReconcileState()).isEqualTo('n'); Split split2 = transaction.getSplits().get(1); assertThat(split2.getUID()).isEqualTo("61d4d604bc00a59cabff4e8875d00bee"); assertThat(split2.getAccountUID()).isEqualTo("dae686a1636addc0dae1ae670701aa4a"); assertThat(split2.getTransactionUID()).isEqualTo("b33c8a6160494417558fd143731fc26a"); assertThat(split2.getType()).isEqualTo(TransactionType.CREDIT); assertThat(split2.getMemo()).isNull(); assertThat(split2.getValue()).isEqualTo(new Money("10", "USD")); assertThat(split2.getQuantity()).isEqualTo(new Money("10", "USD")); assertThat(split2.getReconcileState()).isEqualTo('n'); assertThat(split2.isPairOf(split1)).isTrue(); } /** * Tests importing a transaction with non-default splits. * * @throws ParseException */ @Test public void transactionWithNonDefaultSplitsImport() throws ParseException { String bookUID = importGnuCashXml("transactionWithNonDefaultSplitsImport.xml"); setUpDbAdapters(bookUID); assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1); Transaction transaction = mTransactionsDbAdapter.getRecord("042ff745a80e94e6237fb0549f6d32ae"); // Ensure it's the correct one assertThat(transaction.getDescription()).isEqualTo("Tandoori Mahal"); // Check splits assertThat(transaction.getSplits().size()).isEqualTo(3); // FIXME: don't depend on the order Split expenseSplit = transaction.getSplits().get(0); assertThat(expenseSplit.getUID()).isEqualTo("c50cce06e2bf9085730821c82d0b36ca"); assertThat(expenseSplit.getAccountUID()).isEqualTo("6a7cf8267314992bdddcee56d71a3908"); assertThat(expenseSplit.getTransactionUID()).isEqualTo("042ff745a80e94e6237fb0549f6d32ae"); assertThat(expenseSplit.getType()).isEqualTo(TransactionType.DEBIT); assertThat(expenseSplit.getMemo()).isNull(); assertThat(expenseSplit.getValue()).isEqualTo(new Money("50", "USD")); assertThat(expenseSplit.getQuantity()).isEqualTo(new Money("50", "USD")); Split assetSplit1 = transaction.getSplits().get(1); assertThat(assetSplit1.getUID()).isEqualTo("4930f412665a705eedba39789b6c3a35"); assertThat(assetSplit1.getAccountUID()).isEqualTo("dae686a1636addc0dae1ae670701aa4a"); assertThat(assetSplit1.getTransactionUID()).isEqualTo("042ff745a80e94e6237fb0549f6d32ae"); assertThat(assetSplit1.getType()).isEqualTo(TransactionType.CREDIT); assertThat(assetSplit1.getMemo()).isEqualTo("tip"); assertThat(assetSplit1.getValue()).isEqualTo(new Money("5", "USD")); assertThat(assetSplit1.getQuantity()).isEqualTo(new Money("5", "USD")); assertThat(assetSplit1.isPairOf(expenseSplit)).isFalse(); Split assetSplit2 = transaction.getSplits().get(2); assertThat(assetSplit2.getUID()).isEqualTo("b97cd9bbaa17f181d0a5b39b260dabda"); assertThat(assetSplit2.getAccountUID()).isEqualTo("ee139a5658a0d37507dc26284798e347"); assertThat(assetSplit2.getTransactionUID()).isEqualTo("042ff745a80e94e6237fb0549f6d32ae"); assertThat(assetSplit2.getType()).isEqualTo(TransactionType.CREDIT); assertThat(assetSplit2.getMemo()).isNull(); assertThat(assetSplit2.getValue()).isEqualTo(new Money("45", "USD")); assertThat(assetSplit2.getQuantity()).isEqualTo(new Money("45", "USD")); assertThat(assetSplit2.isPairOf(expenseSplit)).isFalse(); } /** * Tests importing a transaction with multiple currencies. * * @throws ParseException */ @Test public void multiCurrencyTransactionImport() throws ParseException { String bookUID = importGnuCashXml("multiCurrencyTransactionImport.xml"); setUpDbAdapters(bookUID); assertThat(mTransactionsDbAdapter.getRecordsCount()).isEqualTo(1); Transaction transaction = mTransactionsDbAdapter.getRecord("ded49386f8ea319ccaee043ba062b3e1"); // Ensure it's the correct one assertThat(transaction.getDescription()).isEqualTo("Salad express"); assertThat(transaction.getCommodity().getCurrencyCode()).isEqualTo("USD"); // Check splits assertThat(transaction.getSplits().size()).isEqualTo(2); // FIXME: don't depend on the order Split split1 = transaction.getSplits().get(0); assertThat(split1.getUID()).isEqualTo("88bbbbac7689a8657b04427f8117a783"); assertThat(split1.getAccountUID()).isEqualTo("6a7cf8267314992bdddcee56d71a3908"); assertThat(split1.getTransactionUID()).isEqualTo("ded49386f8ea319ccaee043ba062b3e1"); assertThat(split1.getType()).isEqualTo(TransactionType.DEBIT); assertThat(split1.getValue()).isEqualTo(new Money("20", "USD")); assertThat(split1.getQuantity()).isEqualTo(new Money("20", "USD")); Split split2 = transaction.getSplits().get(1); assertThat(split2.getUID()).isEqualTo("e0dd885065bfe3c9ef63552fe84c6d23"); assertThat(split2.getAccountUID()).isEqualTo("0469e915a22ba7846aca0e69f9f9b683"); assertThat(split2.getTransactionUID()).isEqualTo("ded49386f8ea319ccaee043ba062b3e1"); assertThat(split2.getType()).isEqualTo(TransactionType.CREDIT); assertThat(split2.getValue()).isEqualTo(new Money("20", "USD")); assertThat(split2.getQuantity()).isEqualTo(new Money("17.93", "EUR")); assertThat(split2.isPairOf(split1)).isTrue(); } /** * Tests importing a simple scheduled transaction with default splits. */ //@Test Disabled as currently amounts are only read from credit/debit-numeric // slots and transactions without amount are ignored. public void simpleScheduledTransactionImport() throws ParseException { String bookUID = importGnuCashXml("simpleScheduledTransactionImport.xml"); setUpDbAdapters(bookUID); assertThat(mTransactionsDbAdapter.getTemplateTransactionsCount()).isEqualTo(1); Transaction scheduledTransaction = mTransactionsDbAdapter.getRecord("b645bef06d0844aece6424ceeec03983"); // Check attributes assertThat(scheduledTransaction.getDescription()).isEqualTo("Los pollos hermanos"); assertThat(scheduledTransaction.getCommodity().getCurrencyCode()).isEqualTo("USD"); assertThat(scheduledTransaction.getNote()).isEqualTo(""); assertThat(scheduledTransaction.getScheduledActionUID()).isNull(); assertThat(scheduledTransaction.isExported()).isTrue(); assertThat(scheduledTransaction.isTemplate()).isTrue(); assertThat(scheduledTransaction.getTimeMillis()) .isEqualTo(GncXmlHelper.parseDate("2016-08-24 00:00:00 +0200")); assertThat(scheduledTransaction.getCreatedTimestamp().getTime()) .isEqualTo(GncXmlHelper.parseDate("2016-08-24 19:50:15 +0200")); // Check splits assertThat(scheduledTransaction.getSplits().size()).isEqualTo(2); Split split1 = scheduledTransaction.getSplits().get(0); assertThat(split1.getUID()).isEqualTo("f66794ef262aac3ae085ecc3030f2769"); assertThat(split1.getAccountUID()).isEqualTo("6a7cf8267314992bdddcee56d71a3908"); assertThat(split1.getTransactionUID()).isEqualTo("b645bef06d0844aece6424ceeec03983"); assertThat(split1.getType()).isEqualTo(TransactionType.CREDIT); assertThat(split1.getMemo()).isNull(); assertThat(split1.getValue()).isEqualTo(new Money("20", "USD")); // FIXME: the quantity is always 0 as it's set from <split:quantity> instead // of from the slots //assertThat(split1.getQuantity()).isEqualTo(new Money("20", "USD")); Split split2 = scheduledTransaction.getSplits().get(1); assertThat(split2.getUID()).isEqualTo("57e2be6ca6b568f8f7c9b2e455e1e21f"); assertThat(split2.getAccountUID()).isEqualTo("dae686a1636addc0dae1ae670701aa4a"); assertThat(split2.getTransactionUID()).isEqualTo("b645bef06d0844aece6424ceeec03983"); assertThat(split2.getType()).isEqualTo(TransactionType.DEBIT); assertThat(split2.getMemo()).isNull(); assertThat(split2.getValue()).isEqualTo(new Money("20", "USD")); // FIXME: the quantity is always 0 as it's set from <split:quantity> instead // of from the slots //assertThat(split2.getQuantity()).isEqualTo(new Money("20", "USD")); assertThat(split2.isPairOf(split1)).isTrue(); } /** * Tests that importing a weekly scheduled action sets the days of the * week of the recursion. */ @Test public void importingScheduledAction_shouldSetByDays() throws ParseException { String bookUID = importGnuCashXml("importingScheduledAction_shouldSetByDays.xml"); setUpDbAdapters(bookUID); ScheduledAction scheduledTransaction = mScheduledActionDbAdapter.getRecord("b5a13acb5a9459ebed10d06b75bbad10"); // There are 3 byDays but, for now, getting one is enough to ensure it is executed assertThat(scheduledTransaction.getRecurrence().getByDays().size()).isGreaterThanOrEqualTo(1); // Until we implement parsing of days of the week for scheduled actions, // we'll just use the day of the week of the start time. int dayOfWeekFromByDays = scheduledTransaction.getRecurrence().getByDays().get(0); Date startTime = new Date(scheduledTransaction.getStartTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(startTime); int dayOfWeekFromStartTime = calendar.get(Calendar.DAY_OF_WEEK); assertThat(dayOfWeekFromByDays).isEqualTo(dayOfWeekFromStartTime); } /** * Checks for bug 562 - Scheduled transaction imported with imbalanced splits. * * <p>Happens when an scheduled transaction is defined with both credit and * debit slots in each split.</p> */ @Test public void bug562_scheduledTransactionImportedWithImbalancedSplits() throws ParseException { String bookUID = importGnuCashXml("bug562_scheduledTransactionImportedWithImbalancedSplits.xml"); setUpDbAdapters(bookUID); assertThat(mTransactionsDbAdapter.getTemplateTransactionsCount()).isEqualTo(1); Transaction scheduledTransaction = mTransactionsDbAdapter.getRecord("b645bef06d0844aece6424ceeec03983"); // Ensure it's the correct transaction assertThat(scheduledTransaction.getDescription()).isEqualTo("Los pollos hermanos"); assertThat(scheduledTransaction.isTemplate()).isTrue(); // Check splits assertThat(scheduledTransaction.getSplits().size()).isEqualTo(2); Split split1 = scheduledTransaction.getSplits().get(0); assertThat(split1.getAccountUID()).isEqualTo("6a7cf8267314992bdddcee56d71a3908"); assertThat(split1.getType()).isEqualTo(TransactionType.CREDIT); assertThat(split1.getValue()).isEqualTo(new Money("20", "USD")); // FIXME: the quantity is always 0 as it's set from <split:quantity> instead // of from the slots //assertThat(split1.getQuantity()).isEqualTo(new Money("20", "USD")); Split split2 = scheduledTransaction.getSplits().get(1); assertThat(split2.getAccountUID()).isEqualTo("dae686a1636addc0dae1ae670701aa4a"); assertThat(split2.getType()).isEqualTo(TransactionType.DEBIT); assertThat(split2.getValue()).isEqualTo(new Money("20", "USD")); // FIXME: the quantity is always 0 as it's set from <split:quantity> instead // of from the slots //assertThat(split2.getQuantity()).isEqualTo(new Money("20", "USD")); assertThat(split2.isPairOf(split1)).isTrue(); } }
20,255
48.525672
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/AccountTest.java
/* * Copyright (c) 2012 - 2014 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import android.graphics.Color; import org.gnucash.android.model.Account; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Transaction; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class AccountTest{ @Test public void testAccountUsesDefaultCurrency(){ Account account = new Account("Dummy account"); assertThat(account.getCommodity().getCurrencyCode()).isEqualTo(Money.DEFAULT_CURRENCY_CODE); } @Test public void testAccountAlwaysHasUID(){ Account account = new Account("Dummy"); assertThat(account.getUID()).isNotNull(); } @Test public void testTransactionsHaveSameCurrencyAsAccount(){ Account acc1 = new Account("Japanese", Commodity.JPY); acc1.setUID("simile"); Transaction trx = new Transaction("Underground"); Transaction term = new Transaction( "Tube"); assertThat(trx.getCurrencyCode()).isEqualTo(Money.DEFAULT_CURRENCY_CODE); acc1.addTransaction(trx); acc1.addTransaction(term); assertThat(trx.getCurrencyCode()).isEqualTo("JPY"); assertThat(term.getCurrencyCode()).isEqualTo("JPY"); } @Test(expected = IllegalArgumentException.class) public void testSetInvalidColorCode(){ Account account = new Account("Test"); account.setColor("443859"); } @Test(expected = IllegalArgumentException.class) public void testSetColorWithAlphaComponent(){ Account account = new Account("Test"); account.setColor(Color.parseColor("#aa112233")); } @Test public void shouldSetFullNameWhenCreated(){ String fullName = "Full name "; Account account = new Account(fullName); assertThat(account.getName()).isEqualTo(fullName.trim()); //names are trimmed assertThat(account.getFullName()).isEqualTo(fullName.trim()); //names are trimmed } @Test public void settingNameShouldNotChangeFullName(){ String fullName = "Full name"; Account account = new Account(fullName); account.setName("Name"); assertThat(account.getName()).isEqualTo("Name"); assertThat(account.getFullName()).isEqualTo(fullName); } @Test public void newInstance_shouldReturnNonNullValues() { Account account = new Account("Test account"); assertThat(account.getDescription()).isEqualTo(""); assertThat(account.getColor()).isEqualTo(Account.DEFAULT_COLOR); } }
3,386
32.205882
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/BudgetTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import org.gnucash.android.model.Budget; import org.gnucash.android.model.BudgetAmount; import org.gnucash.android.model.Money; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for budgets */ public class BudgetTest { @Test public void addingBudgetAmount_shouldSetBudgetUID(){ Budget budget = new Budget("Test"); assertThat(budget.getBudgetAmounts()).isNotNull(); BudgetAmount budgetAmount = new BudgetAmount(Money.getZeroInstance(), "test"); budget.addBudgetAmount(budgetAmount); assertThat(budget.getBudgetAmounts()).hasSize(1); assertThat(budgetAmount.getBudgetUID()).isEqualTo(budget.getUID()); //setting a whole list should also set the budget UIDs List<BudgetAmount> budgetAmounts = new ArrayList<>(); budgetAmounts.add(new BudgetAmount(Money.getZeroInstance(),"test")); budgetAmounts.add(new BudgetAmount(Money.getZeroInstance(), "second")); budget.setBudgetAmounts(budgetAmounts); assertThat(budget.getBudgetAmounts()).extracting("mBudgetUID") .contains(budget.getUID()); } @Test public void shouldComputeAbsoluteAmountSum(){ Budget budget = new Budget("Test"); Money accountAmount = new Money("-20", "USD"); BudgetAmount budgetAmount = new BudgetAmount(accountAmount, "account1"); BudgetAmount budgetAmount1 = new BudgetAmount(new Money("10", "USD"), "account2"); budget.addBudgetAmount(budgetAmount); budget.addBudgetAmount(budgetAmount1); assertThat(budget.getAmount("account1")).isEqualTo(accountAmount.abs()); assertThat(budget.getAmountSum()).isEqualTo(new Money("30", "USD")); } /** * Tests that the method {@link Budget#getCompactedBudgetAmounts()} does not aggregate * {@link BudgetAmount}s which have different money amounts */ @Test public void shouldNotCompactBudgetAmountsWithDifferentAmounts(){ Budget budget = new Budget("Test"); budget.setNumberOfPeriods(6); BudgetAmount budgetAmount = new BudgetAmount(new Money("10", "USD"), "test"); budgetAmount.setPeriodNum(1); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("15", "USD"), "test"); budgetAmount.setPeriodNum(2); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("5", "USD"), "secondAccount"); budgetAmount.setPeriodNum(5); budget.addBudgetAmount(budgetAmount); List<BudgetAmount> compactedBudgetAmounts = budget.getCompactedBudgetAmounts(); assertThat(compactedBudgetAmounts).hasSize(3); assertThat(compactedBudgetAmounts).extracting("mAccountUID") .contains("test", "secondAccount"); assertThat(compactedBudgetAmounts).extracting("mPeriodNum") .contains(1L, 2L, 5L).doesNotContain(-1L); } /** * Tests that the method {@link Budget#getCompactedBudgetAmounts()} aggregates {@link BudgetAmount}s * with the same amount but leaves others untouched */ @Test public void addingSameAmounts_shouldCompactOnRetrieval(){ Budget budget = new Budget("Test"); budget.setNumberOfPeriods(6); BudgetAmount budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(1); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(2); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(5); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("10", "EUR"), "second"); budgetAmount.setPeriodNum(4); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("13", "EUR"), "third"); budgetAmount.setPeriodNum(-1); budget.addBudgetAmount(budgetAmount); List<BudgetAmount> compactedBudgetAmounts = budget.getCompactedBudgetAmounts(); assertThat(compactedBudgetAmounts).hasSize(3); assertThat(compactedBudgetAmounts).extracting("mPeriodNum").hasSize(3) .contains(-1L, 4L).doesNotContain(1L, 2L, 3L); assertThat(compactedBudgetAmounts).extracting("mAccountUID").hasSize(3) .contains("first", "second", "third"); } /** * Test that when we set a periodNumber of -1 to a budget amount, the method {@link Budget#getExpandedBudgetAmounts()} * should create new budget amounts for each of the periods in the budgeting period */ @Test public void addingNegativePeriodNum_shouldExpandOnRetrieval(){ Budget budget = new Budget("Test"); budget.setNumberOfPeriods(6); BudgetAmount budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(-1); budget.addBudgetAmount(budgetAmount); List<BudgetAmount> expandedBudgetAmount = budget.getExpandedBudgetAmounts(); assertThat(expandedBudgetAmount).hasSize(6); assertThat(expandedBudgetAmount).extracting("mPeriodNum").hasSize(6) .contains(0L,1L,2L,3L,4L,5L).doesNotContain(-1L); assertThat(expandedBudgetAmount).extracting("mAccountUID").hasSize(6); } @Test public void testGetNumberOfAccounts(){ Budget budget = new Budget("Test"); budget.setNumberOfPeriods(6); BudgetAmount budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(1); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(2); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("10", "USD"), "first"); budgetAmount.setPeriodNum(5); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("10", "EUR"), "second"); budgetAmount.setPeriodNum(4); budget.addBudgetAmount(budgetAmount); budgetAmount = new BudgetAmount(new Money("13", "EUR"), "third"); budgetAmount.setPeriodNum(-1); budget.addBudgetAmount(budgetAmount); assertThat(budget.getNumberOfAccounts()).isEqualTo(3); } }
7,213
37.57754
122
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/CommodityTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import org.gnucash.android.model.Commodity; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Test commodities */ public class CommodityTest { @Test public void setSmallestFraction_shouldNotUseDigits(){ Commodity commodity = new Commodity("Test", "USD", 100); assertThat(commodity.getSmallestFraction()).isEqualTo(100); commodity.setSmallestFraction(1000); assertThat(commodity.getSmallestFraction()).isEqualTo(1000); } @Test public void testSmallestFractionDigits(){ Commodity commodity = new Commodity("Test", "USD", 100); assertThat(commodity.getSmallestFractionDigits()).isEqualTo(2); commodity.setSmallestFraction(10); assertThat(commodity.getSmallestFractionDigits()).isEqualTo(1); commodity.setSmallestFraction(1); assertThat(commodity.getSmallestFractionDigits()).isEqualTo(0); } }
1,603
31.08
75
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/MoneyTest.java
/* * Copyright (c) 2012 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.math.BigDecimal; import java.util.Currency; import java.util.Locale; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class MoneyTest{ private static final String CURRENCY_CODE = "EUR"; private Money mMoneyInEur; private int mHashcode; private String amountString = "15.75"; @Before public void setUp() throws Exception { mMoneyInEur = new Money(new BigDecimal(amountString), Commodity.getInstance(CURRENCY_CODE)); mHashcode = mMoneyInEur.hashCode(); } @Test public void testCreation(){ Locale.setDefault(Locale.US); String amount = "12.25"; Money temp = new Money(amount, CURRENCY_CODE); assertThat("12.25").isEqualTo(temp.toPlainString()); assertThat(temp.getNumerator()).isEqualTo(1225L); assertThat(temp.getDenominator()).isEqualTo(100L); Commodity commodity = Commodity.getInstance(CURRENCY_CODE); temp = new Money(BigDecimal.TEN, commodity); assertEquals("10.00", temp.asBigDecimal().toPlainString()); //decimal places for EUR currency assertEquals(commodity, temp.getCommodity()); assertThat("10").isNotEqualTo(temp.asBigDecimal().toPlainString()); } @Test public void testAddition(){ Money result = mMoneyInEur.add(new Money("5", CURRENCY_CODE)); assertEquals("20.75", result.toPlainString()); assertNotSame(result, mMoneyInEur); validateImmutability(); } @Test(expected = Money.CurrencyMismatchException.class) public void testAdditionWithIncompatibleCurrency(){ Money addend = new Money("4", "USD"); mMoneyInEur.add(addend); } @Test public void testSubtraction(){ Money result = mMoneyInEur.subtract(new Money("2", CURRENCY_CODE)); assertEquals(new BigDecimal("13.75"), result.asBigDecimal()); assertNotSame(result, mMoneyInEur); validateImmutability(); } @Test(expected = Money.CurrencyMismatchException.class) public void testSubtractionWithDifferentCurrency(){ Money addend = new Money("4", "USD"); mMoneyInEur.subtract(addend); } @Test public void testMultiplication(){ Money result = mMoneyInEur.multiply(new Money(BigDecimal.TEN, Commodity.getInstance(CURRENCY_CODE))); assertThat("157.50").isEqualTo(result.toPlainString()); assertThat(result).isNotEqualTo(mMoneyInEur); validateImmutability(); } @Test(expected = Money.CurrencyMismatchException.class) public void testMultiplicationWithDifferentCurrencies(){ Money addend = new Money("4", "USD"); mMoneyInEur.multiply(addend); } @Test public void testDivision(){ Money result = mMoneyInEur.divide(2); assertThat(result.toPlainString()).isEqualTo("7.88"); assertThat(result).isNotEqualTo(mMoneyInEur); validateImmutability(); } @Test(expected = Money.CurrencyMismatchException.class) public void testDivisionWithDifferentCurrency(){ Money addend = new Money("4", "USD"); mMoneyInEur.divide(addend); } @Test public void testNegation(){ Money result = mMoneyInEur.negate(); assertThat(result.toPlainString()).startsWith("-"); validateImmutability(); } @Test public void testFractionParts(){ Money money = new Money("14.15", "USD"); assertThat(money.getNumerator()).isEqualTo(1415L); assertThat(money.getDenominator()).isEqualTo(100L); money = new Money("125", "JPY"); assertThat(money.getNumerator()).isEqualTo(125L); assertThat(money.getDenominator()).isEqualTo(1L); } @Test public void nonMatchingCommodityFraction_shouldThrowException(){ Money money = new Money("12.345", "JPY"); assertThat(money.getNumerator()).isEqualTo(12L); assertThat(money.getDenominator()).isEqualTo(1); } @Test public void testPrinting(){ assertEquals(mMoneyInEur.asString(), mMoneyInEur.toPlainString()); assertEquals(amountString, mMoneyInEur.asString()); // the unicode for Euro symbol is \u20AC String symbol = Currency.getInstance("EUR").getSymbol(Locale.GERMANY); String actualOuputDE = mMoneyInEur.formattedString(Locale.GERMANY); assertThat(actualOuputDE).isEqualTo("15,75 " + symbol); symbol = Currency.getInstance("EUR").getSymbol(Locale.GERMANY); String actualOuputUS = mMoneyInEur.formattedString(Locale.US); assertThat(actualOuputUS).isEqualTo(symbol + "15.75"); //always prints with 2 decimal places only Money some = new Money("9.7469", CURRENCY_CODE); assertEquals("9.75", some.asString()); } public void validateImmutability(){ assertEquals(mHashcode, mMoneyInEur.hashCode()); assertEquals(amountString, mMoneyInEur.toPlainString()); assertEquals(CURRENCY_CODE, mMoneyInEur.getCommodity().getCurrencyCode()); } }
5,809
31.640449
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/PriceTest.java
/* * Copyright (c) 2016 Àlex Magaz Graça <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import org.gnucash.android.model.Price; import org.junit.Test; import java.math.BigDecimal; import java.util.Locale; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class PriceTest { @Test public void creatingFromExchangeRate_ShouldGetPrecisionRight() { Locale.setDefault(Locale.US); String exchangeRateString = "0.123456"; BigDecimal exchangeRate = new BigDecimal(exchangeRateString); Price price = new Price("commodity1UID", "commodity2UID", exchangeRate); assertThat(price.toString()).isEqualTo(exchangeRateString); // ensure we don't get more decimal places than needed (0.123000) exchangeRateString = "0.123"; exchangeRate = new BigDecimal(exchangeRateString); price = new Price("commodity1UID", "commodity2UID", exchangeRate); assertThat(price.toString()).isEqualTo(exchangeRateString); } @Test public void toString_shouldUseDefaultLocale() { Locale.setDefault(Locale.GERMANY); String exchangeRateString = "1.234"; BigDecimal exchangeRate = new BigDecimal(exchangeRateString); Price price = new Price("commodity1UID", "commodity2UID", exchangeRate); assertThat(price.toString()).isEqualTo("1,234"); } /** * BigDecimal throws an ArithmeticException if it can't represent exactly * a result. This can happen with divisions like 1/3 if no precision and * round mode is specified with a MathContext. */ @Test public void toString_shouldNotFailForInfinitelyLongDecimalExpansion() { long numerator = 1; long denominator = 3; Price price = new Price(); price.setValueNum(numerator); price.setValueDenom(denominator); try { price.toString(); } catch (ArithmeticException e) { fail("The numerator/denominator division in Price.toString() should not fail."); } } @Test public void getNumerator_shouldReduceAutomatically() { long numerator = 1; long denominator = 3; Price price = new Price(); price.setValueNum(numerator * 2); price.setValueDenom(denominator * 2); assertThat(price.getValueNum()).isEqualTo(numerator); } @Test public void getDenominator_shouldReduceAutomatically() { long numerator = 1; long denominator = 3; Price price = new Price(); price.setValueNum(numerator * 2); price.setValueDenom(denominator * 2); assertThat(price.getValueDenom()).isEqualTo(denominator); } }
3,311
32.795918
92
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/RecurrenceTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import org.joda.time.DateTime; import org.junit.Test; import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; /** * Test {@link Recurrence}s */ public class RecurrenceTest { @Test public void settingCount_shouldComputeCorrectEndTime(){ Recurrence recurrence = new Recurrence(PeriodType.MONTH); DateTime startTime = new DateTime(2015, 10, 5, 0, 0); recurrence.setPeriodStart(new Timestamp(startTime.getMillis())); recurrence.setPeriodEnd(3); DateTime expectedEndtime = new DateTime(2016, 1, 5, 0, 0); assertThat(recurrence.getPeriodEnd().getTime()).isEqualTo(expectedEndtime.getMillis()); } /** * When the end date of a recurrence is set, we should be able to correctly get the number of occurrences */ @Test public void testRecurrenceCountComputation(){ Recurrence recurrence = new Recurrence(PeriodType.MONTH); DateTime start = new DateTime(2015, 10, 5, 0, 0); recurrence.setPeriodStart(new Timestamp(start.getMillis())); DateTime end = new DateTime(2016, 8, 5, 0, 0); recurrence.setPeriodEnd(new Timestamp(end.getMillis())); assertThat(recurrence.getCount()).isEqualTo(10); //test case where last appointment is just a little before end time, but not a complete period since last DateTime startTime = new DateTime(2016, 6, 6, 9, 0); DateTime endTime = new DateTime(2016, 8, 29, 10, 0); PeriodType biWeekly = PeriodType.WEEK; recurrence = new Recurrence(biWeekly); recurrence.setMultiplier(2); recurrence.setPeriodStart(new Timestamp(startTime.getMillis())); recurrence.setPeriodEnd(new Timestamp(endTime.getMillis())); assertThat(recurrence.getCount()).isEqualTo(7); } /** * When no end period is set, getCount() should return the special value -1. * * <p>Tests for bug https://github.com/codinguser/gnucash-android/issues/526</p> */ @Test public void notSettingEndDate_shouldReturnSpecialCountValue() { Recurrence recurrence = new Recurrence(PeriodType.MONTH); DateTime start = new DateTime(2015, 10, 5, 0, 0); recurrence.setPeriodStart(new Timestamp(start.getMillis())); assertThat(recurrence.getCount()).isEqualTo(-1); } }
3,102
34.261364
113
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/ScheduledActionTest.java
/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.model; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import org.gnucash.android.model.ScheduledAction; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; import org.junit.Test; import java.sql.Timestamp; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; /** * Test scheduled actions */ public class ScheduledActionTest { @Test public void settingStartTime_shouldSetRecurrenceStart(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); long startTime = getTimeInMillis(2014, 8, 26); scheduledAction.setStartTime(startTime); assertThat(scheduledAction.getRecurrence()).isNull(); Recurrence recurrence = new Recurrence(PeriodType.MONTH); assertThat(recurrence.getPeriodStart().getTime()).isNotEqualTo(startTime); scheduledAction.setRecurrence(recurrence); assertThat(recurrence.getPeriodStart().getTime()).isEqualTo(startTime); long newStartTime = getTimeInMillis(2015, 6, 6); scheduledAction.setStartTime(newStartTime); assertThat(recurrence.getPeriodStart().getTime()).isEqualTo(newStartTime); } @Test public void settingEndTime_shouldSetRecurrenceEnd(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); long endTime = getTimeInMillis(2014, 8, 26); scheduledAction.setEndTime(endTime); assertThat(scheduledAction.getRecurrence()).isNull(); Recurrence recurrence = new Recurrence(PeriodType.MONTH); assertThat(recurrence.getPeriodEnd()).isNull(); scheduledAction.setRecurrence(recurrence); assertThat(recurrence.getPeriodEnd().getTime()).isEqualTo(endTime); long newEndTime = getTimeInMillis(2015, 6, 6); scheduledAction.setEndTime(newEndTime); assertThat(recurrence.getPeriodEnd().getTime()).isEqualTo(newEndTime); } @Test public void settingRecurrence_shouldSetScheduledActionStartTime(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); assertThat(scheduledAction.getStartTime()).isEqualTo(0); long startTime = getTimeInMillis(2014, 8, 26); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setPeriodStart(new Timestamp(startTime)); scheduledAction.setRecurrence(recurrence); assertThat(scheduledAction.getStartTime()).isEqualTo(startTime); } @Test public void settingRecurrence_shouldSetEndTime(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); assertThat(scheduledAction.getStartTime()).isEqualTo(0); long endTime = getTimeInMillis(2017, 8, 26); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setPeriodEnd(new Timestamp(endTime)); scheduledAction.setRecurrence(recurrence); assertThat(scheduledAction.getEndTime()).isEqualTo(endTime); } /** * Checks that scheduled actions accurately compute the next run time based on the start date * and the last time the action was run */ @Test public void testComputingNextScheduledExecution(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); PeriodType periodType = PeriodType.MONTH; Recurrence recurrence = new Recurrence(periodType); recurrence.setMultiplier(2); DateTime startDate = new DateTime(2015, 8, 15, 12, 0); recurrence.setPeriodStart(new Timestamp(startDate.getMillis())); scheduledAction.setRecurrence(recurrence); assertThat(scheduledAction.computeNextCountBasedScheduledExecutionTime()).isEqualTo(startDate.getMillis()); scheduledAction.setExecutionCount(3); DateTime expectedTime = new DateTime(2016, 2, 15, 12, 0); assertThat(scheduledAction.computeNextCountBasedScheduledExecutionTime()).isEqualTo(expectedTime.getMillis()); } @Test public void testComputingTimeOfLastSchedule(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); PeriodType periodType = PeriodType.WEEK; Recurrence recurrence = new Recurrence(periodType); recurrence.setMultiplier(2); scheduledAction.setRecurrence(recurrence); DateTime startDate = new DateTime(2016, 6, 6, 9, 0); scheduledAction.setStartTime(startDate.getMillis()); assertThat(scheduledAction.getTimeOfLastSchedule()).isEqualTo(-1L); scheduledAction.setExecutionCount(3); DateTime expectedDate = new DateTime(2016, 7, 4, 9, 0); assertThat(scheduledAction.getTimeOfLastSchedule()).isEqualTo(expectedDate.getMillis()); } /** * Weekly actions scheduled to run on multiple days of the week should be due * in each of them in the same week. * * For an action scheduled on Mondays and Thursdays, we test that, if * the last run was on Monday, the next should be due on the Thursday * of the same week instead of the following week. */ @Test public void multiDayOfWeekWeeklyActions_shouldBeDueOnEachDayOfWeekSet() { ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setByDays(Arrays.asList(Calendar.MONDAY, Calendar.THURSDAY)); scheduledAction.setRecurrence(recurrence); scheduledAction.setStartTime(new DateTime(2016, 6, 6, 9, 0).getMillis()); scheduledAction.setLastRun(new DateTime(2017, 4, 17, 9, 0).getMillis()); // Monday long expectedNextDueDate = new DateTime(2017, 4, 20, 9, 0).getMillis(); // Thursday assertThat(scheduledAction.computeNextTimeBasedScheduledExecutionTime()) .isEqualTo(expectedNextDueDate); } /** * Weekly actions scheduled with multiplier should skip intermediate * weeks and be due in the specified day of the week. */ @Test public void weeklyActionsWithMultiplier_shouldBeDueOnTheDayOfWeekSet() { ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setMultiplier(2); recurrence.setByDays(Collections.singletonList(Calendar.WEDNESDAY)); scheduledAction.setRecurrence(recurrence); scheduledAction.setStartTime(new DateTime(2016, 6, 6, 9, 0).getMillis()); scheduledAction.setLastRun(new DateTime(2017, 4, 12, 9, 0).getMillis()); // Wednesday // Wednesday, 2 weeks after the last run long expectedNextDueDate = new DateTime(2017, 4, 26, 9, 0).getMillis(); assertThat(scheduledAction.computeNextTimeBasedScheduledExecutionTime()) .isEqualTo(expectedNextDueDate); } /** * Weekly actions should return a date in the future when no * days of the week have been set in the recurrence. * * See ScheduledAction.computeNextTimeBasedScheduledExecutionTime() */ @Test public void weeklyActionsWithoutDayOfWeekSet_shouldReturnDateInTheFuture() { ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setByDays(Collections.<Integer>emptyList()); scheduledAction.setRecurrence(recurrence); scheduledAction.setStartTime(new DateTime(2016, 6, 6, 9, 0).getMillis()); scheduledAction.setLastRun(new DateTime(2017, 4, 12, 9, 0).getMillis()); long now = LocalDateTime.now().toDate().getTime(); assertThat(scheduledAction.computeNextTimeBasedScheduledExecutionTime()).isGreaterThan(now); } private long getTimeInMillis(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day); return calendar.getTimeInMillis(); } //todo add test for computing the scheduledaction endtime from the recurrence count }
8,960
42.289855
118
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/SplitTest.java
package org.gnucash.android.test.unit.model; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.math.BigDecimal; import static org.assertj.core.api.Assertions.assertThat; /** * Test cases for Splits * * @author Ngewi */ @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class SplitTest { @Test public void amounts_shouldBeStoredUnsigned() { Split split = new Split(new Money("-1", "USD"), new Money("-2", "EUR"), "account-UID"); assertThat(split.getValue().isNegative()).isFalse(); assertThat(split.getQuantity().isNegative()).isFalse(); split.setValue(new Money("-3", "USD")); split.setQuantity(new Money("-4", "EUR")); assertThat(split.getValue().isNegative()).isFalse(); assertThat(split.getQuantity().isNegative()).isFalse(); } @Test public void testAddingSplitToTransaction(){ Split split = new Split(Money.getZeroInstance(), "Test"); assertThat(split.getTransactionUID()).isEmpty(); Transaction transaction = new Transaction("Random"); transaction.addSplit(split); assertThat(transaction.getUID()).isEqualTo(split.getTransactionUID()); } @Test public void testCloning(){ Split split = new Split(new Money(BigDecimal.TEN, Commodity.getInstance("EUR")), "random-account"); split.setTransactionUID("terminator-trx"); split.setType(TransactionType.CREDIT); Split clone1 = new Split(split, false); assertThat(clone1).isEqualTo(split); Split clone2 = new Split(split, true); assertThat(clone2.getUID()).isNotEqualTo(split.getUID()); assertThat(split.isEquivalentTo(clone2)).isTrue(); } /** * Tests that a split pair has the inverse transaction type as the origin split. * Everything else should be the same */ @Test public void shouldCreateInversePair(){ Split split = new Split(new Money("2", "USD"), "dummy"); split.setType(TransactionType.CREDIT); split.setTransactionUID("random-trx"); Split pair = split.createPair("test"); assertThat(pair.getType()).isEqualTo(TransactionType.DEBIT); assertThat(pair.getValue()).isEqualTo(split.getValue()); assertThat(pair.getMemo()).isEqualTo(split.getMemo()); assertThat(pair.getTransactionUID()).isEqualTo(split.getTransactionUID()); } @Test public void shouldGenerateValidCsv(){ Split split = new Split(new Money(BigDecimal.TEN, Commodity.getInstance("EUR")), "random-account"); split.setTransactionUID("terminator-trx"); split.setType(TransactionType.CREDIT); assertThat(split.toCsv()).isEqualTo(split.getUID() + ";1000;100;EUR;1000;100;EUR;terminator-trx;random-account;CREDIT"); } @Test public void shouldParseCsv(){ String csv = "test-split-uid;490;100;USD;490;100;USD;trx-action;test-account;DEBIT;Didn't you get the memo?"; Split split = Split.parseSplit(csv); assertThat(split.getValue().getNumerator()).isEqualTo(new Money("4.90", "USD").getNumerator()); assertThat(split.getTransactionUID()).isEqualTo("trx-action"); assertThat(split.getAccountUID()).isEqualTo("test-account"); assertThat(split.getType()).isEqualTo(TransactionType.DEBIT); assertThat(split.getMemo()).isEqualTo("Didn't you get the memo?"); } }
3,951
37.745098
128
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/model/TransactionTest.java
package org.gnucash.android.test.unit.model; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class TransactionTest { @Test public void testCloningTransaction(){ Transaction transaction = new Transaction("Bobba Fett"); assertThat(transaction.getUID()).isNotNull(); assertThat(transaction.getCurrencyCode()).isEqualTo(Commodity.DEFAULT_COMMODITY.getCurrencyCode()); Transaction clone1 = new Transaction(transaction, false); assertThat(transaction.getUID()).isEqualTo(clone1.getUID()); assertThat(transaction).isEqualTo(clone1); Transaction clone2 = new Transaction(transaction, true); assertThat(transaction.getUID()).isNotEqualTo(clone2.getUID()); assertThat(transaction.getCurrencyCode()).isEqualTo(clone2.getCurrencyCode()); assertThat(transaction.getDescription()).isEqualTo(clone2.getDescription()); assertThat(transaction.getNote()).isEqualTo(clone2.getNote()); assertThat(transaction.getTimeMillis()).isEqualTo(clone2.getTimeMillis()); //TODO: Clone the created_at and modified_at times? } /** * Adding a split to a transaction should set the transaction UID of the split to the GUID of the transaction */ @Test public void addingSplitsShouldSetTransactionUID(){ Transaction transaction = new Transaction(""); assertThat(transaction.getCurrencyCode()).isEqualTo(Commodity.DEFAULT_COMMODITY.getCurrencyCode()); Split split = new Split(Money.getZeroInstance(), "test-account"); assertThat(split.getTransactionUID()).isEmpty(); transaction.addSplit(split); assertThat(split.getTransactionUID()).isEqualTo(transaction.getUID()); } @Test public void settingUID_shouldSetTransactionUidOfSplits(){ Transaction t1 = new Transaction("Test"); Split split1 = new Split(Money.getZeroInstance(), "random"); split1.setTransactionUID("non-existent"); Split split2 = new Split(Money.getZeroInstance(), "account-something"); split2.setTransactionUID("pre-existent"); List<Split> splits = new ArrayList<>(); splits.add(split1); splits.add(split2); t1.setSplits(splits); assertThat(t1.getSplits()).extracting("mTransactionUID") .contains(t1.getUID()) .doesNotContain("non-existent") .doesNotContain("pre-existent"); } @Test public void testCreateAutoBalanceSplit() { Transaction transactionCredit = new Transaction("Transaction with more credit"); transactionCredit.setCommodity(Commodity.getInstance("EUR")); Split creditSplit = new Split(new Money("1", "EUR"), "test-account"); creditSplit.setType(TransactionType.CREDIT); transactionCredit.addSplit(creditSplit); Split debitBalanceSplit = transactionCredit.createAutoBalanceSplit(); assertThat(creditSplit.getValue().isNegative()).isFalse(); assertThat(debitBalanceSplit.getValue()).isEqualTo(creditSplit.getValue()); assertThat(creditSplit.getQuantity().isNegative()).isFalse(); assertThat(debitBalanceSplit.getQuantity()).isEqualTo(creditSplit.getQuantity()); Transaction transactionDebit = new Transaction("Transaction with more debit"); transactionDebit.setCommodity(Commodity.getInstance("EUR")); Split debitSplit = new Split(new Money("1", "EUR"), "test-account"); debitSplit.setType(TransactionType.DEBIT); transactionDebit.addSplit(debitSplit); Split creditBalanceSplit = transactionDebit.createAutoBalanceSplit(); assertThat(debitSplit.getValue().isNegative()).isFalse(); assertThat(creditBalanceSplit.getValue()).isEqualTo(debitSplit.getValue()); assertThat(debitSplit.getQuantity().isNegative()).isFalse(); assertThat(creditBalanceSplit.getQuantity()).isEqualTo(debitSplit.getQuantity()); } }
4,311
38.559633
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/service/ScheduledActionServiceTest.java
/* * Copyright (c) 2016 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.service; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.AccountsDbAdapter; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.db.adapter.CommoditiesDbAdapter; import org.gnucash.android.db.adapter.DatabaseAdapter; import org.gnucash.android.db.adapter.ScheduledActionDbAdapter; import org.gnucash.android.db.adapter.TransactionsDbAdapter; import org.gnucash.android.export.ExportFormat; import org.gnucash.android.export.ExportParams; import org.gnucash.android.export.Exporter; import org.gnucash.android.importer.GncXmlImporter; import org.gnucash.android.model.Account; import org.gnucash.android.model.Commodity; import org.gnucash.android.model.Money; import org.gnucash.android.model.PeriodType; import org.gnucash.android.model.Recurrence; import org.gnucash.android.model.ScheduledAction; import org.gnucash.android.model.Split; import org.gnucash.android.model.Transaction; import org.gnucash.android.model.TransactionType; import org.gnucash.android.service.ScheduledActionService; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.BookUtils; import org.gnucash.android.util.TimestampHelper; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.LocalDateTime; import org.joda.time.Weeks; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; /** * Test the the scheduled actions service runs as expected */ @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class ScheduledActionServiceTest { private static String mActionUID; private SQLiteDatabase mDb; private static Account mBaseAccount = new Account("Base Account"); private static Account mTransferAccount = new Account("Transfer Account"); private static Transaction mTemplateTransaction; private TransactionsDbAdapter mTransactionsDbAdapter; public void createAccounts(){ try { String bookUID = GncXmlImporter.parse(GnuCashApplication.getAppContext().getResources().openRawResource(R.raw.default_accounts)); BookUtils.loadBook(bookUID); //initAdapters(bookUID); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create default accounts"); } } @BeforeClass public static void makeAccounts(){ mTemplateTransaction = new Transaction("Recurring Transaction"); mTemplateTransaction.setTemplate(true); mActionUID = mTemplateTransaction.getUID(); } @Before public void setUp(){ mDb = GnuCashApplication.getActiveDb(); new CommoditiesDbAdapter(mDb); //initializes commodity static values mBaseAccount.setCommodity(Commodity.DEFAULT_COMMODITY); mTransferAccount.setCommodity(Commodity.DEFAULT_COMMODITY); mTemplateTransaction.setCommodity(Commodity.DEFAULT_COMMODITY); Split split1 = new Split(new Money(BigDecimal.TEN, Commodity.DEFAULT_COMMODITY), mBaseAccount.getUID()); Split split2 = split1.createPair(mTransferAccount.getUID()); mTemplateTransaction.addSplit(split1); mTemplateTransaction.addSplit(split2); AccountsDbAdapter accountsDbAdapter = AccountsDbAdapter.getInstance(); accountsDbAdapter.addRecord(mBaseAccount); accountsDbAdapter.addRecord(mTransferAccount); mTransactionsDbAdapter = TransactionsDbAdapter.getInstance(); mTransactionsDbAdapter.addRecord(mTemplateTransaction, DatabaseAdapter.UpdateMethod.insert); } @Test public void disabledScheduledActions_shouldNotRun(){ Recurrence recurrence = new Recurrence(PeriodType.WEEK); ScheduledAction scheduledAction1 = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction1.setStartTime(System.currentTimeMillis() - 100000); scheduledAction1.setEnabled(false); scheduledAction1.setActionUID(mActionUID); scheduledAction1.setRecurrence(recurrence); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction1); TransactionsDbAdapter trxnAdapter = TransactionsDbAdapter.getInstance(); assertThat(trxnAdapter.getRecordsCount()).isZero(); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(trxnAdapter.getRecordsCount()).isZero(); } @Test public void futureScheduledActions_shouldNotRun(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction.setStartTime(System.currentTimeMillis() + 100000); scheduledAction.setEnabled(true); scheduledAction.setRecurrence(new Recurrence(PeriodType.MONTH)); scheduledAction.setActionUID(mActionUID); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction); TransactionsDbAdapter trxnAdapter = TransactionsDbAdapter.getInstance(); assertThat(trxnAdapter.getRecordsCount()).isZero(); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(trxnAdapter.getRecordsCount()).isZero(); } /** * Transactions whose execution count has reached or exceeded the planned execution count */ @Test public void exceededExecutionCounts_shouldNotRun(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); scheduledAction.setActionUID(mActionUID); scheduledAction.setStartTime(new DateTime(2015, 5, 31, 14, 0).getMillis()); scheduledAction.setEnabled(true); scheduledAction.setRecurrence(new Recurrence(PeriodType.WEEK)); scheduledAction.setTotalPlannedExecutionCount(4); scheduledAction.setExecutionCount(4); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction); TransactionsDbAdapter trxnAdapter = TransactionsDbAdapter.getInstance(); assertThat(trxnAdapter.getRecordsCount()).isZero(); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(trxnAdapter.getRecordsCount()).isZero(); } /** * Test that normal scheduled transactions would lead to new transaction entries */ @Test public void missedScheduledTransactions_shouldBeGenerated(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); DateTime startTime = new DateTime(2016, 6, 6, 9, 0); scheduledAction.setStartTime(startTime.getMillis()); DateTime endTime = new DateTime(2016, 9, 12, 8, 0); //end just before last appointment scheduledAction.setEndTime(endTime.getMillis()); scheduledAction.setActionUID(mActionUID); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setMultiplier(2); recurrence.setByDays(Collections.singletonList(Calendar.MONDAY)); scheduledAction.setRecurrence(recurrence); ScheduledActionDbAdapter.getInstance().addRecord(scheduledAction, DatabaseAdapter.UpdateMethod.insert); TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); assertThat(transactionsDbAdapter.getRecordsCount()).isZero(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(transactionsDbAdapter.getRecordsCount()).isEqualTo(7); } public void endTimeInTheFuture_shouldExecuteOnlyUntilPresent(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); DateTime startTime = new DateTime(2016, 6, 6, 9, 0); scheduledAction.setStartTime(startTime.getMillis()); scheduledAction.setActionUID(mActionUID); scheduledAction.setRecurrence(PeriodType.WEEK, 2); scheduledAction.setEndTime(new DateTime(2017, 8, 16, 9, 0).getMillis()); ScheduledActionDbAdapter.getInstance().addRecord(scheduledAction, DatabaseAdapter.UpdateMethod.insert); TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); assertThat(transactionsDbAdapter.getRecordsCount()).isZero(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction); ScheduledActionService.processScheduledActions(actions, mDb); int weeks = Weeks.weeksBetween(startTime, new DateTime(2016, 8, 29, 10, 0)).getWeeks(); int expectedTransactionCount = weeks/2; //multiplier from the PeriodType assertThat(transactionsDbAdapter.getRecordsCount()).isEqualTo(expectedTransactionCount); } /** * Test that if the end time of a scheduled transaction has passed, but the schedule was missed * (either because the book was not opened or similar) then the scheduled transactions for the * relevant period should still be executed even though end time has passed. * <p>This holds only for transactions. Backups will be skipped</p> */ @Test public void scheduledTransactionsWithEndTimeInPast_shouldBeExecuted(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); DateTime startTime = new DateTime(2016, 6, 6, 9, 0); scheduledAction.setStartTime(startTime.getMillis()); scheduledAction.setActionUID(mActionUID); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setMultiplier(2); recurrence.setByDays(Collections.singletonList(Calendar.MONDAY)); scheduledAction.setRecurrence(recurrence); scheduledAction.setEndTime(new DateTime(2016, 8, 8, 9, 0).getMillis()); ScheduledActionDbAdapter.getInstance().addRecord(scheduledAction, DatabaseAdapter.UpdateMethod.insert); TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); assertThat(transactionsDbAdapter.getRecordsCount()).isZero(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction); ScheduledActionService.processScheduledActions(actions, mDb); int expectedCount = 5; assertThat(scheduledAction.getExecutionCount()).isEqualTo(expectedCount); assertThat(transactionsDbAdapter.getRecordsCount()).isEqualTo(expectedCount); //would be 6 if the end time is not respected } /** * Test that only scheduled actions with action UIDs are processed */ @Test //(expected = IllegalArgumentException.class) public void recurringTransactions_shouldHaveScheduledActionUID(){ ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION); DateTime startTime = new DateTime(2016, 7, 4, 12 ,0); scheduledAction.setStartTime(startTime.getMillis()); scheduledAction.setRecurrence(PeriodType.MONTH, 1); TransactionsDbAdapter transactionsDbAdapter = TransactionsDbAdapter.getInstance(); assertThat(transactionsDbAdapter.getRecordsCount()).isZero(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledAction); ScheduledActionService.processScheduledActions(actions, mDb); //no change in the database since no action UID was specified assertThat(transactionsDbAdapter.getRecordsCount()).isZero(); } /** * Scheduled backups should run only once. * * <p>Backups may have been missed since the last run, but still only * one should be done.</p> * * <p>For example, if we have set up a daily backup, the last one * was done on Monday and it's Thursday, two backups have been * missed. Doing the two missed backups plus today's wouldn't be * useful, so just one should be done.</p> */ @Test public void scheduledBackups_shouldRunOnlyOnce(){ ScheduledAction scheduledBackup = new ScheduledAction(ScheduledAction.ActionType.BACKUP); scheduledBackup.setStartTime(LocalDateTime.now() .minusMonths(4).minusDays(2).toDate().getTime()); scheduledBackup.setRecurrence(PeriodType.MONTH, 1); scheduledBackup.setExecutionCount(2); scheduledBackup.setLastRun(LocalDateTime.now().minusMonths(2).toDate().getTime()); long previousLastRun = scheduledBackup.getLastRunTime(); ExportParams backupParams = new ExportParams(ExportFormat.XML); backupParams.setExportTarget(ExportParams.ExportTarget.SD_CARD); scheduledBackup.setTag(backupParams.toCsv()); File backupFolder = new File(Exporter.getExportFolderPath(BooksDbAdapter.getInstance().getActiveBookUID())); assertThat(backupFolder).exists(); assertThat(backupFolder.listFiles()).isEmpty(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledBackup); // Check there's not a backup for each missed run ScheduledActionService.processScheduledActions(actions, mDb); assertThat(scheduledBackup.getExecutionCount()).isEqualTo(3); assertThat(scheduledBackup.getLastRunTime()).isGreaterThan(previousLastRun); File[] backupFiles = backupFolder.listFiles(); assertThat(backupFiles).hasSize(1); assertThat(backupFiles[0]).exists().hasExtension("gnca"); // Check also across service runs previousLastRun = scheduledBackup.getLastRunTime(); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(scheduledBackup.getExecutionCount()).isEqualTo(3); assertThat(scheduledBackup.getLastRunTime()).isEqualTo(previousLastRun); backupFiles = backupFolder.listFiles(); assertThat(backupFiles).hasSize(1); assertThat(backupFiles[0]).exists().hasExtension("gnca"); } /** * Tests that a scheduled backup isn't executed before the next scheduled * execution according to its recurrence. * * <p>Tests for bug https://github.com/codinguser/gnucash-android/issues/583</p> */ @Test public void scheduledBackups_shouldNotRunBeforeNextScheduledExecution(){ ScheduledAction scheduledBackup = new ScheduledAction(ScheduledAction.ActionType.BACKUP); scheduledBackup.setStartTime( LocalDateTime.now().withDayOfWeek(DateTimeConstants.WEDNESDAY).toDate().getTime()); scheduledBackup.setLastRun(scheduledBackup.getStartTime()); long previousLastRun = scheduledBackup.getLastRunTime(); scheduledBackup.setExecutionCount(1); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setMultiplier(1); recurrence.setByDays(Collections.singletonList(Calendar.MONDAY)); scheduledBackup.setRecurrence(recurrence); ExportParams backupParams = new ExportParams(ExportFormat.XML); backupParams.setExportTarget(ExportParams.ExportTarget.SD_CARD); scheduledBackup.setTag(backupParams.toCsv()); File backupFolder = new File( Exporter.getExportFolderPath(BooksDbAdapter.getInstance().getActiveBookUID())); assertThat(backupFolder).exists(); assertThat(backupFolder.listFiles()).isEmpty(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledBackup); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(scheduledBackup.getExecutionCount()).isEqualTo(1); assertThat(scheduledBackup.getLastRunTime()).isEqualTo(previousLastRun); assertThat(backupFolder.listFiles()).hasSize(0); } /** * Tests that a scheduled QIF backup isn't done when no transactions have * been added or modified after the last run. */ @Test public void scheduledBackups_shouldNotIncludeTransactionsPreviousToTheLastRun() { ScheduledAction scheduledBackup = new ScheduledAction(ScheduledAction.ActionType.BACKUP); scheduledBackup.setStartTime(LocalDateTime.now().minusDays(15).toDate().getTime()); scheduledBackup.setLastRun(LocalDateTime.now().minusDays(8).toDate().getTime()); long previousLastRun = scheduledBackup.getLastRunTime(); scheduledBackup.setExecutionCount(1); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setMultiplier(1); recurrence.setByDays(Collections.singletonList(Calendar.WEDNESDAY)); scheduledBackup.setRecurrence(recurrence); ExportParams backupParams = new ExportParams(ExportFormat.QIF); backupParams.setExportTarget(ExportParams.ExportTarget.SD_CARD); backupParams.setExportStartTime(new Timestamp(scheduledBackup.getStartTime())); scheduledBackup.setTag(backupParams.toCsv()); // Create a transaction with a modified date previous to the last run Transaction transaction = new Transaction("Tandoori express"); Split split = new Split(new Money("10", Commodity.DEFAULT_COMMODITY.getCurrencyCode()), mBaseAccount.getUID()); split.setType(TransactionType.DEBIT); transaction.addSplit(split); transaction.addSplit(split.createPair(mTransferAccount.getUID())); mTransactionsDbAdapter.addRecord(transaction); // We set the date directly in the database as the corresponding field // is ignored when the object is stored. It's set through a trigger instead. setTransactionInDbModifiedTimestamp(transaction.getUID(), new Timestamp(LocalDateTime.now().minusDays(9).toDate().getTime())); File backupFolder = new File( Exporter.getExportFolderPath(BooksDbAdapter.getInstance().getActiveBookUID())); assertThat(backupFolder).exists(); assertThat(backupFolder.listFiles()).isEmpty(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledBackup); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(scheduledBackup.getExecutionCount()).isEqualTo(1); assertThat(scheduledBackup.getLastRunTime()).isEqualTo(previousLastRun); assertThat(backupFolder.listFiles()).hasSize(0); } /** * Sets the transaction modified timestamp directly in the database. * * @param transactionUID UID of the transaction to set the modified timestamp. * @param timestamp new modified timestamp. */ private void setTransactionInDbModifiedTimestamp(String transactionUID, Timestamp timestamp) { ContentValues values = new ContentValues(); values.put(DatabaseSchema.TransactionEntry.COLUMN_MODIFIED_AT, TimestampHelper.getUtcStringFromTimestamp(timestamp)); mTransactionsDbAdapter.updateTransaction(values, "uid = ?", new String[]{transactionUID}); } /** * Tests that an scheduled backup includes transactions added or modified * after the last run. */ @Test public void scheduledBackups_shouldIncludeTransactionsAfterTheLastRun() { ScheduledAction scheduledBackup = new ScheduledAction(ScheduledAction.ActionType.BACKUP); scheduledBackup.setStartTime(LocalDateTime.now().minusDays(15).toDate().getTime()); scheduledBackup.setLastRun(LocalDateTime.now().minusDays(8).toDate().getTime()); long previousLastRun = scheduledBackup.getLastRunTime(); scheduledBackup.setExecutionCount(1); Recurrence recurrence = new Recurrence(PeriodType.WEEK); recurrence.setMultiplier(1); recurrence.setByDays(Collections.singletonList(Calendar.FRIDAY)); scheduledBackup.setRecurrence(recurrence); ExportParams backupParams = new ExportParams(ExportFormat.QIF); backupParams.setExportTarget(ExportParams.ExportTarget.SD_CARD); backupParams.setExportStartTime(new Timestamp(scheduledBackup.getStartTime())); scheduledBackup.setTag(backupParams.toCsv()); Transaction transaction = new Transaction("Orient palace"); Split split = new Split(new Money("10", Commodity.DEFAULT_COMMODITY.getCurrencyCode()), mBaseAccount.getUID()); split.setType(TransactionType.DEBIT); transaction.addSplit(split); transaction.addSplit(split.createPair(mTransferAccount.getUID())); mTransactionsDbAdapter.addRecord(transaction); File backupFolder = new File( Exporter.getExportFolderPath(BooksDbAdapter.getInstance().getActiveBookUID())); assertThat(backupFolder).exists(); assertThat(backupFolder.listFiles()).isEmpty(); List<ScheduledAction> actions = new ArrayList<>(); actions.add(scheduledBackup); ScheduledActionService.processScheduledActions(actions, mDb); assertThat(scheduledBackup.getExecutionCount()).isEqualTo(2); assertThat(scheduledBackup.getLastRunTime()).isGreaterThan(previousLastRun); assertThat(backupFolder.listFiles()).hasSize(1); assertThat(backupFolder.listFiles()[0].getName()).endsWith(".qif"); } @After public void tearDown(){ TransactionsDbAdapter.getInstance().deleteAllRecords(); } }
22,945
45.638211
141
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/testutil/ShadowCrashlytics.java
package org.gnucash.android.test.unit.testutil; import android.content.Context; import com.crashlytics.android.Crashlytics; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; /** * Shadow class for crashlytics to prevent logging during testing */ @Implements(Crashlytics.class) public class ShadowCrashlytics { @Implementation public static void start(Context context){ System.out.println("Shadowing crashlytics start"); //nothing to see here, move along } }
539
23.545455
65
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/testutil/ShadowUserVoice.java
package org.gnucash.android.test.unit.testutil; import android.content.Context; import com.uservoice.uservoicesdk.Config; import com.uservoice.uservoicesdk.UserVoice; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; /** * Shadow class for uservoice during testing */ @Implements(UserVoice.class) public class ShadowUserVoice { @Implementation public static void init(Config config, Context context){ //do nothing } }
491
21.363636
60
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/util/AmountParserTest.java
package org.gnucash.android.test.unit.util; import org.gnucash.android.util.AmountParser; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import java.text.ParseException; import java.util.Locale; import static org.assertj.core.api.Assertions.assertThat; public class AmountParserTest { private Locale mPreviousLocale; @Before public void setUp() throws Exception { mPreviousLocale = Locale.getDefault(); Locale.setDefault(Locale.US); } @After public void tearDown() throws Exception { Locale.setDefault(mPreviousLocale); } @Test public void testParseIntegerAmount() throws ParseException { assertThat(AmountParser.parse("123")).isEqualTo(new BigDecimal(123)); } @Test public void parseDecimalAmount() throws ParseException { assertThat(AmountParser.parse("123.45")).isEqualTo(new BigDecimal("123.45")); } @Test public void parseDecimalAmountWithDifferentSeparator() throws ParseException { Locale.setDefault(Locale.GERMANY); assertThat(AmountParser.parse("123,45")).isEqualTo(new BigDecimal("123.45")); } @Test(expected = ParseException.class) public void withGarbageAtTheBeginning_shouldFailWithException() throws ParseException { AmountParser.parse("asdf123.45"); } @Test(expected = ParseException.class) public void withGarbageAtTheEnd_shouldFailWithException() throws ParseException { AmountParser.parse("123.45asdf"); } @Test(expected = ParseException.class) public void emptyString_shouldFailWithException() throws ParseException { AmountParser.parse(""); } }
1,710
28.5
91
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/util/PreferencesHelperTest.java
/* * Copyright (c) 2016 Alceu Rodrigues Neto <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.util; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.PreferencesHelper; import org.gnucash.android.util.TimestampHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class PreferencesHelperTest { @Test public void shouldGetLastExportTimeDefaultValue() { final Timestamp lastExportTime = PreferencesHelper.getLastExportTime(); assertThat(lastExportTime).isEqualTo(TimestampHelper.getTimestampFromEpochZero()); } @Test public void shouldGetLastExportTimeCurrentValue() { final long goldenBoyBirthday = 1190136000L * 1000; final Timestamp goldenBoyBirthdayTimestamp = new Timestamp(goldenBoyBirthday); PreferencesHelper.setLastExportTime(goldenBoyBirthdayTimestamp); assertThat(PreferencesHelper.getLastExportTime()) .isEqualTo(goldenBoyBirthdayTimestamp); } }
1,977
39.367347
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/test/unit/util/TimestampHelperTest.java
/* * Copyright (c) 2016 Alceu Rodrigues Neto <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.test.unit.util; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.gnucash.android.util.TimestampHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class TimestampHelperTest { @Test public void shouldGetUtcStringFromTimestamp() { /** * The values used here are well known. * See https://en.wikipedia.org/wiki/Unix_time#Notable_events_in_Unix_time * for details. */ final long unixBillennium = 1_000_000_000 * 1000L; final String unixBillenniumUtcString = "2001-09-09 01:46:40.000"; final Timestamp unixBillenniumTimestamp = new Timestamp(unixBillennium); assertThat(TimestampHelper.getUtcStringFromTimestamp(unixBillenniumTimestamp)) .isEqualTo(unixBillenniumUtcString); final long the1234567890thSecond = 1234567890 * 1000L; final String the1234567890thSecondUtcString = "2009-02-13 23:31:30.000"; final Timestamp the1234567890thSecondTimestamp = new Timestamp(the1234567890thSecond); assertThat(TimestampHelper.getUtcStringFromTimestamp(the1234567890thSecondTimestamp)) .isEqualTo(the1234567890thSecondUtcString); } @Test public void shouldGetTimestampFromEpochZero() { Timestamp epochZero = TimestampHelper.getTimestampFromEpochZero(); assertThat(epochZero.getTime()).isZero(); } @Test public void shouldGetTimestampFromUtcString() { final long unixBillennium = 1_000_000_000 * 1000L; final String unixBillenniumUtcString = "2001-09-09 01:46:40"; final String unixBillenniumWithMillisecondsUtcString = "2001-09-09 01:46:40.000"; final Timestamp unixBillenniumTimestamp = new Timestamp(unixBillennium); assertThat(TimestampHelper.getTimestampFromUtcString(unixBillenniumUtcString)) .isEqualTo(unixBillenniumTimestamp); assertThat(TimestampHelper.getTimestampFromUtcString(unixBillenniumWithMillisecondsUtcString)) .isEqualTo(unixBillenniumTimestamp); final long the1234567890thSecond = 1234567890 * 1000L; final String the1234567890thSecondUtcString = "2009-02-13 23:31:30"; final String the1234567890thSecondWithMillisecondsUtcString = "2009-02-13 23:31:30.000"; final Timestamp the1234567890thSecondTimestamp = new Timestamp(the1234567890thSecond); assertThat(TimestampHelper.getTimestampFromUtcString(the1234567890thSecondUtcString)) .isEqualTo(the1234567890thSecondTimestamp); assertThat(TimestampHelper.getTimestampFromUtcString(the1234567890thSecondWithMillisecondsUtcString)) .isEqualTo(the1234567890thSecondTimestamp); } @Test public void shouldGetTimestampFromNow() { final long before = System.currentTimeMillis(); final long now = TimestampHelper.getTimestampFromNow().getTime(); final long after = System.currentTimeMillis(); assertThat(now).isGreaterThanOrEqualTo(before) .isLessThanOrEqualTo(after); } }
4,142
45.033333
114
java
gnucash-android
gnucash-android-master/app/src/test/java/org/gnucash/android/util/BackupManagerTest.java
package org.gnucash.android.util; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.importer.GncXmlImporter; import org.gnucash.android.test.unit.testutil.ShadowCrashlytics; import org.gnucash.android.test.unit.testutil.ShadowUserVoice; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.xml.sax.SAXException; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; @RunWith(RobolectricTestRunner.class) //package is required so that resources can be found in dev mode @Config(sdk = 21, packageName = "org.gnucash.android", shadows = {ShadowCrashlytics.class, ShadowUserVoice.class}) public class BackupManagerTest { private BooksDbAdapter mBooksDbAdapter; @Before public void setUp() throws Exception { mBooksDbAdapter = BooksDbAdapter.getInstance(); mBooksDbAdapter.deleteAllRecords(); assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(0); } @Test public void backupAllBooks() throws Exception { String activeBookUID = createNewBookWithDefaultAccounts(); BookUtils.activateBook(activeBookUID); createNewBookWithDefaultAccounts(); assertThat(mBooksDbAdapter.getRecordsCount()).isEqualTo(2); BackupManager.backupAllBooks(); for (String bookUID : mBooksDbAdapter.getAllBookUIDs()) { assertThat(BackupManager.getBackupList(bookUID).size()).isEqualTo(1); } } @Test public void getBackupList() throws Exception { String bookUID = createNewBookWithDefaultAccounts(); BookUtils.activateBook(bookUID); BackupManager.backupActiveBook(); Thread.sleep(1000); // FIXME: Use Mockito to get a different date in Exporter.buildExportFilename BackupManager.backupActiveBook(); assertThat(BackupManager.getBackupList(bookUID).size()).isEqualTo(2); } @Test public void whenNoBackupsHaveBeenDone_shouldReturnEmptyBackupList() { String bookUID = createNewBookWithDefaultAccounts(); BookUtils.activateBook(bookUID); assertThat(BackupManager.getBackupList(bookUID)).isEmpty(); } /** * Creates a new database with default accounts * @return The book UID for the new database * @throws RuntimeException if the new books could not be created */ private String createNewBookWithDefaultAccounts(){ try { return GncXmlImporter.parse(GnuCashApplication.getAppContext().getResources().openRawResource(R.raw.default_accounts)); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create default accounts"); } } }
3,024
35.445783
131
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/AggregateAllCases.java
package org.services.analysis; import java.io.*; import java.util.ArrayList; import java.util.List; public class AggregateAllCases { private static String ROOT_DIR = "C:\\Users\\dingding\\Desktop\\faults\\F13\\step3_fault_shiviz_traces"; private static String SINGLEAGGREGATEFILENAME = "all.txt"; private static String ALLAGGREGATEFILENAME = "AllCasesResult.txt"; public static void main(String[] args){ String destFilePath = String.format("%s\\%s",ROOT_DIR,ALLAGGREGATEFILENAME); File destFile = new File(destFilePath); try { destFile.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(destFile); List<File> dirList = getTestCaseDirList(ROOT_DIR);//Get case1, case2... directory for (int index1 = 0; index1 < dirList.size(); index1++) { File file = new File(String.format("%s\\%s\\%s",ROOT_DIR,dirList.get(index1).getName(),SINGLEAGGREGATEFILENAME)); StringBuilder sb = new StringBuilder(); InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); BufferedReader br = new BufferedReader(reader); String line = null; while((line = br.readLine())!=null){ sb.append(line); sb.append("\r\n"); } reader.close(); fileOutputStream.write(sb.toString().getBytes()); } fileOutputStream.close(); } catch (Exception e){ e.printStackTrace(); } } //Get all the test case directory private static ArrayList<File> getTestCaseDirList(String path) { ArrayList<File> testDirs = new ArrayList<File>(); File rootDir = new File(path); File[] dirList = rootDir.listFiles(); for (int i = 0; i < dirList.length; i++) { File file = dirList[i]; if (file.isDirectory()) testDirs.add(file); } return testDirs; } //Get all the shiviz txt file private static ArrayList<File> getListFiles(Object obj) { File directory = null; if (obj instanceof File) { directory = (File) obj; } else { directory = new File(obj.toString()); } ArrayList<File> files = new ArrayList<File>(); if (directory.isFile()) { files.add(directory); return files; } else if (directory.isDirectory()) { File[] fileArr = directory.listFiles(); for (int i = 0; i < fileArr.length; i++) { File fileOne = fileArr[i]; if (fileOne.getName().endsWith(".txt")) { files.addAll(getListFiles(fileOne)); } } } return files; } }
2,875
36.842105
129
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/AggregateEachCase.java
package org.services.analysis; import java.io.*; import java.util.ArrayList; import java.util.List; public class AggregateEachCase { private static String ROOT_DIR = "C:\\Users\\dingding\\Desktop\\tse debug exp\\F20\\shiviz\\4 scope failure elements\\shiviz_trace"; private static String AGGREGATEFILENAME = "all.txt"; public static void main(String[] args){ List<File> dirList = getTestCaseDirList(ROOT_DIR);//Get case1, case2... directory for (int index1 = 0; index1 < dirList.size(); index1++) { String dirName = dirList.get(index1).getName();//case1, for example String destDir = String.format("%s\\%s", ROOT_DIR, dirName); String destFilePath = String.format("%s\\%s",destDir,AGGREGATEFILENAME); File destFile = new File(destFilePath); try { destFile.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(destFile); List<File> subDirList = getTestCaseDirList(destDir);//Get fail1,fail2... directory System.out.println(subDirList); for (int index2 = 0; index2 < subDirList.size(); index2++) { List<File> fileLists = getListFiles(subDirList.get(index2)); //Aggreate all of the txt file for (int x = 0; x < fileLists.size(); x++) { File file = fileLists.get(x); StringBuilder sb = new StringBuilder(); InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); BufferedReader br = new BufferedReader(reader); String line = null; while((line = br.readLine())!=null){ sb.append(line); sb.append("\r\n"); } reader.close(); fileOutputStream.write(sb.toString().getBytes()); } } fileOutputStream.close(); } catch(Exception e){ e.printStackTrace(); } } } //Get all the test case directory private static ArrayList<File> getTestCaseDirList(String path) { ArrayList<File> testDirs = new ArrayList<File>(); File rootDir = new File(path); File[] dirList = rootDir.listFiles(); for (int i = 0; i < dirList.length; i++) { File file = dirList[i]; if (file.isDirectory()) testDirs.add(file); } return testDirs; } //Get all the shiviz txt file private static ArrayList<File> getListFiles(Object obj) { File directory = null; if (obj instanceof File) { directory = (File) obj; } else { directory = new File(obj.toString()); } ArrayList<File> files = new ArrayList<File>(); if (directory.isFile()) { files.add(directory); return files; } else if (directory.isDirectory()) { File[] fileArr = directory.listFiles(); for (int i = 0; i < fileArr.length; i++) { File fileOne = fileArr[i]; if (fileOne.getName().endsWith(".txt")) { files.addAll(getListFiles(fileOne)); } } } return files; } }
3,470
38.443182
136
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/App.java
/* * This Java source file was generated by the Gradle 'init' task. */ package org.services.analysis; public class App { public String getGreeting() { return "Hello world."; } // public static void main(String[] args) { // System.out.println(new App().getGreeting()); // } }
310
17.294118
65
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/CalculateEventAndNode.java
package org.services.analysis; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CalculateEventAndNode { private static String ROOT_DIR = "C:\\Users\\dingding\\Desktop\\tse debug exp\\F20\\shiviz\\4 scope failure elements\\shiviz_trace"; private static String caseDirectory = "case1"; private static String fileName = "all.txt"; private static Pattern patternEvent = Pattern.compile("\\{traceId=.*spanId=.*event=.*\\}"); private static Pattern patternNode = Pattern.compile("host=(\\S*),"); private static HashSet<String> nodes = new HashSet<String>(); public static void main(String[] args){ try { int count = 0; File file = new File(String.format("%s\\%s\\%s",ROOT_DIR,caseDirectory,fileName)); InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); BufferedReader br = new BufferedReader(reader); String line = null; while((line = br.readLine())!=null){ Matcher matcherEvent = patternEvent.matcher(line); if(matcherEvent.find()) { System.out.println(line); count ++; Matcher matcherNode = patternNode.matcher(line); if(matcherNode.find()){ nodes.add(matcherNode.group(1)); } } } System.out.println(nodes); System.out.println(String.format("The number of event is [%d]", count)); System.out.println(String.format("The number of node is [%d]", nodes.size())); reader.close(); } catch (Exception e){ e.printStackTrace(); } } }
1,906
37.14
136
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/CallAnalysis.java
/* * This Java source file was generated by the Gradle 'init' task. */ package org.services.analysis; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.json.JSONArray; import org.json.JSONObject; public class CallAnalysis { public static void main(String[] args) { HashMap<String, HashMap<String, Object>> traces = new HashMap<String, HashMap<String, Object>>(); List<String> pListAll = new ArrayList<String>(); String traceStr = readFile("./sample/traces-error-normal.json"); JSONArray tracelist = new JSONArray(traceStr); for (int k = 0; k < tracelist.length(); k++) { JSONArray traceobj = (JSONArray) tracelist.get(k); // String call = readFile("./sample/call1x.json"); // JSONArray spanlist = new JSONArray(call); List<HashMap<String, String>> serviceList = new ArrayList<HashMap<String, String>>(); String traceId = ((JSONObject) traceobj.get(0)).getString("traceId"); for (int j = 0; j < traceobj.length(); j++) { JSONObject spanobj = (JSONObject) traceobj.get(j); // String traceId = spanobj.getString("traceId"); String id = spanobj.getString("id"); String pid = ""; if (spanobj.has("parentId")) { pid = spanobj.getString("parentId"); } String name = spanobj.getString("name"); HashMap<String, String> content = new HashMap<String, String>(); content.put("spanid", id); content.put("parentid", pid); content.put("spanname", name); if(spanobj.has("annotations")){ JSONArray annotations = spanobj.getJSONArray("annotations"); for (int i = 0; i < annotations.length(); i++) { JSONObject anno = annotations.getJSONObject(i); if ("sr".equals(anno.getString("value"))) { JSONObject endpoint = anno.getJSONObject("endpoint"); String service = endpoint.getString("serviceName"); content.put("service", service); } } if (name.contains("message:")) { if ("message:input".equals(name)) { content.put("api", content.get("service") + "." + "message_received"); } } else { JSONArray binaryAnnotations = spanobj.getJSONArray("binaryAnnotations"); for (int i = 0; i < binaryAnnotations.length(); i++) { JSONObject anno = binaryAnnotations.getJSONObject(i); if ("error".equals(anno.getString("key"))) { content.put("error", anno.getString("value")); } if ("mvc.controller.class".equals(anno.getString("key")) && !"BasicErrorController".equals(anno.getString("value"))) { String classname = anno.getString("value"); content.put("classname", classname); } if ("mvc.controller.method".equals(anno.getString("key")) && !"errorHtml".equals(anno.getString("value"))) { String methodname = anno.getString("value"); content.put("methodname", methodname); } } content.put("api", content.get("service") + "." + content.get("classname") + "." + content.get("methodname")); } serviceList.add(content); } } // filter validate service api List<HashMap<String, String>> processList = serviceList.stream() .filter(elem -> !"message:output".equals(elem.get("spanname"))).collect(Collectors.toList()); // processList.stream().forEach(n -> System.out.println(n)); boolean failed = processList.stream().anyMatch(pl -> pl.containsKey("error")); // final info List<String> pList = processList.stream().map(pl -> { return pl.get("api"); }).collect(Collectors.toList()); pList.stream().forEach(n -> System.out.println(n)); pListAll.addAll(pList); HashMap<String, Object> traceContent = new HashMap<String, Object>(); traceContent.put("failed", failed); traceContent.put("list", pList); traces.put(traceId, traceContent); } // traces.forEach((key, val) -> System.out.println(val)); System.out.println("---------------result-------------------"); //all double N = traces.keySet().size(); //failed double NF = traces.values().stream().filter(trace->{ return (Boolean)trace.get("failed"); }).collect(Collectors.toList()).size(); double NS = N - NF; System.out.println("Failed cases: " + NF); System.out.println("Success cases: " + NS); //method/spectrum list pListAll = pListAll.stream().distinct().collect(Collectors.toList()); // methods.stream().forEach(n -> System.out.println(n)); HashMap<String, Double> pListNCF = new HashMap<String, Double>(); pListAll.stream().forEach(pl -> pListNCF.put(pl, 0.0)); HashMap<String, Double> pListNCS = new HashMap<String, Double>(); pListAll.stream().forEach(pl -> pListNCS.put(pl, 0.0)); traces.values().stream().forEach(trace->{ List<String> pList = (List<String>)trace.get("list"); if((Boolean)trace.get("failed")){ pList.stream().forEach(pl -> pListNCF.put(pl, pListNCF.get(pl)+1)); }else{ pList.stream().forEach(pl -> pListNCS.put(pl, pListNCS.get(pl)+1)); } }); // System.out.println(pListNCF); // System.out.println(pListNCS); //calculate Suspiciousness //NCF/NF // NCF/NF + NCS/NS //NCF // sqrt(NF*(NCF + NCS)) HashMap<String, Double> pListSuspicious = new HashMap<String, Double>(); pListAll.stream().forEach(pl -> { // double susp = (pListNCF.get(pl)/NF) / (pListNCF.get(pl)/NF + pListNCS.get(pl)/NS); double susp = (pListNCF.get(pl)) / Math.sqrt(NF*(pListNCF.get(pl) + pListNCS.get(pl))); pListSuspicious.put(pl, susp); }); // System.out.println(pListSuspicious); Map<String, Double> result = pListSuspicious.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); result.entrySet().stream().forEach(System.out::println); // System.out.println(result); } public static String readFile(String path) { File file = new File(path); BufferedReader reader = null; String laststr = ""; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; while ((tempString = reader.readLine()) != null) { laststr = laststr + tempString; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } return laststr; } }
6,693
33.153061
99
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/Clock.java
package org.services.analysis; import java.util.HashMap; /** * Created by Administrator on 2017/7/18. */ public class Clock { private String type; private String host; private String src; private String traceId; private String spanId; private String parentId; private HashMap<String,Integer> clock; public Clock(String type, String host, String src, String traceId, String spanId, String parentId, HashMap<String,Integer> clock) { this.type = type; this.host = host; this.src = src; this.traceId = traceId; this.spanId = spanId; this.parentId = parentId; this.clock = clock; } public HashMap<String,Integer> getClock() { return clock; } public boolean isSrc(String traceId, String spanId, String type, String queue, String parentId){ boolean result = false; if("queue".equals(queue)){ if(traceId.equals(this.traceId) && parentId.equals(this.spanId)){ if(type.equals("sr") && this.type.equals("cs")){ result = true; } } }else{ if(traceId.equals(this.traceId) && spanId.equals(this.spanId)){ if(type.equals("sr") && this.type.equals("cs")){ result = true; }else if(type.equals("cr") && this.type.equals("ss")){ result = true; } } } return result; } }
1,505
25.892857
135
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/Span.java
package org.services.analysis; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Administrator on 2017/7/22. */ public class Span { private String traceId; private String spanId; private String parentId; private String spanname; private List<String> childs; private List<HashMap<String,String>> logs; public Span(String traceId, String spanId, String parentId, String spanname) { this.traceId = traceId; this.spanId = spanId; this.parentId = parentId; this.spanname = spanname; logs = new ArrayList<HashMap<String,String>>(); } public void addLog(HashMap<String,String> log){ logs.add(log); } public List<HashMap<String,String>> getLogs(){ return logs; } public String getTraceId() { return traceId; } public String getSpanId() { return spanId; } public String getParentId() { return parentId; } public List<String> getChilds() { return childs; } public void setChilds(List<String> childs) { this.childs = childs; } public void addChild(String childId){ childs.add(childId); } public String getSpanname() { return spanname; } public void setSpanname(String spanname) { this.spanname = spanname; } }
1,390
20.075758
82
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/Test.java
package org.services.analysis; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { private static String SRC_DIR = "D:\\workspace\\microservice\\faults\\F1\\step2_fault_origin_traces"; public static void main(String[] args){ String mircroServiceName = "{traceId=1b114102c6306ef8, spanId=1b114102c6306ef8, hostName=ts-order-service, destName=null, host=ts-order-service, clock={\"ts-order-service\":4,\"ts-sso-service\":2}, dest=null, event=ts-order-service.OrderController.queryOrders, type=ss, parentId=, timestamp=1516255241135800, }"; Pattern patternNode = Pattern.compile("host=(\\S*),"); Matcher matcherCase = patternNode.matcher(mircroServiceName); if(matcherCase.find()){ System.out.println(matcherCase.group(1)); } } //Get all the test case directory private static ArrayList<File> getTestCaseDirList(String path){ ArrayList<File> testDirs = new ArrayList<File>(); File rootDir = new File(path); File[] dirList = rootDir.listFiles(); for (int i = 0; i < dirList.length; i++) { File file = dirList[i]; if(file.isDirectory()) testDirs.add(file); } return testDirs; } }
1,348
38.676471
320
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/TraceTranslator.java
package org.services.analysis; ///** // * Created by hh on 2017-07-08. // */ ///** // * Created by Administrator on 2017/7/11. // */ import java.io.*; import java.sql.Timestamp; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by hh on 2017-07-08. */ public class TraceTranslator { // private static String SRC_DIR = "F:\\gitwork\\fault_replicate\\faults-dingding\\F2\\step2_fault_origin_traces"; private static String SRC_DIR = "./example/zipkin_log"; private static String DEST_DIR = "./example/shiviz_log"; // private static String DEST_DIR = "F:\\gitwork\\fault_replicate\\faults-dingding\\F2\\step3_fault_shiviz_traces"; public static void main(String[] args) throws JSONException { List<File> dirList = getTestCaseDirList(SRC_DIR);//Get case1, case2... directory for (int index1 = 0; index1 < dirList.size(); index1++) { String dirName = dirList.get(index1).getName();//case1, for example //Get the test case number Pattern patternCaseNumber = Pattern.compile("case([0-9]+)"); Matcher matcherCaseNumber = patternCaseNumber.matcher(dirName); int testCaseNumber = 0; if(matcherCaseNumber.find()) testCaseNumber = Integer.parseInt(matcherCaseNumber.group(1)); List<File> subDirList = getTestCaseDirList(String.format("%s\\%s", SRC_DIR, dirName));//Get fail1,fail2... directory System.out.println(subDirList); for (int index2 = 0; index2 < subDirList.size(); index2++) { /** * Begin */ String subDirName = subDirList.get(index2).getName(); List<File> fileLists = getListFiles(subDirList.get(index2)); String destDir = String.format("%s\\%s\\%s",DEST_DIR,dirName,subDirName); //Create the output directory File outputDir = new File(destDir); if(!outputDir.exists()) outputDir.mkdirs(); for (int x = 0; x < fileLists.size(); x++) { File file = fileLists.get(x); String path = file.getPath(); String microserviceName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); String traceStr = readFile(path); JSONArray tracelist = new JSONArray(traceStr); List<HashMap<String, String>> logs = new ArrayList<HashMap<String, String>>(); HashMap<String, String> states = new HashMap<String, String>(); JSONArray traceobj = tracelist; List<HashMap<String, String>> serviceList = new ArrayList<HashMap<String, String>>(); String traceId = ((JSONObject) traceobj.get(0)).getString("traceId"); for (int j = 0; j < traceobj.length(); j++) { JSONObject spanobj = (JSONObject) traceobj.get(j); String id = spanobj.getString("id"); String pid = ""; if (spanobj.has("parentId")) { pid = spanobj.getString("parentId"); } String name = spanobj.getString("name"); String time = String.valueOf(spanobj.getLong("timestamp")); HashMap<String, String> content = new HashMap<String, String>(); content.put("traceId", traceId); content.put("spanid", id); content.put("parentid", pid); content.put("spanname", name); //annotation if (spanobj.has("annotations")) { JSONArray annotations = spanobj.getJSONArray("annotations"); for (int i = 0; i < annotations.length(); i++) { JSONObject anno = annotations.getJSONObject(i); if ("cs".equals(anno.getString("value"))) { JSONObject endpoint = anno.getJSONObject("endpoint"); String service = endpoint.getString("serviceName"); content.put("clientName", service); String csTime = String.valueOf(anno.getLong("timestamp")); content.put("csTime", csTime); } if ("sr".equals(anno.getString("value"))) { JSONObject endpoint = anno.getJSONObject("endpoint"); String service = endpoint.getString("serviceName"); content.put("serverName", service); String srTime = String.valueOf(anno.getLong("timestamp")); content.put("srTime", srTime); } if ("ss".equals(anno.getString("value"))) { JSONObject endpoint = anno.getJSONObject("endpoint"); String service = endpoint.getString("serviceName"); content.put("serverName", service); String ssTime = String.valueOf(anno.getLong("timestamp")); content.put("ssTime", ssTime); } if ("cr".equals(anno.getString("value"))) { JSONObject endpoint = anno.getJSONObject("endpoint"); String service = endpoint.getString("serviceName"); content.put("clientName", service); String crTime = String.valueOf(anno.getLong("timestamp")); content.put("crTime", crTime); } } } //if annotation doesn't exist if (!spanobj.has("annotations")) { content.put("time", time); } JSONArray binaryAnnotations = spanobj.getJSONArray("binaryAnnotations"); for (int i = 0; i < binaryAnnotations.length(); i++) { JSONObject anno = binaryAnnotations.getJSONObject(i); if ("error".equals(anno.getString("key"))) { content.put("error", anno.getString("value")); } if ("mvc.controller.class".equals(anno.getString("key")) && !"BasicErrorController".equals(anno.getString("value"))) { String classname = anno.getString("value"); content.put("classname", classname); } if ("mvc.controller.method".equals(anno.getString("key")) && !"errorHtml".equals(anno.getString("value"))) { String methodname = anno.getString("value"); content.put("methodname", methodname); } if ("spring.instance_id".equals(anno.getString("key"))) { String instance_id = anno.getString("value"); JSONObject endpoint = anno.getJSONObject("endpoint"); String ipv4 = endpoint.getString("ipv4"); if (content.get("serverName") != null && instance_id.indexOf(content.get("serverName")) != -1) { String key = content.get("serverName") + ":" + ipv4; String new_instance_id; if (states.containsKey(key)) { new_instance_id = content.get("serverName") + ":" + states.get(key); } else { new_instance_id = content.get("serverName"); } content.put("server_instance_id", new_instance_id); } if (content.get("clientName") != null && instance_id.indexOf(content.get("clientName")) != -1) { String key = content.get("clientName") + ":" + ipv4; String new_instance_id; if (states.containsKey(key)) { new_instance_id = content.get("clientName") + ":" + states.get(key); } else { new_instance_id = content.get("clientName"); } content.put("client_instance_id", new_instance_id); } } if ("http.method".equals(anno.getString("key"))) { String httpMethod = anno.getString("value"); content.put("httpMethod", httpMethod); } if ("class".equals(anno.getString("key"))) { String c = anno.getString("value"); content.put("class", c); JSONObject endpoint = anno.getJSONObject("endpoint"); String ipv4 = endpoint.getString("ipv4"); String port = String.valueOf(endpoint.get("port")); String serviceName = String.valueOf(endpoint.get("serviceName")); String hostId = serviceName; content.put("hostId", hostId); content.put("serviceName", serviceName); } if ("method".equals(anno.getString("key"))) { String method = anno.getString("value"); content.put("method", method); JSONObject endpoint = anno.getJSONObject("endpoint"); String ipv4 = endpoint.getString("ipv4"); String port = String.valueOf(endpoint.get("port")); String serviceName = String.valueOf(endpoint.get("serviceName")); String hostId = serviceName; content.put("hostId", hostId); content.put("serviceName", serviceName); } if ("controller_state".equals(anno.getString("key"))) { String state = anno.getString("value"); JSONObject endpoint = anno.getJSONObject("endpoint"); String ipv4 = endpoint.getString("ipv4"); String serviceName = String.valueOf(endpoint.get("serviceName")); content.put("state", state); content.put("ipv4State", ipv4); content.put("serviceNameState", serviceName); states.put(serviceName + ":" + ipv4, state); } } if (content.get("serverName") != null && (content.get("classname") != null || content.get("methodname") != null)) { content.put("api", content.get("serverName") + "." + content.get("classname") + "." + content.get("methodname")); } else if (content.get("hostId") != null && (content.get("class") != null || content.get("method") != null)) { content.put("api", content.get("hostId") + "." + content.get("class") + "." + content.get("method")); } if (name.contains("message:")) { if (content.get("serverName") != null) { if ("message:input".equals(name)) { content.put("api", content.get("serverName") + "." + "message_received"); } else if ("message:output".equals(name)) { content.put("api", content.get("serverName") + "." + "message_send"); } } else if (content.get("clientName") != null) { if ("message:input".equals(name)) { content.put("api", content.get("clientName") + "." + "message_received"); } else if ("message:output".equals(name)) { content.put("api", content.get("clientName") + "." + "message_send"); } } } serviceList.add(content); } serviceList.forEach(n -> { if (n.get("csTime") != null) { HashMap<String, String> log = new HashMap<String, String>(); log.put("traceId", n.get("traceId")); log.put("spanId", n.get("spanid")); log.put("parentId", n.get("parentid")); log.put("timestamp", n.get("csTime")); log.put("hostName", n.get("clientName")); log.put("host", n.get("client_instance_id")); log.put("destName", n.get("serverName")); log.put("dest", n.get("server_instance_id")); log.put("api", n.get("api")); log.put("spanname", n.get("spanname")); if (n.get("spanname").contains("message:")) { log.put("event", n.get("api")); log.put("queue", "queue"); } else { log.put("event", ""); } log.put("type", "cs"); if (null != n.get("api")) { log.put("api", n.get("api")); } if (n.containsKey("error")) { log.put("error", n.get("error")); } logs.add(log); } if (n.get("srTime") != null) { HashMap<String, String> log = new HashMap<String, String>(); log.put("traceId", n.get("traceId")); log.put("spanId", n.get("spanid")); log.put("parentId", n.get("parentid")); log.put("timestamp", n.get("srTime")); log.put("hostName", n.get("serverName")); log.put("host", n.get("server_instance_id")); log.put("srcName", n.get("clientName")); log.put("src", n.get("client_instance_id")); log.put("api", n.get("api")); log.put("spanname", n.get("spanname")); log.put("event", n.get("api")); log.put("type", "sr"); if (n.containsKey("error")) { log.put("error", n.get("error")); } if (n.get("spanname").contains("message:")) { log.put("queue", "queue"); } logs.add(log); } if (n.get("ssTime") != null) { HashMap<String, String> log = new HashMap<String, String>(); log.put("traceId", n.get("traceId")); log.put("spanId", n.get("spanid")); log.put("parentId", n.get("parentid")); log.put("timestamp", n.get("ssTime")); log.put("hostName", n.get("serverName")); log.put("host", n.get("server_instance_id")); log.put("destName", n.get("clientName")); log.put("dest", n.get("client_instance_id")); log.put("api", n.get("api")); log.put("spanname", n.get("spanname")); log.put("event", n.get("api")); log.put("type", "ss"); if (n.containsKey("error")) { log.put("error", n.get("error")); } if (n.get("spanname").contains("message:")) { log.put("queue", "queue"); } logs.add(log); } if (n.get("crTime") != null) { HashMap<String, String> log = new HashMap<String, String>(); log.put("traceId", n.get("traceId")); log.put("spanId", n.get("spanid")); log.put("parentId", n.get("parentid")); log.put("timestamp", n.get("crTime")); log.put("hostName", n.get("clientName")); log.put("host", n.get("client_instance_id")); log.put("srcName", n.get("serverName")); log.put("src", n.get("server_instance_id")); log.put("api", n.get("api")); log.put("spanname", n.get("spanname")); if (n.get("spanname").contains("message:")) { log.put("event", n.get("api")); log.put("queue", "queue"); } else { log.put("event", ""); } log.put("type", "cr"); if (n.containsKey("error")) { log.put("error", n.get("error")); } logs.add(log); } if (n.get("time") != null) { HashMap<String, String> log = new HashMap<String, String>(); log.put("traceId", n.get("traceId")); log.put("spanId", n.get("spanid")); log.put("parentId", n.get("parentid")); log.put("timestamp", n.get("time")); log.put("hostName", n.get("serviceName")); log.put("host", n.get("hostId")); log.put("api", n.get("api")); log.put("spanname", n.get("spanname")); log.put("event", n.get("api")); log.put("type", "async"); if (n.containsKey("error")) { log.put("error", n.get("error")); } if (n.get("spanname").contains("message:")) { log.put("queue", "queue"); } logs.add(log); } }); HashMap<String, String> traceIds = new HashMap<String, String>(); logs.forEach(n -> { if (!traceIds.containsKey(n.get("traceId"))) { traceIds.put(n.get("traceId"), ""); } }); List<List<HashMap<String, String>>> list = new ArrayList<List<HashMap<String, String>>>(); HashMap<List<HashMap<String, String>>, Boolean> failures = new HashMap<List<HashMap<String, String>>, Boolean>(); traceIds.forEach((n, s) -> { List l = logs.stream().filter(elem -> { return n.equals(elem.get("traceId")); }).collect(Collectors.toList()); List<HashMap<String, String>> listWithClock = clock2(l); boolean failed = listWithClock.stream().anyMatch(pl -> pl.containsKey("error")); failures.put(listWithClock, failed); list.add(listWithClock); }); List<List<HashMap<String, String>>> listSorted = sortListByTime(list); listSorted.forEach(n -> { System.out.println("event number:" + n.size()); }); String fileName = getFileName(file.getName()); writeFile(String.format("%s\\shiviz-%s.txt",destDir,fileName), listSorted, subDirName, microserviceName, testCaseNumber); } /** * End */ } } } private static String getFileName(String origin) { String name; String prefix = origin.substring(origin.lastIndexOf(".")); int num = prefix.length();//得到后缀名长度 name = origin.substring(0, origin.length() - num); return name; } //Get all the test case directory private static ArrayList<File> getTestCaseDirList(String path) { ArrayList<File> testDirs = new ArrayList<File>(); File rootDir = new File(path); File[] dirList = rootDir.listFiles(); for (int i = 0; i < dirList.length; i++) { File file = dirList[i]; if (file.isDirectory()) testDirs.add(file); } return testDirs; } private static ArrayList<File> getListFiles(Object obj) { File directory = null; if (obj instanceof File) { directory = (File) obj; } else { directory = new File(obj.toString()); } ArrayList<File> files = new ArrayList<File>(); if (directory.isFile()) { files.add(directory); return files; } else if (directory.isDirectory()) { File[] fileArr = directory.listFiles(); for (int i = 0; i < fileArr.length; i++) { File fileOne = fileArr[i]; if (fileOne.getName().endsWith(".json")) { files.addAll(getListFiles(fileOne)); } } } return files; } private static List<List<HashMap<String, String>>> sortListByTime(List<List<HashMap<String, String>>> list) { List<List<HashMap<String, String>>> result = new ArrayList<List<HashMap<String, String>>>(); Iterator<List<HashMap<String, String>>> iterator = list.iterator(); List<HashMap<String, String>> logs; HashMap<String, String> log; HashMap<String, String> times = new HashMap<String, String>(); HashMap<String, List<HashMap<String, String>>> traceIdAndList = new HashMap<String, List<HashMap<String, String>>>(); while (iterator.hasNext()) { logs = iterator.next(); log = logs.get(0); String traceId = log.get("traceId"); traceIdAndList.put(traceId, logs); for (HashMap<String, String> stringStringHashMap : logs) { if (stringStringHashMap.get("spanId").equals(traceId)) { times.put(stringStringHashMap.get("timestamp"), traceId); break; } } // if(!times.containsKey(traceId)){ // for (HashMap<String, String> stringStringHashMap : logs) { // if(stringStringHashMap.get("parentId").equals(traceId)){ // times.put(stringStringHashMap.get("timestamp"), traceId); // break; // } // } // } } Long[] timestamps = new Long[times.size()]; Iterator<String> iterator1 = times.keySet().iterator(); for (int i = 0; i < timestamps.length; i++) { timestamps[i] = Long.valueOf(iterator1.next()); } Arrays.sort(timestamps); for (int i = 0; i < timestamps.length; i++) { String traceId1 = times.get(String.valueOf(timestamps[i])); result.add(traceIdAndList.get(traceId1)); } return result; } public static HashMap<String, Integer> findSrcClock(List<Clock> allClocks, String traceId, String spanId, String type, String queue, String parentId) { HashMap<String, Integer> clock = null; Clock item; for (int i = allClocks.size() - 1; i >= 0; i--) { item = allClocks.get(i); if (item.isSrc(traceId, spanId, type, queue, parentId)) { clock = item.getClock(); break; } } if (clock == null) { System.out.println(); } return (HashMap<String, Integer>) clock.clone(); } //sort the log for one trace according to the calling sequences public static List<HashMap<String, String>> sortLog(List<HashMap<String, String>> logs) { // List<HashMap<String,String>> list = logs.stream().sorted((log1,log2) -> { // Long time1 = Long.valueOf(log1.get("timestamp")); // Long time2 = Long.valueOf(log2.get("timestamp")); // return time1.compareTo(time2); // }).collect(Collectors.toList()); List<HashMap<String, String>> list = null; HashMap<String, String> log = logs.get(0); String traceId = log.get("traceId"); HashMap<String, Span> spans = new HashMap<String, Span>(); HashMap<String, List<String>> spanRelation = new HashMap<String, List<String>>(); logs.forEach(n -> { String spanId = n.get("spanId"); if (spans.containsKey(spanId)) { Span span = spans.get(spanId); span.addLog(n); } else { Span span = new Span(n.get("traceId"), n.get("spanId"), n.get("parentId"), n.get("spanname")); span.addLog(n); spans.put(spanId, span); } if (spanRelation.containsKey(n.get("parentId"))) { List<String> childs = spanRelation.get(n.get("parentId")); if (!childs.contains(spanId)) { childs.add(spanId); } } else { List<String> childs = new ArrayList<String>(); childs.add(spanId); spanRelation.put(n.get("parentId"), childs); } }); //add the event for cs & cr HashMap<String, String> apis = new HashMap<String, String>(); logs.forEach(n -> { String api = n.get("api"); apis.put(n.get("spanId"), n.get("api")); }); logs.forEach(n -> { if ("cs".equals(n.get("type")) || "cr".equals(n.get("type"))) { if ("".equals(n.get("event"))) { n.put("event", apis.get(n.get("parentId"))); } } else if ("sr".equals(n.get("type")) || "ss".equals(n.get("type"))) { n.put("event", n.get("api")); } else if ("async".equals(n.get("type"))) { n.put("event", n.get("api")); } n.remove("api"); }); List<HashMap<String, String>> forwardLogs = new ArrayList<HashMap<String, String>>(); List<HashMap<String, String>> backwardLogs = new ArrayList<HashMap<String, String>>(); List<Span> sortedSpan = new ArrayList<Span>(); Span entrance = spans.get(traceId); if (entrance == null) { Iterator<Map.Entry<String, Span>> entries = spans.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, Span> entry = entries.next(); Span span = entry.getValue(); if (traceId.equals(span.getParentId())) { entrance = span; break; } } } setChilds(spanRelation, entrance, spans); traverse(entrance, forwardLogs, backwardLogs, spans); forwardLogs = mergeForwardAndBackwardLogs(forwardLogs, backwardLogs); forwardLogs.forEach(n -> { n.remove("spanname"); }); return forwardLogs; } public static void setChilds(HashMap<String, List<String>> spanRelation, Span entrance, HashMap<String, Span> spans) { Span s = entrance; //Queue,add the src and srcName for queue receive(sr),dest& destName for queue send(cs) if ("message:input".equals(s.getSpanname())) { Span parent = spans.get(s.getParentId()); HashMap<String, String> parentCs = null; HashMap<String, String> sr = null; Iterator<HashMap<String, String>> parentIterator = parent.getLogs().iterator(); while (parentIterator.hasNext()) { HashMap<String, String> log = parentIterator.next(); if ("cs".equals(log.get("type"))) { parentCs = log; break; } } Iterator<HashMap<String, String>> sIterator = s.getLogs().iterator(); while (sIterator.hasNext()) { HashMap<String, String> log = sIterator.next(); if ("sr".equals(log.get("type"))) { sr = log; break; } } if (sr != null && parentCs != null) { sr.put("src", parentCs.get("host")); sr.put("srcName", parentCs.get("hostName")); parentCs.put("dest", sr.get("host")); parentCs.put("destName", sr.get("hostName")); } else { System.out.println(sr); System.out.println(parentCs); } } if (spanRelation.containsKey(s.getSpanId())) { s.setChilds(spanRelation.get(s.getSpanId())); Iterator<String> iterator = s.getChilds().iterator(); while (iterator.hasNext()) { String childId = iterator.next(); s = spans.get(childId); setChilds(spanRelation, s, spans); } } } public static void traverse(Span entrance, List<HashMap<String, String>> forwardLogs, List<HashMap<String, String>> backwardLogs, HashMap<String, Span> spans) { //from the entrance to end Span s = entrance; HashMap<String, String> cs = null; HashMap<String, String> sr = null; HashMap<String, String> ss = null; HashMap<String, String> cr = null; HashMap<String, String> async = null; Iterator<HashMap<String, String>> iterator = s.getLogs().iterator(); while (iterator.hasNext()) { HashMap<String, String> log1 = iterator.next(); if ("cs".equals(log1.get("type"))) { cs = log1; } if ("sr".equals(log1.get("type"))) { sr = log1; } if ("ss".equals(log1.get("type"))) { ss = log1; } if ("cr".equals(log1.get("type"))) { cr = log1; } if ("async".equals(log1.get("type"))) { async = log1; } } if (cs != null) { forwardLogs.add(cs); } if (sr != null) { forwardLogs.add(sr); } if (async != null) { forwardLogs.add(async); } if (cr != null) { backwardLogs.add(cr); } if (ss != null) { backwardLogs.add(ss); } if (s.getChilds() != null) { List<String> sortedChilds = s.getChilds().stream().sorted((spanId1, spanId2) -> { Span span1 = spans.get(spanId1); Span span2 = spans.get(spanId2); HashMap<String, String> sr1 = null; HashMap<String, String> sr2 = null; Iterator<HashMap<String, String>> ite1 = span1.getLogs().iterator(); while (ite1.hasNext()) { HashMap<String, String> log1 = ite1.next(); if ("cs".equals(log1.get("type"))) { sr1 = log1; } else if ("sr".equals(log1.get("type"))) { sr1 = log1; } else if ("async".equals(log1.get("type"))) { sr1 = log1; } } Iterator<HashMap<String, String>> ite2 = span2.getLogs().iterator(); while (ite2.hasNext()) { HashMap<String, String> log2 = ite2.next(); if ("cs".equals(log2.get("type"))) { sr2 = log2; } else if ("sr".equals(log2.get("type"))) { sr2 = log2; } else if ("async".equals(log2.get("type"))) { sr2 = log2; } } // System.out.println("sr1:"+sr1.get("timestamp")); // System.out.println("sr2:"+sr2.get("timestamp")); Long time1 = Long.valueOf(sr1.get("timestamp")); Long time2 = Long.valueOf(sr2.get("timestamp")); return time1.compareTo(time2); }).collect(Collectors.toList()); // Iterator<String> iterator1 = sortedChilds.iterator(); // List<HashMap<String,String>> childsLogs = new ArrayList<HashMap<String,String>>(); // // while(iterator1.hasNext()){ // List<HashMap<String,String>> childForwardLogs = new ArrayList<HashMap<String,String>>(); // List<HashMap<String,String>> childBackwardLogs = new ArrayList<HashMap<String,String>>(); // String childId = iterator1.next(); // traverse(spans.get(childId), childForwardLogs, childBackwardLogs, spans); // childsLogs.addAll(mergeForwardAndBackwardLogs(childForwardLogs,childBackwardLogs)); // } // forwardLogs.addAll(childsLogs); Iterator<String> iterator1 = sortedChilds.iterator(); List<List<HashMap<String, String>>> childLogLists = new ArrayList<List<HashMap<String, String>>>(); while (iterator1.hasNext()) { List<HashMap<String, String>> childForwardLogs = new ArrayList<HashMap<String, String>>(); List<HashMap<String, String>> childBackwardLogs = new ArrayList<HashMap<String, String>>(); String childId = iterator1.next(); traverse(spans.get(childId), childForwardLogs, childBackwardLogs, spans); childLogLists.add(mergeForwardAndBackwardLogs(childForwardLogs, childBackwardLogs)); } List<HashMap<String, String>> childsLogs = mergeChildLogLists(childLogLists); forwardLogs.addAll(childsLogs); } } private static List<HashMap<String, String>> mergeChildLogLists(List<List<HashMap<String, String>>> childLogLists) { List<HashMap<String, String>> childsLogs = new ArrayList<HashMap<String, String>>(); List<HashMap<String, String>> logs; List<HashMap<String, String>> childLogList; HashMap<String, String> earlist; while (!childLogLists.isEmpty()) { logs = new ArrayList<HashMap<String, String>>(); for (int i = 0, size = childLogLists.size(); i < size; i++) { childLogList = childLogLists.get(i); if (!childLogList.isEmpty()) { logs.add(childLogList.get(0)); } } earlist = findEarliest(logs, childLogLists); childsLogs.add(earlist); for (int i = 0, length = logs.size(); i < length; i++) { if (earlist == logs.get(i)) { childLogList = childLogLists.get(i); childLogList.remove(0); if (childLogList.isEmpty()) { childLogLists.remove(childLogList); } } } } return childsLogs; } private static HashMap<String, String> findEarliest(List<HashMap<String, String>> logs, List<List<HashMap<String, String>>> logLists) { HashMap<String, String> earlist = logs.get(0); List<HashMap<String, String>> logListEarlist = logLists.get(0); Iterator<HashMap<String, String>> iterator1 = logs.iterator(); Iterator<List<HashMap<String, String>>> iterator2 = logLists.iterator(); while (iterator1.hasNext() && iterator2.hasNext()) { HashMap<String, String> log = iterator1.next(); List<HashMap<String, String>> logList = iterator2.next(); if (compareLog(log, earlist, logList, logListEarlist)) { earlist = log; logListEarlist = logList; } } return earlist; } /* log1 happens before log2 return true; log2 happens before log1 return false; */ private static boolean compareLog(HashMap<String, String> log1, HashMap<String, String> log2, List<HashMap<String, String>> logs1, List<HashMap<String, String>> logs2) { long timestamp1 = Long.valueOf(log1.get("timestamp")); long timestamp2 = Long.valueOf(log2.get("timestamp")); String host1 = log1.get("host"); String host2 = log2.get("host"); if (host1.equals(host2)) { if (timestamp1 <= timestamp2) { return true; } else { return false; } } else { Iterator<HashMap<String, String>> iterator1 = logs1.iterator(); Iterator<HashMap<String, String>> iterator2 = logs2.iterator(); HashMap<String, String> log3 = null; HashMap<String, String> log4 = null; //log1 before log3, log3 before log2, then log1 before log2 while (iterator1.hasNext()) { log3 = iterator1.next(); if (host2.equals(log3.get("host"))) { break; } } if (log3 != null) { long timestamp = Long.valueOf(log3.get("timestamp")); if (timestamp <= timestamp2) { return true; } } //log2 before log4, log4 before log1, then log2 before log1 while (iterator2.hasNext()) { log4 = iterator2.next(); if (host1.equals(log4.get("host"))) { break; } } if (log4 != null) { long timestamp = Long.valueOf(log4.get("timestamp")); if (timestamp <= timestamp1) { return false; } } //still can't compare, then just compare timestamp, maybe wrong //but 1->2 or 2->1 both are meaningful if (timestamp1 <= timestamp2) { return true; } else { return false; } } } public static List<HashMap<String, String>> mergeForwardAndBackwardLogs(List<HashMap<String, String>> forwardLogs, List<HashMap<String, String>> backwardLogs) { Stack<HashMap<String, String>> stack = new Stack<HashMap<String, String>>(); backwardLogs.forEach(n -> { stack.push(n); }); while (!stack.isEmpty()) { forwardLogs.add(stack.pop()); } return forwardLogs; } public static List<HashMap<String, String>> clock2(List<HashMap<String, String>> logs) { HashMap<String, HashMap<String, Integer>> clocks = new HashMap<String, HashMap<String, Integer>>(); List<Clock> allClocks = new ArrayList<Clock>(); List<HashMap<String, String>> list = sortLog(logs); list.forEach(n -> { if (clocks.containsKey(n.get("host"))) { HashMap<String, Integer> clock = clocks.get(n.get("host")); if (n.get("src") != null) { HashMap<String, Integer> srcClock = findSrcClock(allClocks, n.get("traceId"), n.get("spanId"), n.get("type"), n.get("queue"), n.get("parentId")); Iterator<Map.Entry<String, Integer>> iterator = srcClock.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); if (clock.get(entry.getKey()) != null) { if (entry.getValue() <= clock.get(entry.getKey())) { //don't change clock } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } clock.put(n.get("host"), clock.get(n.get("host")) + 1); } else { clock.put(n.get("host"), clock.get(n.get("host")) + 1); } n.put("clock", clock.toString()); clocks.put(n.get("host"), clock); allClocks.add(new Clock(n.get("type"), n.get("host"), n.get("src"), n.get("traceId"), n.get("spanId"), n.get("parentId"), (HashMap<String, Integer>) clock.clone())); } else { HashMap<String, Integer> clock = new HashMap<String, Integer>(); if (n.get("src") != null) { HashMap<String, Integer> srcClock = findSrcClock(allClocks, n.get("traceId"), n.get("spanId"), n.get("type"), n.get("queue"), n.get("parentId")); Iterator<Map.Entry<String, Integer>> iterator = srcClock.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); if (clock.get(entry.getKey()) != null) { if (entry.getValue() <= clock.get(entry.getKey())) { //don't change clock } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } clock.put(n.get("host"), 1); } else { clock.put(n.get("host"), 1); } n.put("clock", clock.toString()); clocks.put(n.get("host"), clock); allClocks.add(new Clock(n.get("type"), n.get("host"), n.get("src"), n.get("traceId"), n.get("spanId"), n.get("parentId"), (HashMap<String, Integer>) clock.clone())); } }); list.forEach(n -> { if (n.containsKey("queue")) { n.remove("queue"); } }); return list; } public static List<HashMap<String, String>> clock(List<HashMap<String, String>> logs) { HashMap<String, HashMap<String, Integer>> clocks = new HashMap<String, HashMap<String, Integer>>(); List<HashMap<String, String>> list = logs.stream().sorted((log1, log2) -> { Long time1 = Long.valueOf(log1.get("timestamp")); Long time2 = Long.valueOf(log2.get("timestamp")); return time1.compareTo(time2); }).collect(Collectors.toList()); list.forEach(n -> { if (clocks.containsKey(n.get("host"))) { HashMap<String, Integer> clock = clocks.get(n.get("host")); if (n.get("src") != null) { HashMap<String, Integer> srcClock = (HashMap<String, Integer>) clocks.get(n.get("src")).clone(); Iterator<Map.Entry<String, Integer>> iterator = srcClock.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); if (clock.get(entry.getKey()) != null) { if (entry.getValue() <= clock.get(entry.getKey())) { //don't change clock } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } clock.put(n.get("host"), clock.get(n.get("host")) + 1); } else { clock.put(n.get("host"), clock.get(n.get("host")) + 1); } n.put("clock", clock.toString()); clocks.put(n.get("host"), clock); } else { HashMap<String, Integer> clock = new HashMap<String, Integer>(); if (n.get("src") != null) { HashMap<String, Integer> srcClock = (HashMap<String, Integer>) clocks.get(n.get("src")).clone(); Iterator<Map.Entry<String, Integer>> iterator = srcClock.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); if (clock.get(entry.getKey()) != null) { if (entry.getValue() <= clock.get(entry.getKey())) { //don't change clock } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } else { //update clock clock.put(entry.getKey(), entry.getValue()); } } clock.put(n.get("host"), 1); } else { clock.put(n.get("host"), 1); } n.put("clock", clock.toString()); clocks.put(n.get("host"), clock); } }); return list; } public static String readFile(String path) { File file = new File(path); BufferedReader reader = null; String laststr = ""; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; while ((tempString = reader.readLine()) != null) { laststr = laststr + tempString; // System.out.println("reading"); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } return laststr; } public static boolean write(String path, List<HashMap<String, String>> logs) { File writer = new File(path); BufferedWriter out = null; try { writer.createNewFile(); // 鍒涘缓鏂版枃浠? out = new BufferedWriter(new FileWriter(writer)); Iterator<HashMap<String, String>> iterator = logs.iterator(); while (iterator.hasNext()) { HashMap<String, String> map = iterator.next(); out.write(map.toString() + "\r\n"); } } catch (IOException e) { e.printStackTrace(); return false; } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e1) { } } } return true; } public static boolean writeFile(String path, List<List<HashMap<String, String>>> logs, String dirName, String microserviceName, int testCaseNumber) { File writer = new File(path); System.out.println(dirName); BufferedWriter out = null; try { writer.createNewFile(); out = new BufferedWriter(new FileWriter(writer)); boolean failed = true; Pattern patternFail = Pattern.compile("fail([0-9]+)"); Matcher matcherFail = patternFail.matcher(dirName); int failExecutionNumber = 0; if(matcherFail.find()) { failExecutionNumber = Integer.parseInt(matcherFail.group(1)); failed = true; } Pattern patternSuccess = Pattern.compile("success"); Matcher matcherSuccess = patternSuccess.matcher(dirName); int successExecutionNumber = 1; if(matcherSuccess.find()) failed = false; //截取microserviceName Pattern patternCase = Pattern.compile("case"); Matcher matcherCase = patternCase.matcher(microserviceName); if(matcherCase.find()){ int begin = matcherCase.start(); microserviceName = microserviceName.substring(begin); } Iterator<List<HashMap<String, String>>> iterator1 = logs.iterator(); while (iterator1.hasNext()) { List<HashMap<String, String>> list = iterator1.next(); if (failed) { out.write("\r\n=== " + "TestCase" + testCaseNumber + " " + microserviceName + " Fail execution " + failExecutionNumber + " ===\r\n"); } else { out.write("\r\n=== " + "TestCase" + testCaseNumber + " " + microserviceName + " Success execution " + successExecutionNumber + " ===\r\n"); } Iterator<HashMap<String, String>> iterator = list.iterator(); while (iterator.hasNext()) { HashMap<String, String> map = iterator.next(); out.write("{"); if (map.containsKey("traceId")) { out.write("traceId=" + map.get("traceId") + ", "); } if (map.containsKey("spanId")) { out.write("spanId=" + map.get("spanId") + ", "); } if (map.containsKey("hostName")) { out.write("hostName=" + map.get("hostName") + ", "); } if (map.containsKey("srcName")) { out.write("srcName=" + map.get("srcName") + ", "); } if (map.containsKey("destName")) { out.write("destName=" + map.get("destName") + ", "); } if (map.containsKey("src")) { out.write("src=" + map.get("src") + ", "); } if (map.containsKey("host")) { out.write("host=" + map.get("host") + ", "); } if (map.containsKey("api")) { out.write("api=" + map.get("api") + ", "); } if (map.containsKey("clock")) { String clocks = map.get("clock"); String[] c = clocks.split(","); out.write("clock={"); for (int i = 0, length = c.length; i < length; i++) { c[i] = "\"" + c[i].substring(1, c[i].lastIndexOf("=")) + "\":" + c[i].substring(c[i].lastIndexOf("=") + 1); if (i < length - 1) { out.write(c[i] + ","); } else { out.write(c[i]); } } out.write(", "); } if (map.containsKey("dest")) { out.write("dest=" + map.get("dest") + ", "); } if (map.containsKey("event")) { out.write("event=" + map.get("event") + ", "); } if (map.containsKey("type")) { out.write("type=" + map.get("type") + ", "); } if (map.containsKey("error")) { out.write("error=" + map.get("error") + ", "); } if (map.containsKey("parentId")) { out.write("parentId=" + map.get("parentId") + ", "); } if (map.containsKey("timestamp")) { out.write("timestamp=" + map.get("timestamp") + ", "); } out.write("}\r\n"); } } } catch (IOException e) { e.printStackTrace(); return false; } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e1) { } } } return true; } }
55,100
43.90709
181
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/main/java/org/services/analysis/TraceTranslatorQueue.java
///** // * Created by hh on 2017-07-08. // */ ///** // * Created by Administrator on 2017/7/11. // */ //package org.services.analysis; // //import java.io.*; //import java.util.*; //import java.util.stream.Collectors; //import org.json.JSONArray; //import org.json.JSONException; //import org.json.JSONObject; //import org.services.analysis.Clock; //import org.services.analysis.Span; // ///** // * Created by hh on 2017-07-08. // */ //public class TraceTranslatorQueue { // public static void main(String[] args) throws JSONException { // //// // //// String path = "./sample/trace-error-queue-seq-multi.json"; //// String destPath = "./output/shiviz-error-queue-seq-multi.txt"; // //// String path = "./ts-sample/ts-error-queue/success.json"; //// String destPath = "./ts-output/error-queue/shiviz-error-queue-success.txt"; // // String path = "./ts-sample/ts-external-normal/ts-external-normal.json"; // String destPath = "./ts-output/ts-external-normal/shiviz-external-normal.txt"; // // String traceStr = readFile(path); // JSONArray tracelist = new JSONArray(traceStr); // List<HashMap<String,String>> logs = new ArrayList<HashMap<String, String>>(); // HashMap<String,String> states = new HashMap<String,String>(); // // for (int k = 0; k < tracelist.length(); k++) { // // JSONArray traceobj = tracelist.getJSONArray(k); // // List<HashMap<String, String>> serviceList = new ArrayList<HashMap<String, String>>(); // String traceId = ((JSONObject) traceobj.get(0)).getString("traceId"); // // for (int j = 0; j < traceobj.length(); j++) { // JSONObject spanobj = (JSONObject) traceobj.get(j); // // // String traceId = spanobj.getString("traceId"); // String id = spanobj.getString("id"); // String pid = ""; // if (spanobj.has("parentId")) { // pid = spanobj.getString("parentId"); // } // String name = spanobj.getString("name"); // String time = String.valueOf(spanobj.getLong("timestamp")); // // HashMap<String, String> content = new HashMap<String, String>(); // content.put("traceId" , traceId); // content.put("spanid", id); // content.put("parentid", pid); // content.put("spanname", name); // // // // //annotation // if(spanobj.has("annotations")) { // JSONArray annotations = spanobj.getJSONArray("annotations"); // for (int i = 0; i < annotations.length(); i++) { // JSONObject anno = annotations.getJSONObject(i); // if ("cs".equals(anno.getString("value"))) { // JSONObject endpoint = anno.getJSONObject("endpoint"); // String service = endpoint.getString("serviceName"); // content.put("clientName", service); // String csTime = String.valueOf(anno.getLong("timestamp")); // content.put("csTime", csTime); // } // if ("sr".equals(anno.getString("value"))) { // JSONObject endpoint = anno.getJSONObject("endpoint"); // String service = endpoint.getString("serviceName"); // content.put("serverName", service); // String srTime = String.valueOf(anno.getLong("timestamp")); // content.put("srTime", srTime); // } // if ("ss".equals(anno.getString("value"))) { // JSONObject endpoint = anno.getJSONObject("endpoint"); // String service = endpoint.getString("serviceName"); // content.put("serverName", service); // String ssTime = String.valueOf(anno.getLong("timestamp")); // content.put("ssTime", ssTime); // } // if ("cr".equals(anno.getString("value"))) { // JSONObject endpoint = anno.getJSONObject("endpoint"); // String service = endpoint.getString("serviceName"); // content.put("clientName", service); // String crTime = String.valueOf(anno.getLong("timestamp")); // content.put("crTime", crTime); // } // } // } // // // // //if annotation doesn't exist // if(!spanobj.has("annotations")){ // content.put("time",time); // } // // // //binaryAnnotation //// if (name.contains("message:")) { //// if ("message:input".equals(name)) { //// content.put("api", content.get("service") + "." + "message_received"); //// } //// } else { // JSONArray binaryAnnotations = spanobj.getJSONArray("binaryAnnotations"); // for (int i = 0; i < binaryAnnotations.length(); i++) { // JSONObject anno = binaryAnnotations.getJSONObject(i); // if ("error".equals(anno.getString("key"))) { // content.put("error", anno.getString("value")); // } // if ("mvc.controller.class".equals(anno.getString("key")) // && !"BasicErrorController".equals(anno.getString("value"))) { // String classname = anno.getString("value"); // content.put("classname", classname); // } // if ("mvc.controller.method".equals(anno.getString("key")) // && !"errorHtml".equals(anno.getString("value"))) { // String methodname = anno.getString("value"); // content.put("methodname", methodname); // } // if ("spring.instance_id".equals(anno.getString("key"))) { // String instance_id = anno.getString("value"); // JSONObject endpoint = anno.getJSONObject("endpoint"); // String ipv4 = endpoint.getString("ipv4"); //// String port = String.valueOf(endpoint.get("port")); // // if(content.get("serverName")!=null && instance_id.indexOf(content.get("serverName")) != -1){ // String key = content.get("serverName") + ":" + ipv4; // String new_instance_id; // if(states.containsKey(key)){ // new_instance_id = content.get("serverName") + ":" + states.get(key) + ":" + ipv4; // }else{ // new_instance_id = content.get("serverName") + ":" + ipv4; // } // // content.put("server_instance_id", new_instance_id); // } // if(content.get("clientName")!=null && instance_id.indexOf(content.get("clientName")) != -1){ // String key = content.get("clientName") + ":" + ipv4; // String new_instance_id; // if(states.containsKey(key)){ // new_instance_id = content.get("clientName") + ":" + states.get(key) + ":" + ipv4; // }else{ //// new_instance_id = ipv4 + ":" + content.get("clientName") + ":" + port; // new_instance_id = content.get("clientName") + ":" + ipv4 ; // } // content.put("client_instance_id", new_instance_id); // } // } // if ("http.method".equals(anno.getString("key"))) { // String httpMethod = anno.getString("value"); // content.put("httpMethod", httpMethod); // } // if ("class".equals(anno.getString("key"))) { // String c = anno.getString("value"); // content.put("class", c); // JSONObject endpoint = anno.getJSONObject("endpoint"); // String ipv4 = endpoint.getString("ipv4"); // String port = String.valueOf(endpoint.get("port")); // String serviceName = String.valueOf(endpoint.get("serviceName")); // // String hostId = serviceName + ":" + ipv4 ; // content.put("hostId", hostId); // content.put("serviceName", serviceName); // // } // if ("method".equals(anno.getString("key"))) { // String method = anno.getString("value"); // content.put("method", method); // JSONObject endpoint = anno.getJSONObject("endpoint"); // String ipv4 = endpoint.getString("ipv4"); // String port = String.valueOf(endpoint.get("port")); // String serviceName = String.valueOf(endpoint.get("serviceName")); // // String hostId = serviceName + ":" + ipv4 ; // content.put("hostId", hostId); // content.put("serviceName", serviceName); // } // if ("controller_state".equals(anno.getString("key"))) { // String state = anno.getString("value"); // JSONObject endpoint = anno.getJSONObject("endpoint"); // String ipv4 = endpoint.getString("ipv4"); // String serviceName = String.valueOf(endpoint.get("serviceName")); // content.put("state",state); // content.put("ipv4State",ipv4); // content.put("serviceNameState",serviceName); // states.put(serviceName +":" + ipv4, state); // } // // // } // // // // if(content.get("serverName") != null && (content.get("classname") != null || content.get("methodname") != null)){ // content.put("api", // content.get("serverName") + "." + content.get("classname") + "." + content.get("methodname")); // }else if(content.get("hostId") != null && (content.get("class") != null || content.get("method") != null)){ // content.put("api", // content.get("hostId") + "." + content.get("class") + "." + content.get("method")); // } // if (name.contains("message:")) { // if(content.get("serverName") != null){ // if ("message:input".equals(name)) { // content.put("api", content.get("serverName") + "." + "message_received"); // }else if("message:output".equals(name)){ // content.put("api", content.get("serverName") + "." + "message_received"); // } // }else if(content.get("clientName") != null){ // if ("message:input".equals(name)) { // content.put("api", content.get("clientName") + "." + "message_send"); // }else if("message:output".equals(name)){ // content.put("api", content.get("clientName") + "." + "message_send"); // } // } // } // // // serviceList.add(content); // } // // // serviceList.forEach(n -> { // // if(n.get("csTime") != null){ // HashMap<String,String> log = new HashMap<String,String>(); // log.put("traceId" , n.get("traceId")); // log.put("spanId" , n.get("spanid")); // log.put("parentId" , n.get("parentid")); // log.put("timestamp",n.get("csTime")); // log.put("hostName" , n.get("clientName")); // log.put("host" , n.get("client_instance_id")); // log.put("destName" , n.get("serverName")); // log.put("dest" , n.get("server_instance_id")); // // if(n.get("spanname").contains("message:")){ // log.put("event" , n.get("api")); // }else{ // log.put("event" , ""); // } // if(n.get("spanname").contains("message:")){ // log.put("spanname", n.get("spanname")); // } // // log.put("type", "cs"); // if(null != n.get("api")){ // log.put("api", n.get("api")); // } // if(n.containsKey("error")){ // log.put("error", n.get("error")); // } // logs.add(log); // } // if(n.get("srTime") != null){ // HashMap<String,String> log = new HashMap<String,String>(); // log.put("traceId" , n.get("traceId")); // log.put("spanId" , n.get("spanid")); // log.put("parentId" , n.get("parentid")); // log.put("timestamp",n.get("srTime")); // log.put("hostName" , n.get("serverName")); // log.put("host" , n.get("server_instance_id")); // log.put("srcName" , n.get("clientName")); // log.put("src" , n.get("client_instance_id")); // log.put("event", n.get("api")); // log.put("type", "sr"); // if(n.containsKey("error")){ // log.put("error", n.get("error")); // } // if(n.get("spanname").contains("message:")){ // log.put("spanname", n.get("spanname")); // } // logs.add(log); // } // if(n.get("ssTime") != null){ // HashMap<String,String> log = new HashMap<String,String>(); // log.put("traceId" , n.get("traceId")); // log.put("spanId" , n.get("spanid")); // log.put("parentId" , n.get("parentid")); // log.put("timestamp",n.get("ssTime")); // log.put("hostName" , n.get("serverName")); // log.put("host" , n.get("server_instance_id")); // log.put("destName" , n.get("clientName")); // log.put("dest" , n.get("client_instance_id")); // // log.put("event", n.get("api")); // log.put("type", "ss"); // if(n.containsKey("error")){ // log.put("error", n.get("error")); // } // if(n.get("spanname").contains("message:")){ // log.put("spanname", n.get("spanname")); // } // logs.add(log); // } // if(n.get("crTime") != null){ // HashMap<String,String> log = new HashMap<String,String>(); // log.put("traceId" , n.get("traceId")); // log.put("spanId" , n.get("spanid")); // log.put("parentId" , n.get("parentid")); // log.put("timestamp",n.get("crTime")); // log.put("hostName" , n.get("clientName")); // log.put("host" , n.get("client_instance_id")); // log.put("srcName" , n.get("serverName")); // log.put("src" , n.get("server_instance_id")); // // if(n.get("spanname").contains("message:")){ // log.put("event" , n.get("api")); // }else{ // log.put("event" , ""); // } // if(n.get("spanname").contains("message:")){ // log.put("spanname", n.get("spanname")); // } // // log.put("type", "cr"); // if(n.containsKey("error")){ // log.put("error", n.get("error")); // } // logs.add(log); // } // if(n.get("time") != null){ // HashMap<String,String> log = new HashMap<String,String>(); // log.put("traceId" , n.get("traceId")); // log.put("spanId" , n.get("spanid")); // log.put("parentId" , n.get("parentid")); // log.put("timestamp",n.get("time")); // log.put("hostName" , n.get("serviceName")); // log.put("host" , n.get("hostId")); // log.put("event", n.get("api")); // log.put("type", "inside_payment.async"); // if(n.containsKey("error")){ // log.put("error", n.get("error")); // } // if(n.get("spanname").contains("message:")){ // log.put("spanname", n.get("spanname")); // } // logs.add(log); // } // // // }); // // } // // // // HashMap<String,String> traceIds = new HashMap<String,String>(); // logs.forEach(n -> { // if(!traceIds.containsKey(n.get("traceId"))){ // traceIds.put(n.get("traceId"),""); // } // }); // // List<List<HashMap<String,String>>> list = new ArrayList<List<HashMap<String,String>>>(); // HashMap<List<HashMap<String,String>>, Boolean> failures = new HashMap<List<HashMap<String,String>>, Boolean>(); // traceIds.forEach((n,s) -> { // List l = logs.stream().filter(elem -> { // return n.equals(elem.get("traceId")); // }).collect(Collectors.toList()); // List<HashMap<String,String>> listWithClock = clock2(l); // boolean failed = listWithClock.stream().anyMatch(pl -> pl.containsKey("error")); // failures.put(listWithClock,failed); // list.add(listWithClock); // }); // // // writeFile(destPath, list, failures); // // // // } // // public static HashMap<String,Integer> findSrcClock(List<Clock> allClocks, String traceId, String spanId, String type){ // HashMap<String,Integer> clock = null; // Clock item; // // for(int i= allClocks.size() - 1; i >= 0 ; i--){ // item = allClocks.get(i); // if(item.isSrc(traceId, spanId, type)){ // clock = item.getClock(); // break; // } // } // return (HashMap<String,Integer>)clock.clone(); // } // // // // //sort the log for one trace according to the calling sequences // public static List<HashMap<String,String>> sortLog(List<HashMap<String,String>> logs){ // List<HashMap<String,String>> list = null ; // // HashMap<String,String> log = logs.get(0); // String traceId = log.get("traceId"); // // HashMap<String, Span> spans = new HashMap<String, Span>(); // HashMap<String,List<String>> spanRelation = new HashMap<String, List<String>>(); // logs.forEach(n -> { // String spanId = n.get("spanId"); // if(spans.containsKey(spanId)){ // Span span = spans.get(spanId); // span.addLog(n); // }else{ // Span span = new Span(n.get("traceId"), n.get("spanId"), n.get("parentId")); // span.addLog(n); // spans.put(spanId,span); // } // // if(spanRelation.containsKey(n.get("parentId"))){ // List<String> childs = spanRelation.get(n.get("parentId")); // if(!childs.contains(spanId)){ // childs.add(spanId); // } // }else{ // List<String> childs = new ArrayList<String>(); // childs.add(spanId); // spanRelation.put(n.get("parentId"),childs); // } // }); // // List<HashMap<String,String>> forwardLogs = new ArrayList<HashMap<String,String>>(); // List<HashMap<String,String>> backwardLogs = new ArrayList<HashMap<String,String>>(); // List<Span> sortedSpan = new ArrayList<Span>(); // // Span entrance = spans.get(traceId); // // if(entrance == null){ // Iterator<Map.Entry<String, Span>> entries = spans.entrySet().iterator(); // while(entries.hasNext()){ // Map.Entry<String, Span> entry = entries.next(); // Span span = entry.getValue(); // if(traceId.equals(span.getParentId())){ // entrance = span; // break; // } // } // } // // setChilds(spanRelation,entrance,spans); // // traverse(entrance, forwardLogs, backwardLogs, spans); // // Stack<HashMap<String,String>> stack = new Stack<HashMap<String,String>>(); // backwardLogs.forEach(n ->{ // stack.push(n); // }); // // while(!stack.isEmpty()){ // forwardLogs.add(stack.pop()); // } // // return forwardLogs; // } // // public static void setChilds(HashMap<String,List<String>> spanRelation, Span entrance, HashMap<String, Span> spans){ // Span s = entrance; // // if(spanRelation.containsKey(s.getSpanId())){ // s.setChilds(spanRelation.get(s.getSpanId())); // Iterator<String> iterator = s.getChilds().iterator(); // while(iterator.hasNext()){ // String childId = iterator.next(); // s = spans.get(childId); // setChilds(spanRelation,s,spans); // } // } // } // // public static void traverse(Span entrance, List<HashMap<String,String>> forwardLogs, List<HashMap<String,String>> backwardLogs, HashMap<String, Span> spans){ // //from the entrance to end // Span s = entrance; // // HashMap<String,String> cs = null; // HashMap<String,String> sr = null; // HashMap<String,String> ss = null; // HashMap<String,String> cr = null; // HashMap<String,String> async = null; // // Iterator<HashMap<String,String>> iterator = s.getLogs().iterator(); // while(iterator.hasNext()){ // HashMap<String,String> log1 = iterator.next(); // if("cs".equals(log1.get("type"))){ // cs = log1; // } // if("sr".equals(log1.get("type"))){ // sr = log1; // } // if("ss".equals(log1.get("type"))){ // ss = log1; // } // if("cr".equals(log1.get("type"))){ // cr = log1; // } // if("inside_payment.async".equals(log1.get("type"))){ // async = log1; // } // } // // if(cs != null){ // forwardLogs.add(cs); // } // if(sr != null){ // forwardLogs.add(sr); // } // if(async != null){ // forwardLogs.add(async); // } // if(cr != null){ // backwardLogs.add(cr); // } // if(ss != null){ // backwardLogs.add(ss); // } // // // // if(s.getChilds() != null){ // List<String> sortedChilds = s.getChilds().stream().sorted((spanId1,spanId2) -> { // Span span1 = spans.get(spanId1); // Span span2 = spans.get(spanId2); // // HashMap<String,String> sr1 = null; // HashMap<String,String> sr2 = null; // // Iterator<HashMap<String,String>> ite1 = span1.getLogs().iterator(); // while(ite1.hasNext()){ // HashMap<String,String> log1 = ite1.next(); // if("cs".equals(log1.get("type"))){ // sr1 = log1; // }else if("sr".equals(log1.get("type"))){ // sr1 = log1; // }else if("inside_payment.async".equals(log1.get("type"))){ // sr1 = log1; // } // } // // Iterator<HashMap<String,String>> ite2 = span2.getLogs().iterator(); // while(ite2.hasNext()){ // HashMap<String,String> log2 = ite2.next(); // if("cs".equals(log2.get("type"))){ // sr2 = log2; // }else if("sr".equals(log2.get("type"))){ // sr2 = log2; // }else if("inside_payment.async".equals(log2.get("type"))){ // sr2 = log2; // } // } // // System.out.println("sr1:"+sr1.get("timestamp")); // System.out.println("sr2:"+sr2.get("timestamp")); // Long time1 = Long.valueOf(sr1.get("timestamp")); // Long time2 = Long.valueOf(sr2.get("timestamp")); // return time1.compareTo(time2); // }).collect(Collectors.toList()); // // Iterator<String> iterator1 = sortedChilds.iterator(); // List<HashMap<String,String>> childsLogs = new ArrayList<HashMap<String,String>>(); // // while(iterator1.hasNext()){ // List<HashMap<String,String>> childForwardLogs = new ArrayList<HashMap<String,String>>(); // List<HashMap<String,String>> childBackwardLogs = new ArrayList<HashMap<String,String>>(); // String childId = iterator1.next(); // traverse(spans.get(childId), childForwardLogs, childBackwardLogs, spans); // childsLogs.addAll(mergeForwardAndBackwardLogs(childForwardLogs,childBackwardLogs)); // } // // forwardLogs.addAll(childsLogs); // } // // // } // // public static List<HashMap<String,String>> mergeForwardAndBackwardLogs(List<HashMap<String,String>> forwardLogs, List<HashMap<String,String>> backwardLogs){ // Stack<HashMap<String,String>> stack = new Stack<HashMap<String,String>>(); // backwardLogs.forEach(n ->{ // stack.push(n); // }); // // while(!stack.isEmpty()){ // forwardLogs.add(stack.pop()); // } // // return forwardLogs; // } // // public static List<HashMap<String,String>> clock2(List<HashMap<String,String>> logs){ // HashMap<String,HashMap<String,Integer>> clocks = new HashMap<String,HashMap<String,Integer>>(); // List<Clock> allClocks = new ArrayList<Clock>(); // // List<HashMap<String,String>> list = sortLog(logs); // // list.forEach(n -> { // if(clocks.containsKey(n.get("host"))){ // HashMap<String,Integer> clock = clocks.get(n.get("host")); // // if(n.get("src") != null){ // HashMap<String,Integer> srcClock = findSrcClock(allClocks, n.get("traceId"), n.get("spanId"), n.get("type")); // // Iterator<Map.Entry<String,Integer>> iterator = srcClock.entrySet().iterator(); // while (iterator.hasNext()) { // Map.Entry<String, Integer> entry = iterator.next(); // if(clock.get(entry.getKey()) != null){ // if(entry.getValue() <= clock.get(entry.getKey())){ // //don't change clock // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // } // // clock.put(n.get("host"),clock.get(n.get("host")) +1); // // }else{ // clock.put(n.get("host"),clock.get(n.get("host")) +1); // } // n.put("clock",clock.toString()); // // clocks.put(n.get("host"), clock); // allClocks.add(new Clock(n.get("type"), n.get("host"), n.get("src"), n.get("traceId"), n.get("spanId"), (HashMap<String,Integer>)clock.clone())); // }else{ // HashMap<String,Integer> clock = new HashMap<String,Integer>(); // // if(n.get("src") != null){ // HashMap<String,Integer> srcClock = findSrcClock(allClocks, n.get("traceId"), n.get("spanId"), n.get("type")); // // Iterator<Map.Entry<String,Integer>> iterator = srcClock.entrySet().iterator(); // while (iterator.hasNext()) { // Map.Entry<String, Integer> entry = iterator.next(); // if(clock.get(entry.getKey()) != null){ // if(entry.getValue() <= clock.get(entry.getKey())){ // //don't change clock // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // } // clock.put(n.get("host"),1); // }else{ // clock.put(n.get("host"),1); // } // n.put("clock",clock.toString()); // // clocks.put(n.get("host"), clock); // allClocks.add(new Clock(n.get("type"), n.get("host"), n.get("src"), n.get("traceId"), n.get("spanId"), (HashMap<String,Integer>)clock.clone())); // } // }); // // return list; // } // // public static List<HashMap<String,String>> clock(List<HashMap<String,String>> logs){ // HashMap<String,HashMap<String,Integer>> clocks = new HashMap<String,HashMap<String,Integer>>(); // // List<HashMap<String,String>> list = logs.stream().sorted((log1,log2) -> { // Long time1 = Long.valueOf(log1.get("timestamp")); // Long time2 = Long.valueOf(log2.get("timestamp")); // return time1.compareTo(time2); // }).collect(Collectors.toList()); // // list.forEach(n -> { // if(clocks.containsKey(n.get("host"))){ // HashMap<String,Integer> clock = clocks.get(n.get("host")); // // if(n.get("src") != null){ // HashMap<String,Integer> srcClock = (HashMap<String,Integer>)clocks.get(n.get("src")).clone(); // // Iterator<Map.Entry<String,Integer>> iterator = srcClock.entrySet().iterator(); // while (iterator.hasNext()) { // Map.Entry<String, Integer> entry = iterator.next(); // if(clock.get(entry.getKey()) != null){ // if(entry.getValue() <= clock.get(entry.getKey())){ // //don't change clock // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // } // // clock.put(n.get("host"),clock.get(n.get("host")) +1); // // }else{ // clock.put(n.get("host"),clock.get(n.get("host")) +1); // } // n.put("clock",clock.toString()); // clocks.put(n.get("host"), clock); // }else{ // HashMap<String,Integer> clock = new HashMap<String,Integer>(); // // if(n.get("src") != null){ // HashMap<String,Integer> srcClock = (HashMap<String,Integer>)clocks.get(n.get("src")).clone(); // // Iterator<Map.Entry<String,Integer>> iterator = srcClock.entrySet().iterator(); // while (iterator.hasNext()) { // Map.Entry<String, Integer> entry = iterator.next(); // if(clock.get(entry.getKey()) != null){ // if(entry.getValue() <= clock.get(entry.getKey())){ // //don't change clock // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // }else{ //update clock // clock.put(entry.getKey(),entry.getValue()); // } // } // clock.put(n.get("host"),1); // }else{ // clock.put(n.get("host"),1); // } // n.put("clock",clock.toString()); // clocks.put(n.get("host"), clock); // } // }); // // return list; // } // // // public static String readFile(String path) { // File file = new File(path); // BufferedReader reader = null; // String laststr = ""; // try { // reader = new BufferedReader(new FileReader(file)); // String tempString = null; // while ((tempString = reader.readLine()) != null) { // laststr = laststr + tempString; // System.out.println("reading"); // } // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e1) { // } // } // } // return laststr; // } // // public static boolean write(String path, List<HashMap<String,String>> logs){ // File writer = new File(path); // BufferedWriter out = null; // try{ // writer.createNewFile(); // 鍒涘缓鏂版枃浠? // out = new BufferedWriter(new FileWriter(writer)); // Iterator<HashMap<String,String>> iterator = logs.iterator(); // while(iterator.hasNext()){ // HashMap<String,String> map = iterator.next(); // out.write(map.toString() + "\r\n"); // } // }catch(IOException e){ // e.printStackTrace(); // return false; // }finally{ // if (out != null) { // try { // out.flush(); // out.close(); // } catch (IOException e1) { // } // } // } // // return true; // } // // //// public static boolean writeFile(String path, List<HashMap<String,String>> logs){ //// File writer = new File(path); //// BufferedWriter out = null; //// try{ //// writer.createNewFile(); // 鍒涘缓鏂版枃浠? //// out = new BufferedWriter(new FileWriter(writer)); //// Iterator<HashMap<String,String>> iterator = logs.iterator(); //// while(iterator.hasNext()){ //// HashMap<String,String> map = iterator.next(); //// Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator(); //// out.write("{"); //// while (entries.hasNext()) { //// Map.Entry<String, String> entry = entries.next(); //// if(entry.getKey().equals("clock")){ //// String clocks = entry.getValue(); //// String[] c = clocks.split(","); //// out.write("clock={"); //// for(int i=0,length=c.length; i<length; i++){ //// c[i] = "\"" + c[i].substring(1,c[i].indexOf("=")) + "\":" //// + c[i].substring(c[i].indexOf("=")+1); //// if(i < length-1){ //// out.write(c[i] + ","); //// }else{ //// out.write(c[i]); //// } //// //// } //// out.write(", "); //// //// }else{ //// out.write(entry.toString() + ", "); //// } //// } //// //// out.write("}\r\n"); //// } //// }catch(IOException e){ //// e.printStackTrace(); //// return false; //// }finally{ //// if (out != null) { //// try { //// out.flush(); //// out.close(); //// } catch (IOException e1) { //// } //// } //// } //// //// return true; //// } // //// public static boolean writeFile(String path, List<List<HashMap<String,String>>> logs, HashMap<List<HashMap<String,String>>, Boolean> failures){ //// File writer = new File(path); //// BufferedWriter out = null; //// try{ //// writer.createNewFile(); // 鍒涘缓鏂版枃浠? //// out = new BufferedWriter(new FileWriter(writer)); //// int fail = 0; //// int success = 0; //// //// Iterator<List<HashMap<String,String>>> iterator1 = logs.iterator(); //// while(iterator1.hasNext()){ //// List<HashMap<String,String>> list = iterator1.next(); //// //// boolean failed = failures.get(list); //// if(failed){ //// out.write("\r\n=== Fail execution " + (fail++) + " ===\r\n"); //// }else{ //// out.write("\r\n=== Success execution " + (success++) + " ===\r\n"); //// } //// //// Iterator<HashMap<String,String>> iterator = list.iterator(); //// while(iterator.hasNext()){ //// HashMap<String,String> map = iterator.next(); //// Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator(); //// out.write("{"); //// while (entries.hasNext()) { //// Map.Entry<String, String> entry = entries.next(); //// if(entry.getKey().equals("clock")){ //// String clocks = entry.getValue(); //// String[] c = clocks.split(","); //// out.write("clock={"); //// for(int i=0,length=c.length; i<length; i++){ //// c[i] = "\"" + c[i].substring(1,c[i].lastIndexOf("=")) + "\":" //// + c[i].substring(c[i].lastIndexOf("=")+1); //// if(i < length-1){ //// out.write(c[i] + ","); //// }else{ //// out.write(c[i]); //// } //// //// } //// out.write(", "); //// //// }else{ //// out.write(entry.toString() + ", "); //// } //// } //// //// out.write("}\r\n"); //// } //// } //// //// //// //// }catch(IOException e){ //// e.printStackTrace(); //// return false; //// }finally{ //// if (out != null) { //// try { //// out.flush(); //// out.close(); //// } catch (IOException e1) { //// } //// } //// } //// //// return true; //// } // // public static boolean writeFile(String path, List<List<HashMap<String,String>>> logs, HashMap<List<HashMap<String,String>>, Boolean> failures){ // File writer = new File(path); // BufferedWriter out = null; // try{ // writer.createNewFile(); // 鍒涘缓鏂版枃浠? // out = new BufferedWriter(new FileWriter(writer)); // int fail = 0; // int success = 0; // // Iterator<List<HashMap<String,String>>> iterator1 = logs.iterator(); // while(iterator1.hasNext()){ // List<HashMap<String,String>> list = iterator1.next(); // // boolean failed = failures.get(list); // if(failed){ // out.write("\r\n=== Fail execution " + (fail++) + " ===\r\n"); // }else{ // out.write("\r\n=== Success execution " + (success++) + " ===\r\n"); // } // // Iterator<HashMap<String,String>> iterator = list.iterator(); // while(iterator.hasNext()){ // HashMap<String,String> map = iterator.next(); // out.write("{"); // // // if(map.containsKey("traceId")){ // out.write("traceId="+ map.get("traceId") + ", "); // } // if(map.containsKey("spanId")){ // out.write("spanId="+ map.get("spanId") + ", "); // } // if(map.containsKey("hostName")){ // out.write("hostName="+ map.get("hostName") + ", "); // } // if(map.containsKey("srcName")){ // out.write("srcName="+ map.get("srcName") + ", "); // } // if(map.containsKey("destName")){ // out.write("destName="+ map.get("destName") + ", "); // } // if(map.containsKey("src")){ // out.write("src="+ map.get("src") + ", "); // } // if(map.containsKey("host")){ // out.write("host="+ map.get("host") + ", "); // } // if(map.containsKey("api")){ // out.write("api="+ map.get("api") + ", "); // } // if(map.containsKey("clock")){ // String clocks = map.get("clock"); // String[] c = clocks.split(","); // out.write("clock={"); // for(int i=0,length=c.length; i<length; i++){ // c[i] = "\"" + c[i].substring(1,c[i].lastIndexOf("=")) + "\":" // + c[i].substring(c[i].lastIndexOf("=")+1); // if(i < length-1){ // out.write(c[i] + ","); // }else{ // out.write(c[i]); // } // // } // out.write(", "); // } // if(map.containsKey("dest")){ // out.write("dest="+ map.get("dest") + ", "); // } // if(map.containsKey("event")){ // out.write("event="+ map.get("event") + ", "); // } // if(map.containsKey("type")){ // out.write("type="+ map.get("type") + ", "); // } // if(map.containsKey("error")){ // out.write("error="+ map.get("error") + ", "); // } // if(map.containsKey("parentId")){ // out.write("parentId="+ map.get("parentId") + ", "); // } // if(map.containsKey("timestamp")){ // out.write("timestamp="+ map.get("timestamp") + ", "); // } // // // out.write("}\r\n"); // } // } // // // // }catch(IOException e){ // e.printStackTrace(); // return false; // }finally{ // if (out != null) { // try { // out.flush(); // out.close(); // } catch (IOException e1) { // } // } // } // // return true; // } //}
45,307
43.463199
163
java
train-ticket
train-ticket-master/old-docs/Json2Shiviz/src/test/java/org/services/analysis/AppTest.java
/* * This Java source file was generated by the Gradle 'init' task. */ //package org.services.analysis; // // //import org.junit.Test; //import static org.junit.Assert.*; // //public class AppTest { // @Test public void testAppHasAGreeting() { // App classUnderTest = new App(); // assertNotNull("app should have a greeting", classUnderTest.getGreeting()); // } //}
389
21.941176
84
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/ChainCallable.java
package org.myproject.ms.monitoring; import java.util.concurrent.Callable; public class ChainCallable<V> implements Callable<V> { private final Chainer tracer; private final ItemNamer spanNamer; private final Callable<V> delegate; private final String name; private final Item parent; public ChainCallable(Chainer tracer, ItemNamer spanNamer, Callable<V> delegate) { this(tracer, spanNamer, delegate, null); } public ChainCallable(Chainer tracer, ItemNamer spanNamer, Callable<V> delegate, String name) { this.tracer = tracer; this.spanNamer = spanNamer; this.delegate = delegate; this.name = name; this.parent = tracer.getCurrentSpan(); } @Override public V call() throws Exception { Item span = startSpan(); try { return this.getDelegate().call(); } finally { close(span); } } protected Item startSpan() { return this.tracer.createSpan(getSpanName(), this.parent); } protected String getSpanName() { if (this.name != null) { return this.name; } return this.spanNamer.name(this.delegate, "async"); } protected void close(Item span) { this.tracer.close(span); } protected Item continueSpan(Item span) { return this.tracer.continueSpan(span); } protected Item detachSpan(Item span) { return this.tracer.detach(span); } public Chainer getTracer() { return this.tracer; } public Callable<V> getDelegate() { return this.delegate; } public String getName() { return this.name; } public Item getParent() { return this.parent; } }
1,527
18.341772
95
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/ChainKeys.java
package org.myproject.ms.monitoring; import java.util.Collection; import java.util.LinkedHashSet; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("spring.sleuth.keys") public class ChainKeys { private Http http = new Http(); private Message message = new Message(); private Hystrix hystrix = new Hystrix(); private Async async = new Async(); private Mvc mvc = new Mvc(); public Http getHttp() { return this.http; } public Message getMessage() { return this.message; } public Hystrix getHystrix() { return this.hystrix; } public Async getAsync() { return this.async; } public Mvc getMvc() { return this.mvc; } public void setHttp(Http http) { this.http = http; } public void setMessage(Message message) { this.message = message; } public void setHystrix(Hystrix hystrix) { this.hystrix = hystrix; } public void setAsync(Async async) { this.async = async; } public void setMvc(Mvc mvc) { this.mvc = mvc; } public static class Message { private Payload payload = new Payload(); public Payload getPayload() { return this.payload; } public String getPrefix() { return this.prefix; } public Collection<String> getHeaders() { return this.headers; } public void setPayload(Payload payload) { this.payload = payload; } public void setPrefix(String prefix) { this.prefix = prefix; } public void setHeaders(Collection<String> headers) { this.headers = headers; } public static class Payload { private String size = "message/payload-size"; private String type = "message/payload-type"; public String getSize() { return this.size; } public String getType() { return this.type; } public void setSize(String size) { this.size = size; } public void setType(String type) { this.type = type; } } private String prefix = "message/"; private Collection<String> headers = new LinkedHashSet<String>(); } public static class Http { private String host = "http.host"; private String method = "http.method"; private String path = "http.path"; private String url = "http.url"; private String statusCode = "http.status_code"; private String requestSize = "http.request.size"; private String responseSize = "http.response.size"; private String prefix = "http."; private Collection<String> headers = new LinkedHashSet<String>(); public String getHost() { return this.host; } public String getMethod() { return this.method; } public String getPath() { return this.path; } public String getUrl() { return this.url; } public String getStatusCode() { return this.statusCode; } public String getRequestSize() { return this.requestSize; } public String getResponseSize() { return this.responseSize; } public String getPrefix() { return this.prefix; } public Collection<String> getHeaders() { return this.headers; } public void setHost(String host) { this.host = host; } public void setMethod(String method) { this.method = method; } public void setPath(String path) { this.path = path; } public void setUrl(String url) { this.url = url; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public void setRequestSize(String requestSize) { this.requestSize = requestSize; } public void setResponseSize(String responseSize) { this.responseSize = responseSize; } public void setPrefix(String prefix) { this.prefix = prefix; } public void setHeaders(Collection<String> headers) { this.headers = headers; } } public static class Hystrix { private String prefix = ""; private String commandKey = "commandKey"; private String commandGroup = "commandGroup"; private String threadPoolKey = "threadPoolKey"; public String getPrefix() { return this.prefix; } public String getCommandKey() { return this.commandKey; } public String getCommandGroup() { return this.commandGroup; } public String getThreadPoolKey() { return this.threadPoolKey; } public void setPrefix(String prefix) { this.prefix = prefix; } public void setCommandKey(String commandKey) { this.commandKey = commandKey; } public void setCommandGroup(String commandGroup) { this.commandGroup = commandGroup; } public void setThreadPoolKey(String threadPoolKey) { this.threadPoolKey = threadPoolKey; } } public static class Async { private String prefix = ""; private String threadNameKey = "thread"; private String classNameKey = "class"; private String methodNameKey = "method"; public String getPrefix() { return this.prefix; } public String getThreadNameKey() { return this.threadNameKey; } public String getClassNameKey() { return this.classNameKey; } public String getMethodNameKey() { return this.methodNameKey; } public void setPrefix(String prefix) { this.prefix = prefix; } public void setThreadNameKey(String threadNameKey) { this.threadNameKey = threadNameKey; } public void setClassNameKey(String classNameKey) { this.classNameKey = classNameKey; } public void setMethodNameKey(String methodNameKey) { this.methodNameKey = methodNameKey; } } public static class Mvc { private String controllerClass = "mvc.controller.class"; private String controllerMethod = "mvc.controller.method"; public String getControllerClass() { return this.controllerClass; } public void setControllerClass(String controllerClass) { this.controllerClass = controllerClass; } public String getControllerMethod() { return this.controllerMethod; } public void setControllerMethod(String controllerMethod) { this.controllerMethod = controllerMethod; } } }
5,970
16.158046
75
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/ChainRunnable.java
package org.myproject.ms.monitoring; public class ChainRunnable implements Runnable { private static final String DEFAULT_SPAN_NAME = "async"; private final Chainer tracer; private final ItemNamer spanNamer; private final Runnable delegate; private final String name; private final Item parent; public ChainRunnable(Chainer tracer, ItemNamer spanNamer, Runnable delegate) { this(tracer, spanNamer, delegate, null); } public ChainRunnable(Chainer tracer, ItemNamer spanNamer, Runnable delegate, String name) { this.tracer = tracer; this.spanNamer = spanNamer; this.delegate = delegate; this.name = name; this.parent = tracer.getCurrentSpan(); } @Override public void run() { Item span = startSpan(); try { this.getDelegate().run(); } finally { close(span); } } protected Item startSpan() { return this.tracer.createSpan(getSpanName(), this.parent); } protected String getSpanName() { if (this.name != null) { return this.name; } return this.spanNamer.name(this.delegate, DEFAULT_SPAN_NAME); } protected void close(Item span) { // race conditions - check #447 if (!this.tracer.isTracing()) { this.tracer.continueSpan(span); } this.tracer.close(span); } protected Item continueSpan(Item span) { return this.tracer.continueSpan(span); } protected Item detachSpan(Item span) { if (this.tracer.isTracing()) { return this.tracer.detach(span); } return span; } public Chainer getTracer() { return this.tracer; } public Runnable getDelegate() { return this.delegate; } public String getName() { return this.name; } public Item getParent() { return this.parent; } }
1,677
18.511628
92
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/Chainer.java
package org.myproject.ms.monitoring; import java.util.concurrent.Callable; public interface Chainer extends ItemAccessor { Item createSpan(String name); Item createSpan(String name, Item parent); Item createSpan(String name, Sampler sampler); Item continueSpan(Item span); void addTag(String key, String value); Item detach(Item span); Item close(Item span); <V> Callable<V> wrap(Callable<V> callable); Runnable wrap(Runnable runnable); }
480
12
47
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/DefaultItemNamer.java
package org.myproject.ms.monitoring; import org.springframework.core.annotation.AnnotationUtils; public class DefaultItemNamer implements ItemNamer { @Override public String name(Object object, String defaultValue) { ItemName annotation = AnnotationUtils .findAnnotation(object.getClass(), ItemName.class); String spanName = annotation != null ? annotation.value() : object.toString(); // If there is no overridden toString method we'll put a constant value if (isDefaultToString(object, spanName)) { return defaultValue; } return spanName; } private static boolean isDefaultToString(Object delegate, String spanName) { return (delegate.getClass().getName() + "@" + Integer.toHexString(delegate.hashCode())).equals(spanName); } }
767
27.444444
80
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/Item.java
package org.myproject.ms.monitoring; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class Item implements ItemContext { public static final String SAMPLED_NAME = "X-B3-Sampled"; public static final String PROCESS_ID_NAME = "X-Process-Id"; public static final String PARENT_ID_NAME = "X-B3-ParentSpanId"; public static final String TRACE_ID_NAME = "X-B3-TraceId"; public static final String SPAN_NAME_NAME = "X-Span-Name"; public static final String SPAN_ID_NAME = "X-B3-SpanId"; public static final String SPAN_EXPORT_NAME = "X-Span-Export"; public static final String SPAN_FLAGS = "X-B3-Flags"; public static final String SPAN_BAGGAGE_HEADER_PREFIX = "baggage"; public static final Set<String> SPAN_HEADERS = new HashSet<>( Arrays.asList(SAMPLED_NAME, PROCESS_ID_NAME, PARENT_ID_NAME, TRACE_ID_NAME, SPAN_ID_NAME, SPAN_NAME_NAME, SPAN_EXPORT_NAME)); public static final String SPAN_SAMPLED = "1"; public static final String SPAN_NOT_SAMPLED = "0"; public static final String SPAN_LOCAL_COMPONENT_TAG_NAME = "lc"; public static final String SPAN_ERROR_TAG_NAME = "error"; public static final String CLIENT_RECV = "cr"; // For an outbound RPC call, it should log a "cs" annotation. // If possible, it should log a binary annotation of "sa", indicating the // destination address. public static final String CLIENT_SEND = "cs"; // If an inbound RPC call, it should log a "sr" annotation. // If possible, it should log a binary annotation of "ca", indicating the // caller's address (ex X-Forwarded-For header) public static final String SERVER_RECV = "sr"; public static final String SERVER_SEND = "ss"; public static final String SPAN_PEER_SERVICE_TAG_NAME = "peer.service"; public static final String INSTANCEID = "spring.instance_id"; private final long begin; private long end = 0; private final String name; private final long traceIdHigh; private final long traceId; private List<Long> parents = new ArrayList<>(); private final long spanId; private boolean remote = false; private boolean exportable = true; private final Map<String, String> tags; private final String processId; private final Collection<Log> logs; private final Item savedSpan; @JsonIgnore private final Map<String,String> baggage; // Null means we don't know the start tick, so fallback to time @JsonIgnore private final Long startNanos; private Long durationMicros; // serialized in json so micros precision isn't lost @SuppressWarnings("unused") private Item() { this(-1, -1, "dummy", 0, Collections.<Long>emptyList(), 0, false, false, null); } public Item(Item current, Item savedSpan) { this.begin = current.getBegin(); this.end = current.getEnd(); this.name = current.getName(); this.traceIdHigh = current.getTraceIdHigh(); this.traceId = current.getTraceId(); this.parents = current.getParents(); this.spanId = current.getSpanId(); this.remote = current.isRemote(); this.exportable = current.isExportable(); this.processId = current.getProcessId(); this.tags = current.tags; this.logs = current.logs; this.startNanos = current.startNanos; this.durationMicros = current.durationMicros; this.baggage = current.baggage; this.savedSpan = savedSpan; } @Deprecated public Item(long begin, long end, String name, long traceId, List<Long> parents, long spanId, boolean remote, boolean exportable, String processId) { this(begin, end, name, traceId, parents, spanId, remote, exportable, processId, null); } @Deprecated public Item(long begin, long end, String name, long traceId, List<Long> parents, long spanId, boolean remote, boolean exportable, String processId, Item savedSpan) { this(new SpanBuilder() .begin(begin) .end(end) .name(name) .traceId(traceId) .parents(parents) .spanId(spanId) .remote(remote) .exportable(exportable) .processId(processId) .savedSpan(savedSpan)); } Item(SpanBuilder builder) { if (builder.begin > 0) { // conventionally, 0 indicates unset this.startNanos = null; // don't know the start tick this.begin = builder.begin; } else { this.startNanos = nanoTime(); this.begin = System.currentTimeMillis(); } if (builder.end > 0) { this.end = builder.end; this.durationMicros = (this.end - this.begin) * 1000; } this.name = builder.name != null ? builder.name : ""; this.traceIdHigh = builder.traceIdHigh; this.traceId = builder.traceId; this.parents.addAll(builder.parents); this.spanId = builder.spanId; this.remote = builder.remote; this.exportable = builder.exportable; this.processId = builder.processId; this.savedSpan = builder.savedSpan; this.tags = new ConcurrentHashMap<>(); this.tags.putAll(builder.tags); this.logs = new ConcurrentLinkedQueue<>(); this.logs.addAll(builder.logs); this.baggage = new ConcurrentHashMap<>(); this.baggage.putAll(builder.baggage); } public static SpanBuilder builder() { return new SpanBuilder(); } public synchronized void stop() { if (this.durationMicros == null) { if (this.begin == 0) { throw new IllegalStateException( "Span for " + this.name + " has not been started"); } if (this.end == 0) { this.end = System.currentTimeMillis(); } if (this.startNanos != null) { // set a precise duration this.durationMicros = Math.max(1, (nanoTime() - this.startNanos) / 1000); } else { this.durationMicros = (this.end - this.begin) * 1000; } } } @Deprecated @JsonIgnore public synchronized long getAccumulatedMillis() { return getAccumulatedMicros() / 1000; } @JsonIgnore public synchronized long getAccumulatedMicros() { if (this.durationMicros != null) { return this.durationMicros; } else { // stop() hasn't yet been called if (this.begin == 0) { return 0; } if (this.startNanos != null) { return Math.max(1, (nanoTime() - this.startNanos) / 1000); } else { return (System.currentTimeMillis() - this.begin) * 1000; } } } // Visible for testing @JsonIgnore long nanoTime() { return System.nanoTime(); } @JsonIgnore public synchronized boolean isRunning() { return this.begin != 0 && this.durationMicros == null; } public void tag(String key, String value) { if (StringUtils.hasText(value)) { this.tags.put(key, value); } } public void logEvent(String event) { logEvent(System.currentTimeMillis(), event); } public void logEvent(long timestampMilliseconds, String event) { this.logs.add(new Log(timestampMilliseconds, event)); } public Item setBaggageItem(String key, String value) { this.baggage.put(key, value); return this; } public String getBaggageItem(String key) { return this.baggage.get(key); } @Override public final Iterable<Map.Entry<String,String>> baggageItems() { return this.baggage.entrySet(); } public final Map<String,String> getBaggage() { return Collections.unmodifiableMap(this.baggage); } public Map<String, String> tags() { return Collections.unmodifiableMap(new LinkedHashMap<>(this.tags)); } public List<Log> logs() { return Collections.unmodifiableList(new ArrayList<>(this.logs)); } @JsonIgnore public Item getSavedSpan() { return this.savedSpan; } public boolean hasSavedSpan() { return this.savedSpan != null; } public String getName() { return this.name; } public long getSpanId() { return this.spanId; } public long getTraceIdHigh() { return this.traceIdHigh; } public long getTraceId() { return this.traceId; } public String getProcessId() { return this.processId; } public List<Long> getParents() { return this.parents; } public boolean isRemote() { return this.remote; } public long getBegin() { return this.begin; } public long getEnd() { return this.end; } public boolean isExportable() { return this.exportable; } public String traceIdString() { if (this.traceIdHigh != 0) { char[] result = new char[32]; writeHexLong(result, 0, this.traceIdHigh); writeHexLong(result, 16, this.traceId); return new String(result); } char[] result = new char[16]; writeHexLong(result, 0, this.traceId); return new String(result); } public SpanBuilder toBuilder() { return builder().from(this); } public static String idToHex(long id) { char[] data = new char[16]; writeHexLong(data, 0, id); return new String(data); } static void writeHexLong(char[] data, int pos, long v) { writeHexByte(data, pos + 0, (byte) ((v >>> 56L) & 0xff)); writeHexByte(data, pos + 2, (byte) ((v >>> 48L) & 0xff)); writeHexByte(data, pos + 4, (byte) ((v >>> 40L) & 0xff)); writeHexByte(data, pos + 6, (byte) ((v >>> 32L) & 0xff)); writeHexByte(data, pos + 8, (byte) ((v >>> 24L) & 0xff)); writeHexByte(data, pos + 10, (byte) ((v >>> 16L) & 0xff)); writeHexByte(data, pos + 12, (byte) ((v >>> 8L) & 0xff)); writeHexByte(data, pos + 14, (byte) (v & 0xff)); } static void writeHexByte(char[] data, int pos, byte b) { data[pos + 0] = HEX_DIGITS[(b >> 4) & 0xf]; data[pos + 1] = HEX_DIGITS[b & 0xf]; } static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static long hexToId(String hexString) { Assert.hasText(hexString, "Can't convert empty hex string to long"); int length = hexString.length(); if (length < 1 || length > 32) throw new IllegalArgumentException("Malformed id: " + hexString); // trim off any high bits int beginIndex = length > 16 ? length - 16 : 0; return hexToId(hexString, beginIndex); } public static long hexToId(String lowerHex, int index) { Assert.hasText(lowerHex, "Can't convert empty hex string to long"); long result = 0; for (int endIndex = Math.min(index + 16, lowerHex.length()); index < endIndex; index++) { char c = lowerHex.charAt(index); result <<= 4; if (c >= '0' && c <= '9') { result |= c - '0'; } else if (c >= 'a' && c <= 'f') { result |= c - 'a' + 10; } else { throw new IllegalArgumentException("Malformed id: " + lowerHex); } } return result; } @Override public String toString() { return "[Trace: " + traceIdString() + ", Span: " + idToHex(this.spanId) + ", Parent: " + getParentIdIfPresent() + ", exportable:" + this.exportable + "]"; } private String getParentIdIfPresent() { return this.getParents().isEmpty() ? "null" : idToHex(this.getParents().get(0)); } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (this.traceIdHigh >>> 32) ^ this.traceIdHigh; h *= 1000003; h ^= (this.traceId >>> 32) ^ this.traceId; h *= 1000003; h ^= (this.spanId >>> 32) ^ this.spanId; h *= 1000003; return h; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Item) { Item that = (Item) o; return (this.traceIdHigh == that.traceIdHigh) && (this.traceId == that.traceId) && (this.spanId == that.spanId); } return false; } public static class SpanBuilder { private long begin; private long end; private String name; private long traceIdHigh; private long traceId; private ArrayList<Long> parents = new ArrayList<>(); private long spanId; private boolean remote; private boolean exportable = true; private String processId; private Item savedSpan; private List<Log> logs = new ArrayList<>(); private Map<String, String> tags = new LinkedHashMap<>(); private Map<String, String> baggage = new LinkedHashMap<>(); SpanBuilder() { } public Item.SpanBuilder begin(long begin) { this.begin = begin; return this; } public Item.SpanBuilder end(long end) { this.end = end; return this; } public Item.SpanBuilder name(String name) { this.name = name; return this; } public Item.SpanBuilder traceIdHigh(long traceIdHigh) { this.traceIdHigh = traceIdHigh; return this; } public Item.SpanBuilder traceId(long traceId) { this.traceId = traceId; return this; } public Item.SpanBuilder parent(Long parent) { this.parents.add(parent); return this; } public Item.SpanBuilder parents(Collection<Long> parents) { this.parents.clear(); this.parents.addAll(parents); return this; } public Item.SpanBuilder log(Log log) { this.logs.add(log); return this; } public Item.SpanBuilder logs(Collection<Log> logs) { this.logs.clear(); this.logs.addAll(logs); return this; } public Item.SpanBuilder tag(String tagKey, String tagValue) { this.tags.put(tagKey, tagValue); return this; } public Item.SpanBuilder tags(Map<String, String> tags) { this.tags.clear(); this.tags.putAll(tags); return this; } public Item.SpanBuilder baggage(String baggageKey, String baggageValue) { this.baggage.put(baggageKey, baggageValue); return this; } public Item.SpanBuilder baggage(Map<String, String> baggage) { this.baggage.putAll(baggage); return this; } public Item.SpanBuilder spanId(long spanId) { this.spanId = spanId; return this; } public Item.SpanBuilder remote(boolean remote) { this.remote = remote; return this; } public Item.SpanBuilder exportable(boolean exportable) { this.exportable = exportable; return this; } public Item.SpanBuilder processId(String processId) { this.processId = processId; return this; } public Item.SpanBuilder savedSpan(Item savedSpan) { this.savedSpan = savedSpan; return this; } public Item.SpanBuilder from(Item span) { return begin(span.begin).end(span.end).name(span.name) .traceIdHigh(span.traceIdHigh).traceId(span.traceId) .parents(span.getParents()).logs(span.logs).tags(span.tags) .spanId(span.spanId).remote(span.remote).exportable(span.exportable) .processId(span.processId).savedSpan(span.savedSpan); } public Item build() { return new Item(this); } @Override public String toString() { return new Item(this).toString(); } } }
14,705
24.311532
98
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/ItemAccessor.java
package org.myproject.ms.monitoring; public interface ItemAccessor { Item getCurrentSpan(); boolean isTracing(); }
128
7.6
36
java
train-ticket
train-ticket-master/old-docs/Lib/ms-monitoring-core/src/main/java/org/myproject/ms/monitoring/ItemAdjuster.java
package org.myproject.ms.monitoring; public interface ItemAdjuster { Item adjust(Item span); }
102
9.3
36
java