Advertisement
Guest User

Untitled

a guest
Nov 13th, 2016
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.43 KB | None | 0 0
  1. package com.example.wojciech.debitum.not_logged;
  2.  
  3. import android.content.res.Resources;
  4. import android.support.v7.app.AppCompatActivity;
  5.  
  6. import android.os.Bundle;
  7. import android.text.InputFilter;
  8. import android.util.Log;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.widget.Button;
  12. import android.widget.EditText;
  13. import android.widget.TextView;
  14. import android.widget.Toast;
  15.  
  16. import com.example.wojciech.debitum.R;
  17. import com.example.wojciech.debitum.filters.LoginFilter;
  18. import com.example.wojciech.debitum.filters.PasswordFilter;
  19. import com.example.wojciech.debitum.logged.HomeActivity;
  20. import com.example.wojciech.debitum.network.RequestCallback;
  21. import com.example.wojciech.debitum.network.RequestSender;
  22. import com.example.wojciech.debitum.network.RestApi;
  23. import com.example.wojciech.debitum.tools.ActivitySwitcher;
  24. import com.example.wojciech.debitum.tools.ErrorChecker;
  25. import com.example.wojciech.debitum.user.SavedUser;
  26. import com.google.gson.Gson;
  27. import com.google.gson.JsonArray;
  28. import com.google.gson.JsonElement;
  29. import com.google.gson.JsonObject;
  30. import com.google.gson.JsonParser;
  31.  
  32. import org.json.JSONObject;
  33.  
  34. import java.util.HashMap;
  35. import java.util.Map;
  36. import java.util.concurrent.ExecutionException;
  37.  
  38. import static com.example.wojciech.debitum.network.RequestReturnCodes.INCORRECT_DATA;
  39. import static com.example.wojciech.debitum.network.RequestReturnCodes.REQUEST_NO_CONTENT;
  40. import static com.example.wojciech.debitum.network.RequestReturnCodes.REQUEST_OK;
  41.  
  42. /**
  43. * A login screen that offers login via email/password.
  44. */
  45.  
  46. public class LoginActivity extends AppCompatActivity {
  47.  
  48. //map for layout EditText fields
  49. Map<String, TextView> _fields;
  50.  
  51. @Override
  52. protected void onCreate(Bundle saved_instance_state) {
  53. super.onCreate(saved_instance_state);
  54. setContentView(R.layout.activity_login);
  55.  
  56.  
  57. fillActivity();
  58. autoLogin();
  59. }
  60.  
  61. private void fillActivity() {
  62.  
  63. _fields = new HashMap<>();
  64. Resources r = getResources();
  65.  
  66. //pushing fields into map and setting input filters (basic validation)
  67. TextView t = (TextView) findViewById(R.id.login_user_login);
  68. t.setFilters(new InputFilter[]{new LoginFilter(t, r)});
  69. _fields.put(RestApi.LOGIN_KEY, t);
  70.  
  71. t = (EditText) findViewById(R.id.login_user_pass);
  72. t.setFilters(new InputFilter[] {new PasswordFilter(t, r)});
  73. _fields.put(RestApi.PASSWORD_KEY, t);
  74.  
  75. Button confirm = (Button) findViewById(R.id.login_confirm);
  76. Button registration = (Button) findViewById(R.id.login_button_not_registered_yet);
  77. confirm.setOnClickListener(new OnClickListener() {
  78. @Override
  79. public void onClick(View view) {
  80. onLoginAttempt();
  81. }
  82. });
  83. registration.setOnClickListener(new OnClickListener() {
  84. @Override
  85. public void onClick(View view) {
  86. onRegistrationRequest();
  87. }
  88. });
  89. }
  90.  
  91. private void autoLogin() {
  92.  
  93. //check if someone is logged
  94. SavedUser saved_user = new SavedUser(this);
  95. if(!saved_user.getToken().equals("")) {
  96. ActivitySwitcher.switchActivityAndFinish(this, null, HomeActivity.class);
  97. }
  98. }
  99.  
  100. private void onRegistrationRequest() {
  101.  
  102. //switch activity after button click
  103. ActivitySwitcher.switchActivityAndFinish(this, null, RegistrationActivity.class);
  104. }
  105.  
  106. private void onLoginAttempt() {
  107.  
  108. //checking if some field has error
  109. boolean correct = ErrorChecker.checkFieldsCorrectness(_fields, getResources());
  110.  
  111. //checking in database
  112. if(correct && checkDatabaseDataCorrectness()) {
  113. ActivitySwitcher.switchActivityAndFinish(this, null, HomeActivity.class);
  114. }
  115.  
  116. //if data is invalid display error for a while
  117. for (String field : _fields.keySet()) {
  118. ErrorChecker.delayedErrorHide(_fields.get(field));
  119. }
  120. }
  121.  
  122. private boolean checkDatabaseDataCorrectness() {
  123.  
  124. //calling to rest api
  125. Integer result = 0;
  126. final StringBuilder response_content = new StringBuilder();
  127. final JsonObject params = getRequestParams();
  128. RequestCallback callback = new RequestCallback() {
  129. @Override
  130. public Integer doRequest() {
  131. return RestApi.login(params, response_content);
  132. }
  133. };
  134.  
  135. RequestSender sender = new RequestSender(callback);
  136.  
  137. try {
  138. //gathering result from call
  139. result = sender.execute().get();
  140. } catch (InterruptedException e) {
  141. Log.e("TAGS", "Interrupted " + e.toString());
  142. } catch (ExecutionException e) {
  143. Log.e("TAGS", "Execution " + e.toString());
  144. }
  145.  
  146. if(result == REQUEST_OK.value()) {
  147. onCorrectValidation(response_content);
  148. } else if (result == INCORRECT_DATA.value()){
  149. onFailedValidation(response_content);
  150. } else {
  151. Toast.makeText(this, getResources().getString(R.string.error_error_occurred), Toast.LENGTH_LONG).show();
  152. }
  153.  
  154. return result == REQUEST_OK.value();
  155. }
  156.  
  157. private JsonObject getRequestParams() {
  158.  
  159. //pushing required data into json
  160. JsonObject data = new JsonObject();
  161. for(Map.Entry<String, TextView> e : _fields.entrySet()) {
  162. data.addProperty(e.getKey(), e.getValue().getText().toString());
  163. }
  164. return data;
  165. }
  166.  
  167. private void onCorrectValidation(StringBuilder response_content) {
  168.  
  169. //after correct call get auth token from json
  170. JsonObject obj = new JsonParser().parse(response_content.toString()).getAsJsonObject();
  171. SavedUser user = new SavedUser(this);
  172. user.setToken(obj.get(RestApi.TOKEN_KEY).getAsString());
  173. }
  174.  
  175. private void onFailedValidation(StringBuilder response_content) {
  176.  
  177. //on failed validation get error from json and display in correct field
  178. try {
  179. JsonArray arr = new JsonParser().parse(response_content.toString()).getAsJsonArray();
  180. for(int i = 0; i < arr.size(); i ++) {
  181. JsonObject obj = arr.get(i).getAsJsonObject();
  182. String key = obj.get(RestApi.ERROR_PATH).getAsString();
  183. String val = obj.get(RestApi.ERROR_MESSAGE).getAsString();
  184. _fields.get(key).setError(val);
  185. }
  186.  
  187. } catch (Exception e) {
  188. Log.e("TAGS", response_content.toString() + " " + e.toString());
  189. }
  190. }
  191. }
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204.  
  205.  
  206.  
  207.  
  208.  
  209.  
  210.  
  211. //
  212. //public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
  213. //
  214. // /**
  215. // * Id to identity READ_CONTACTS permission request.
  216. // */
  217. // private static final int REQUEST_READ_CONTACTS = 0;
  218. //
  219. // /**
  220. // * A dummy authentication store containing known user names and passwords.
  221. // * TODO: remove after connecting to a real authentication system.
  222. // */
  223. // private static final String[] DUMMY_CREDENTIALS = new String[]{
  224. // "foo@example.com:hello", "bar@example.com:world"
  225. // };
  226. // /**
  227. // * Keep track of the login task to ensure we can cancel it if requested.
  228. // */
  229. // private UserLoginTask mAuthTask = null;
  230. //
  231. // // UI references.
  232. // private AutoCompleteTextView mEmailView;
  233. // private EditText mPasswordView;
  234. // private View mProgressView;
  235. // private View mLoginFormView;
  236. //
  237. // @Override
  238. // protected void onCreate(Bundle savedInstanceState) {
  239. // super.onCreate(savedInstanceState);
  240. // setContentView(R.layout.activity_login);
  241. // // Set up the login form.
  242. // mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
  243. // populateAutoComplete();
  244. //
  245. // mPasswordView = (EditText) findViewById(R.id.password);
  246. // mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  247. // @Override
  248. // public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  249. // if (id == R.id.login || id == EditorInfo.IME_NULL) {
  250. // attemptLogin();
  251. // return true;
  252. // }
  253. // return false;
  254. // }
  255. // });
  256. //
  257. // Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
  258. // mEmailSignInButton.setOnClickListener(new OnClickListener() {
  259. // @Override
  260. // public void onClick(View view) {
  261. // attemptLogin();
  262. // }
  263. // });
  264. //
  265. // mLoginFormView = findViewById(R.id.login_form);
  266. // mProgressView = findViewById(R.id.login_progress);
  267. // }
  268. //
  269. // private void populateAutoComplete() {
  270. // if (!mayRequestContacts()) {
  271. // return;
  272. // }
  273. //
  274. // getLoaderManager().initLoader(0, null, this);
  275. // }
  276. //
  277. // private boolean mayRequestContacts() {
  278. // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
  279. // return true;
  280. // }
  281. // if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
  282. // return true;
  283. // }
  284. // if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
  285. // Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
  286. // .setAction(android.R.string.ok, new View.OnClickListener() {
  287. // @Override
  288. // @TargetApi(Build.VERSION_CODES.M)
  289. // public void onClick(View v) {
  290. // requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
  291. // }
  292. // });
  293. // } else {
  294. // requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
  295. // }
  296. // return false;
  297. // }
  298. //
  299. // /**
  300. // * Callback received when a permissions request has been completed.
  301. // */
  302. // @Override
  303. // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  304. // @NonNull int[] grantResults) {
  305. // if (requestCode == REQUEST_READ_CONTACTS) {
  306. // if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  307. // populateAutoComplete();
  308. // }
  309. // }
  310. // }
  311. //
  312. //
  313. // /**
  314. // * Attempts to sign in or register the account specified by the login form.
  315. // * If there are form errors (invalid email, missing fields, etc.), the
  316. // * errors are presented and no actual login attempt is made.
  317. // */
  318. // private void attemptLogin() {
  319. // if (mAuthTask != null) {
  320. // return;
  321. // }
  322. //
  323. // // Reset errors.
  324. // mEmailView.setError(null);
  325. // mPasswordView.setError(null);
  326. //
  327. // // Store values at the time of the login attempt.
  328. // String email = mEmailView.getText().toString();
  329. // String password = mPasswordView.getText().toString();
  330. //
  331. // boolean cancel = false;
  332. // View focusView = null;
  333. //
  334. // // Check for a valid password, if the user entered one.
  335. // if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
  336. // mPasswordView.setError(getString(R.string.error_invalid_password));
  337. // focusView = mPasswordView;
  338. // cancel = true;
  339. // }
  340. //
  341. // // Check for a valid email address.
  342. // if (TextUtils.isEmpty(email)) {
  343. // mEmailView.setError(getString(R.string.error_field_required));
  344. // focusView = mEmailView;
  345. // cancel = true;
  346. // } else if (!isEmailValid(email)) {
  347. // mEmailView.setError(getString(R.string.error_invalid_email));
  348. // focusView = mEmailView;
  349. // cancel = true;
  350. // }
  351. //
  352. // if (cancel) {
  353. // // There was an error; don't attempt login and focus the first
  354. // // form field with an error.
  355. // focusView.requestFocus();
  356. // } else {
  357. // // Show a progress spinner, and kick off a background task to
  358. // // perform the user login attempt.
  359. // showProgress(true);
  360. // mAuthTask = new UserLoginTask(email, password);
  361. // mAuthTask.execute((Void) null);
  362. // }
  363. // }
  364. //
  365. // private boolean isEmailValid(String email) {
  366. // //TODO: Replace this with your own logic
  367. // return email.contains("@");
  368. // }
  369. //
  370. // private boolean isPasswordValid(String password) {
  371.  
  372. //TODO: Replace this with your own logic
  373.  
  374. // return password.length() > 4;
  375. // }
  376. //
  377. // /**
  378. // * Shows the progress UI and hides the login form.
  379. // */
  380. // @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  381. // private void showProgress(final boolean show) {
  382. // // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  383. // // for very easy animations. If available, use these APIs to fade-in
  384. // // the progress spinner.
  385. // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  386. // int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  387. //
  388. // mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  389. // mLoginFormView.animate().setDuration(shortAnimTime).alpha(
  390. // show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  391. // @Override
  392. // public void onAnimationEnd(Animator animation) {
  393. // mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  394. // }
  395. // });
  396. //
  397. // mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  398. // mProgressView.animate().setDuration(shortAnimTime).alpha(
  399. // show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  400. // @Override
  401. // public void onAnimationEnd(Animator animation) {
  402. // mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  403. // }
  404. // });
  405. // } else {
  406. // // The ViewPropertyAnimator APIs are not available, so simply show
  407. // // and hide the relevant UI components.
  408. // mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
  409. // mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  410. // }
  411. // }
  412. //
  413. // @Override
  414. // public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
  415. // return new CursorLoader(this,
  416. // // Retrieve data rows for the device user's 'profile' contact.
  417. // Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
  418. // ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
  419. //
  420. // // Select only email addresses.
  421. // ContactsContract.Contacts.Data.MIMETYPE +
  422. // " = ?", new String[]{ContactsContract.CommonDataKinds.Email
  423. // .CONTENT_ITEM_TYPE},
  424. //
  425. // // Show primary email addresses first. Note that there won't be
  426. // // a primary email address if the user hasn't specified one.
  427. // ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
  428. // }
  429. //
  430. // @Override
  431. // public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
  432. // List<String> emails = new ArrayList<>();
  433. // cursor.moveToFirst();
  434. // while (!cursor.isAfterLast()) {
  435. // emails.add(cursor.getString(ProfileQuery.ADDRESS));
  436. // cursor.moveToNext();
  437. // }
  438. //
  439. // addEmailsToAutoComplete(emails);
  440. // }
  441. //
  442. // @Override
  443. // public void onLoaderReset(Loader<Cursor> cursorLoader) {
  444. //
  445. // }
  446. //
  447. // private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
  448. // //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
  449. // ArrayAdapter<String> adapter =
  450. // new ArrayAdapter<>(LoginActivity.this,
  451. // android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
  452. //
  453. // mEmailView.setAdapter(adapter);
  454. // }
  455. //
  456. //
  457. // private interface ProfileQuery {
  458. // String[] PROJECTION = {
  459. // ContactsContract.CommonDataKinds.Email.ADDRESS,
  460. // ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
  461. // };
  462. //
  463. // int ADDRESS = 0;
  464. // int IS_PRIMARY = 1;
  465. // }
  466. //
  467. // /**
  468. // * Represents an asynchronous login/registration task used to authenticate
  469. // * the user.
  470. // */
  471. // public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  472. //
  473. // private final String mEmail;
  474. // private final String mPassword;
  475. //
  476. // UserLoginTask(String email, String password) {
  477. // mEmail = email;
  478. // mPassword = password;
  479. // }
  480. //
  481. // @Override
  482. // protected Boolean doInBackground(Void... params) {
  483. // // TODO: attempt authentication against a network service.
  484. //
  485. // try {
  486. // // Simulate network access.
  487. // Thread.sleep(2000);
  488. // } catch (InterruptedException e) {
  489. // return false;
  490. // }
  491. //
  492. // for (String credential : DUMMY_CREDENTIALS) {
  493. // String[] pieces = credential.split(":");
  494. // if (pieces[0].equals(mEmail)) {
  495. // // Account exists, return true if the password matches.
  496. // return pieces[1].equals(mPassword);
  497. // }
  498. // }
  499. //
  500. // // TODO: register the new account here.
  501. // return true;
  502. // }
  503. //
  504. // @Override
  505. // protected void onPostExecute(final Boolean success) {
  506. // mAuthTask = null;
  507. // showProgress(false);
  508. //
  509. // if (success) {
  510. // finish();
  511. // } else {
  512. // mPasswordView.setError(getString(R.string.error_incorrect_password));
  513. // mPasswordView.requestFocus();
  514. // }
  515. // }
  516. //
  517. // @Override
  518. // protected void onCancelled() {
  519. // mAuthTask = null;
  520. // showProgress(false);
  521. // }
  522. // }
  523. //}
  524. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement