Advertisement
Guest User

Untitled

a guest
Jan 15th, 2018
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.54 KB | None | 0 0
  1. /*
  2. * Copyright 2013-2017 Amazon.com,
  3. * Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Licensed under the Amazon Software License (the "License").
  6. * You may not use this file except in compliance with the
  7. * License. A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/asl/
  10. *
  11. * or in the "license" file accompanying this file. This file is
  12. * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, express or implied. See the License
  14. * for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17.  
  18. package com.amazonaws.youruserpools;
  19.  
  20. import android.app.DownloadManager;
  21. import android.app.ProgressDialog;
  22. import android.content.DialogInterface;
  23. import android.content.Intent;
  24. import android.content.pm.ActivityInfo;
  25. import android.os.Bundle;
  26. import android.support.design.widget.NavigationView;
  27. import android.support.v4.widget.DrawerLayout;
  28. import android.support.v7.app.ActionBarDrawerToggle;
  29. import android.support.v7.app.AlertDialog;
  30. import android.support.v7.app.AppCompatActivity;
  31. import android.support.v7.widget.Toolbar;
  32. import android.util.Log;
  33. import android.view.Menu;
  34. import android.view.MenuItem;
  35. import android.view.View;
  36. import android.widget.AdapterView;
  37. import android.widget.ArrayAdapter;
  38. import android.widget.EditText;
  39. import android.widget.ImageView;
  40. import android.widget.LinearLayout;
  41. import android.widget.ListView;
  42. import android.widget.TextView;
  43. import android.widget.Toast;
  44.  
  45. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice;
  46. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser;
  47. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserAttributes;
  48. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails;
  49. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserDetails;
  50. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
  51. import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler;
  52. import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GetDetailsHandler;
  53. import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.UpdateAttributesHandler;
  54. import com.amazonaws.youruserpools.CognitoYourUserPoolsDemo.R;
  55. import com.android.volley.Request;
  56. import com.android.volley.RequestQueue;
  57. import com.android.volley.Response;
  58. import com.android.volley.VolleyError;
  59. import com.android.volley.toolbox.JsonArrayRequest;
  60. import com.android.volley.toolbox.JsonObjectRequest;
  61. import com.android.volley.toolbox.Volley;
  62.  
  63. import org.json.JSONArray;
  64. import org.json.JSONException;
  65. import org.json.JSONObject;
  66.  
  67. import java.util.ArrayList;
  68. import java.util.List;
  69.  
  70. public class UserActivity extends AppCompatActivity {
  71. private final String TAG="UserActivity";
  72.  
  73. private NavigationView nDrawer;
  74. private DrawerLayout mDrawer;
  75. private ActionBarDrawerToggle mDrawerToggle;
  76. private Toolbar toolbar;
  77. private AlertDialog userDialog;
  78. private ProgressDialog waitDialog;
  79. private ListView attributesList;
  80.  
  81. // Cognito user objects
  82. private CognitoUser user;
  83. private CognitoUserSession session;
  84. private CognitoUserDetails details;
  85.  
  86. // User details
  87. private String username;
  88.  
  89. // To track changes to user details
  90. private final List<String> attributesToDelete = new ArrayList<>();
  91.  
  92. @Override
  93. protected void onCreate(Bundle savedInstanceState) {
  94. super.onCreate(savedInstanceState);
  95. setContentView(R.layout.activity_user);
  96. Log.d("t","help us");
  97. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  98.  
  99. // Set toolbar for this screen
  100. toolbar = (Toolbar) findViewById(R.id.main_toolbar);
  101. toolbar.setTitle("");
  102. TextView main_title = (TextView) findViewById(R.id.main_toolbar_title);
  103. main_title.setText("Account");
  104. setSupportActionBar(toolbar);
  105.  
  106. // Set navigation drawer for this screen
  107. mDrawer = (DrawerLayout) findViewById(R.id.user_drawer_layout);
  108. mDrawerToggle = new ActionBarDrawerToggle(this,mDrawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
  109. mDrawer.addDrawerListener(mDrawerToggle);
  110. mDrawerToggle.syncState();
  111.  
  112. nDrawer = (NavigationView) findViewById(R.id.nav_view);
  113. setNavDrawer();
  114. init();
  115. View navigationHeader = nDrawer.getHeaderView(0);
  116. TextView navHeaderSubTitle = (TextView) navigationHeader.findViewById(R.id.textViewNavUserSub);
  117. navHeaderSubTitle.setText(username);
  118. }
  119.  
  120. @Override
  121. public boolean onCreateOptionsMenu(Menu menu) {
  122. // Inflate the menu; this adds items to the action bar if it is present.
  123. getMenuInflater().inflate(R.menu.activity_user_menu, menu);
  124. return true;
  125. }
  126.  
  127. @Override
  128. public boolean onOptionsItemSelected(MenuItem item) {
  129. // Find which menu item was selected
  130. int menuItem = item.getItemId();
  131.  
  132. // Do the task
  133. if(menuItem == R.id.user_update_attribute) {
  134. //updateAllAttributes();
  135. showWaitDialog("Updating...");
  136. getDetails();
  137. return true;
  138. }
  139.  
  140. return super.onOptionsItemSelected(item);
  141. }
  142.  
  143. @Override
  144. public void onBackPressed() {
  145. exit();
  146. }
  147.  
  148. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  149. super.onActivityResult(requestCode, resultCode, data);
  150.  
  151. switch (requestCode) {
  152. case 20:
  153. // Settings
  154. if(resultCode == RESULT_OK) {
  155. boolean refresh = data.getBooleanExtra("refresh", true);
  156. if (refresh) {
  157. showAttributes();
  158. }
  159. }
  160. break;
  161. case 21:
  162. // Verify attributes
  163. if(resultCode == RESULT_OK) {
  164. boolean refresh = data.getBooleanExtra("refresh", true);
  165. if (refresh) {
  166. showAttributes();
  167. }
  168. }
  169. break;
  170. case 22:
  171. // Add attributes
  172. if(resultCode == RESULT_OK) {
  173. boolean refresh = data.getBooleanExtra("refresh", true);
  174. if (refresh) {
  175. showAttributes();
  176. }
  177. }
  178. break;
  179. }
  180. }
  181.  
  182. // Handle when the a navigation item is selected
  183. private void setNavDrawer() {
  184. nDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
  185. @Override
  186. public boolean onNavigationItemSelected(MenuItem item) {
  187. performAction(item);
  188. return true;
  189. }
  190. });
  191. }
  192.  
  193. // Perform the action for the selected navigation item
  194. private void performAction(MenuItem item) {
  195. // Close the navigation drawer
  196. mDrawer.closeDrawers();
  197.  
  198. // Find which item was selected
  199. switch(item.getItemId()) {
  200. case R.id.nav_user_add_attribute:
  201. // Add a new attribute
  202. addAttribute();
  203. break;
  204.  
  205. case R.id.nav_user_change_password:
  206. // Change password
  207. changePassword();
  208. break;
  209. case R.id.nav_user_verify_attribute:
  210. // Confirm new user
  211. // confirmUser();
  212. attributesVerification();
  213. break;
  214. case R.id.nav_user_settings:
  215. // Show user settings
  216. showSettings();
  217. break;
  218. case R.id.nav_user_sign_out:
  219. // Sign out from this account
  220. signOut();
  221. break;
  222. case R.id.nav_user_trusted_devices:
  223. showTrustedDevices();
  224. break;
  225. case R.id.nav_user_about:
  226. // For the inquisitive
  227. Intent aboutAppActivity = new Intent(this, AboutApp.class);
  228. startActivity(aboutAppActivity);
  229. break;
  230. }
  231. }
  232.  
  233. // Get user details from CIP service
  234. private void getDetails() {
  235. AppHelper.getPool().getUser(username).getDetailsInBackground(detailsHandler);
  236. }
  237.  
  238. // Show user attributes from CIP service
  239. private void showAttributes() {
  240.  
  241. /*
  242. final UserAttributesAdapter attributesAdapter = new UserAttributesAdapter(getApplicationContext());
  243. final ListView attributesListView;
  244. attributesListView = (ListView) findViewById(R.id.listViewUserAttributes);
  245. attributesListView.setAdapter(attributesAdapter);
  246. attributesList = attributesListView;
  247.  
  248.  
  249. attributesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  250. @Override
  251. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  252. TextView data = (TextView) view.findViewById(R.id.editTextUserDetailInput);
  253. String attributeType = data.getHint().toString();
  254. String attributeValue = data.getText().toString();
  255. showUserDetail(attributeType, attributeValue);
  256. }
  257. });
  258.  
  259. */
  260. final ListView attributesListView;
  261. attributesListView = (ListView) findViewById(R.id.listViewUserAttributes);
  262. final List<String> your_array_list = new ArrayList<String>();
  263.  
  264.  
  265. final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
  266. this,
  267. android.R.layout.simple_list_item_1,
  268. your_array_list );
  269.  
  270. attributesListView.setAdapter(arrayAdapter);
  271.  
  272. //setContentView(R.layout.activity_user);
  273. final TextView display = (TextView) findViewById(R.id.textViewUserDetailMessage);
  274.  
  275.  
  276.  
  277. //Request
  278. String url = "https://anapioficeandfire.com/api/characters/583";
  279. final String url2 = "https://0d1mc6d1fk.execute-api.us-west-2.amazonaws.com/production/playlists?userId=1";
  280. final String url3 = "https://0d1mc6d1fk.execute-api.us-west-2.amazonaws.com/production/playlists?userId=1&playlistName=";
  281. final RequestQueue queue = Volley.newRequestQueue(this);
  282.  
  283. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
  284. Request.Method.GET,
  285. url2,
  286. null,
  287. new Response.Listener<JSONArray>() {
  288. @Override
  289. public void onResponse(JSONArray response) {
  290. // Do something with response
  291. //mTextView.setText(response.toString());
  292.  
  293. // Process the JSON
  294. try{
  295. // Loop through the array elements
  296. for(int i=0;i<response.length();i++){
  297. // Get current json object
  298. JSONObject student = response.getJSONObject(i);
  299. your_array_list.add(student.getString("playlistName"));
  300. }
  301. }catch (JSONException e){
  302. e.printStackTrace();
  303. }
  304.  
  305. attributesListView.setAdapter(arrayAdapter);
  306.  
  307. attributesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  308. @Override
  309. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  310.  
  311. String playlistname = your_array_list.get(position);
  312.  
  313. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
  314. Request.Method.GET,
  315. url3.concat(playlistname),
  316. null,
  317. new Response.Listener<JSONObject>() {
  318. @Override
  319. public void onResponse(JSONObject response) {
  320. // Do something with response
  321. //mTextView.setText(response.toString());
  322.  
  323. // Process the JSON
  324. try{
  325.  
  326. JSONObject songs = response.getJSONObject("songs");
  327. your_array_list.clear();
  328. for (int i=0; i<songs.names().length(); i++){
  329. your_array_list.add(songs.names().getString(i).toString());
  330.  
  331. }
  332. }catch (JSONException e){
  333. e.printStackTrace();
  334. }
  335. attributesListView.setAdapter(arrayAdapter);
  336. }
  337. },
  338. new Response.ErrorListener(){
  339. @Override
  340. public void onErrorResponse(VolleyError error){
  341. // Do something when error occurred
  342. }
  343. }
  344. );
  345.  
  346. // Add JsonArrayRequest to the RequestQueue
  347. queue.add(jsonObjectRequest);
  348.  
  349. attributesListView.setAdapter(arrayAdapter);
  350. }
  351. });
  352.  
  353. }
  354. },
  355. new Response.ErrorListener(){
  356. @Override
  357. public void onErrorResponse(VolleyError error){
  358. // Do something when error occurred
  359.  
  360. }
  361. }
  362. );
  363.  
  364. // Add JsonArrayRequest to the RequestQueue
  365. queue.add(jsonArrayRequest);
  366.  
  367. }
  368.  
  369. // Update attributes
  370. private void updateAttribute(String attributeType, String attributeValue) {
  371.  
  372. if(attributeType == null || attributeType.length() < 1) {
  373. return;
  374. }
  375. CognitoUserAttributes updatedUserAttributes = new CognitoUserAttributes();
  376. updatedUserAttributes.addAttribute(attributeType, attributeValue);
  377. Toast.makeText(getApplicationContext(), attributeType + ": " + attributeValue, Toast.LENGTH_LONG);
  378. showWaitDialog("Updating...");
  379. AppHelper.getPool().getUser(AppHelper.getCurrUser()).updateAttributesInBackground(updatedUserAttributes, updateHandler);
  380. }
  381.  
  382. // Show user MFA Settings
  383. private void showSettings() {
  384. Intent userSettingsActivity = new Intent(this,SettingsActivity.class);
  385. startActivityForResult(userSettingsActivity, 20);
  386. }
  387.  
  388. // Add a new attribute
  389. private void addAttribute() {
  390. Intent addAttrbutesActivity = new Intent(this,AddAttributeActivity.class);
  391. startActivityForResult(addAttrbutesActivity, 22);
  392. }
  393.  
  394. // Delete attribute
  395. private void deleteAttribute(String attributeName) {
  396. showWaitDialog("Deleting...");
  397. List<String> attributesToDelete = new ArrayList<>();
  398. attributesToDelete.add(attributeName);
  399. AppHelper.getPool().getUser(AppHelper.getCurrUser()).deleteAttributesInBackground(attributesToDelete, deleteHandler);
  400. }
  401.  
  402. // Change user password
  403. private void changePassword() {
  404. Intent changePssActivity = new Intent(this, ChangePasswordActivity.class);
  405. startActivity(changePssActivity);
  406. }
  407.  
  408. // Verify attributes
  409. private void attributesVerification() {
  410. Intent attrbutesActivity = new Intent(this,VerifyActivity.class);
  411. startActivityForResult(attrbutesActivity, 21);
  412. }
  413.  
  414. private void showTrustedDevices() {
  415. Intent trustedDevicesActivity = new Intent(this, DeviceSettings.class);
  416. startActivity(trustedDevicesActivity);
  417. }
  418.  
  419. // Sign out user
  420. private void signOut() {
  421. user.signOut();
  422. exit();
  423. }
  424.  
  425. // Initialize this activity
  426. private void init() {
  427. // Get the user name
  428. Bundle extras = getIntent().getExtras();
  429. username = AppHelper.getCurrUser();
  430. user = AppHelper.getPool().getUser(username);
  431. getDetails();
  432. }
  433.  
  434. GetDetailsHandler detailsHandler = new GetDetailsHandler() {
  435. @Override
  436. public void onSuccess(CognitoUserDetails cognitoUserDetails) {
  437.  
  438. closeWaitDialog();
  439. // Store details in the AppHandler
  440. AppHelper.setUserDetails(cognitoUserDetails);
  441. showAttributes();
  442. // Trusted devices?
  443. handleTrustedDevice();
  444. }
  445.  
  446. @Override
  447. public void onFailure(Exception exception) {
  448. closeWaitDialog();
  449. showDialogMessage("Could not fetch user details!", AppHelper.formatException(exception), true);
  450. }
  451. };
  452.  
  453. private void handleTrustedDevice() {
  454. CognitoDevice newDevice = AppHelper.getNewDevice();
  455. if (newDevice != null) {
  456. AppHelper.newDevice(null);
  457. trustedDeviceDialog(newDevice);
  458. }
  459. }
  460.  
  461. private void updateDeviceStatus(CognitoDevice device) {
  462. device.rememberThisDeviceInBackground(trustedDeviceHandler);
  463. }
  464.  
  465. private void trustedDeviceDialog(final CognitoDevice newDevice) {
  466. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  467. builder.setTitle("Remember this device?");
  468. //final EditText input = new EditText(UserActivity.this);
  469.  
  470. LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
  471. LinearLayout.LayoutParams.MATCH_PARENT,
  472. LinearLayout.LayoutParams.MATCH_PARENT);
  473.  
  474. //input.setLayoutParams(lp);
  475. //input.requestFocus();
  476. //builder.setView(input);
  477.  
  478. builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  479. @Override
  480. public void onClick(DialogInterface dialog, int which) {
  481. try {
  482. //String newValue = input.getText().toString();
  483. showWaitDialog("Remembering this device...");
  484. updateDeviceStatus(newDevice);
  485. userDialog.dismiss();
  486. } catch (Exception e) {
  487. // Log failure
  488. }
  489. }
  490. }).setNegativeButton("No", new DialogInterface.OnClickListener() {
  491. @Override
  492. public void onClick(DialogInterface dialog, int which) {
  493. try {
  494. userDialog.dismiss();
  495. } catch (Exception e) {
  496. // Log failure
  497. }
  498. }
  499. });
  500. userDialog = builder.create();
  501. userDialog.show();
  502. }
  503.  
  504. // Callback handlers
  505.  
  506. UpdateAttributesHandler updateHandler = new UpdateAttributesHandler() {
  507. @Override
  508. public void onSuccess(List<CognitoUserCodeDeliveryDetails> attributesVerificationList) {
  509. // Update successful
  510. if(attributesVerificationList.size() > 0) {
  511. showDialogMessage("Updated", "The updated attributes has to be verified", false);
  512. }
  513. getDetails();
  514. }
  515.  
  516. @Override
  517. public void onFailure(Exception exception) {
  518. // Update failed
  519. closeWaitDialog();
  520. showDialogMessage("Update failed", AppHelper.formatException(exception), false);
  521. }
  522. };
  523.  
  524. GenericHandler deleteHandler = new GenericHandler() {
  525. @Override
  526. public void onSuccess() {
  527. closeWaitDialog();
  528. // Attribute was deleted
  529. Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT);
  530.  
  531. // Fetch user details from the the service
  532. getDetails();
  533. }
  534.  
  535. @Override
  536. public void onFailure(Exception e) {
  537. closeWaitDialog();
  538. // Attribute delete failed
  539. showDialogMessage("Delete failed", AppHelper.formatException(e), false);
  540.  
  541. // Fetch user details from the service
  542. getDetails();
  543. }
  544. };
  545.  
  546. GenericHandler trustedDeviceHandler = new GenericHandler() {
  547. @Override
  548. public void onSuccess() {
  549. // Close wait dialog
  550. closeWaitDialog();
  551. }
  552.  
  553. @Override
  554. public void onFailure(Exception exception) {
  555. closeWaitDialog();
  556. showDialogMessage("Failed to update device status", AppHelper.formatException(exception), true);
  557. }
  558. };
  559.  
  560. private void showUserDetail(final String attributeType, final String attributeValue) {
  561.  
  562. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  563. builder.setTitle(attributeType);
  564. final EditText input = new EditText(UserActivity.this);
  565. input.setText(attributeValue);
  566.  
  567. LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
  568. LinearLayout.LayoutParams.MATCH_PARENT,
  569. LinearLayout.LayoutParams.MATCH_PARENT);
  570.  
  571. input.setLayoutParams(lp);
  572. input.requestFocus();
  573. builder.setView(input);
  574.  
  575. builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
  576. @Override
  577. public void onClick(DialogInterface dialog, int which) {
  578. try {
  579. String newValue = input.getText().toString();
  580. if(!newValue.equals(attributeValue)) {
  581. showWaitDialog("Updating...");
  582. updateAttribute(AppHelper.getSignUpFieldsC2O().get(attributeType), newValue);
  583. }
  584. userDialog.dismiss();
  585. } catch (Exception e) {
  586. // Log failure
  587. }
  588. }
  589. }).setPositiveButton("Delete", new DialogInterface.OnClickListener() {
  590. @Override
  591. public void onClick(DialogInterface dialog, int which) {
  592. try {
  593. userDialog.dismiss();
  594. deleteAttribute(AppHelper.getSignUpFieldsC2O().get(attributeType));
  595. } catch (Exception e) {
  596. // Log failure
  597. }
  598. }
  599. });
  600. userDialog = builder.create();
  601. userDialog.show();
  602. }
  603.  
  604. private void showWaitDialog(String message) {
  605. closeWaitDialog();
  606. waitDialog = new ProgressDialog(this);
  607. waitDialog.setTitle(message);
  608. waitDialog.show();
  609. }
  610.  
  611. private void showDialogMessage(String title, String body, final boolean exit) {
  612. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  613. builder.setTitle(title).setMessage(body).setNeutralButton("OK", new DialogInterface.OnClickListener() {
  614. @Override
  615. public void onClick(DialogInterface dialog, int which) {
  616. try {
  617. userDialog.dismiss();
  618. if(exit) {
  619. exit();
  620. }
  621. } catch (Exception e) {
  622. // Log failure
  623. Log.e(TAG," -- Dialog dismiss failed");
  624. if(exit) {
  625. exit();
  626. }
  627. }
  628. }
  629. });
  630. userDialog = builder.create();
  631. userDialog.show();
  632. }
  633.  
  634. private void closeWaitDialog() {
  635. try {
  636. waitDialog.dismiss();
  637. }
  638. catch (Exception e) {
  639. //
  640. }
  641. }
  642.  
  643. private void exit () {
  644. Intent intent = new Intent();
  645. if(username == null)
  646. username = "";
  647. intent.putExtra("name",username);
  648. setResult(RESULT_OK, intent);
  649. finish();
  650. }
  651. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement